JavaScript Functions

Optional Parameters

There may be times when there is code in a function that is only wanted on some of the calls and not others. This is an obvious situation where an if statement can be used inside of the function and we pass in a parameter to control whether that if statement runs.

function myfunction(y, z, w) {
if (w) {a += y;}
b -= z;

Coding the function this way we can control whether the first parameter actually gets added or not by passing in a third value that is true when we want the addition to take place and false when it is not needed.

This is a somewhat messy way of achieving this result. An easier way is to move the parameter that is not always needed to the end of the parameter list and then test if a value is actually passed into the function in that parameter rather than adding an extra parameter.

function myfunction(z,y) {
if (y!=null) {a += y;}
b -= z;

Now when we don't need to perform the addition, we simply omit the second parameter. We call myfunction(c); instead of myfunction('' , c, true); as would have been needed with the earlier version. JavaScript allows us to do even better than this. It allows a function to process as many parameters as you decide to pass to it. JavaScript provides an alternative way of referencing the arguments within the function without having to give them all names within the function declaration. Here is the same function as we saw in the previous tutorial except that here we don't provide our own names for the arguments. Instead we refer to an internal name that JavaScript automatically allocates to each of the arguments.

Note that JavaScript assigns these internal names as well even when you provide your own names.

function x() {a += arguments[0];
b -= arguments[1];

By using to these generated names for the arguments we can reference as many arguments as we need to based on the number of parameters that are passed to the function.

JavaScript also provides a way to determine exactly how many parameters were passed to the function in another internally generated variable called arguments.length.

go to previous section go to next section 


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow