Java Reference

In-Depth Information

Parameters and Arguments

Parameters
and
arguments
are often used interchangeably to represent values that are

provided for the function to use. There is a subtle difference though: any parameters a func-

tion needs are set when the function is
defined
. When a function is
invoked
, it is provided

with arguments.

JavaScript does not have a built-in function to square numbers, so we can create one to

demonstrate using parameters. In the example that follows, the
square
function takes one

parameter,
x
, which is the number to be squared. In the body of the function, the name of the

parameter acts like a variable equal to the value that is entered when the function is invoked.

As you can see, it is multiplied by itself and the result is returned by the function:

function square(x){

return x*x;

}

When we invoke this function, we need to provide an argument, which is the number to be

squared:

square(4.5);

<< 20.25

You can use as many parameters as you like when defining functions. For example, the fol-

lowing function finds the mean of any three numbers:

function mean(a,b,c){

return (a+b+c)/3;

}

<< undefined

mean(2, 6, 19);

<< 9

If a parameter is not provided as an argument when the function is invoked, the function

will still be invoked, but the parameter will be given a value of
undefined
. If we try to