Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book


It would be rather limiting if your functions could only behave in an identical fashion each and every time they were called, as would be the case in the preceding example.

Fortunately, you can extend the capabilities of functions a great deal by passing data to them. You do this when the function is called, by passing to it one or more arguments:


Let’s write a simple function to calculate the cube of a number and display the result:

function cube(x) {
    alert(x * x * x);

Now we can call our function, replacing the variable x with a number. Calling the function like this


results in a dialog box being displayed that contains the result of the calculation, in this case 27.

Of course, you could equally pass a variable name as an argument. The following code would also generate a dialog containing the number 27:

var length = 3;

Multiple Arguments

Functions are not limited to a single argument. When you want to send multiple arguments to a function, all you need to do is separate them with commas:

function times(a, b) {
    alert(a * b);
times(3, 4); // alerts '12'

You can use as many arguments as you want.

It’s important to note that the names given to arguments in the definition of your function have nothing to do with the names of any variables whose values are passed to the function. The variable names in the argument list act like placeholders for the actual values that will be passed when the function is called. The names that you give to arguments are only used inside the function definition to specify how it works.

We talk about this in more detail later in the hour when we discuss variable scope.

  • + Share This
  • 🔖 Save To Your Account