JavaScript Functions

Default Values for Arguments

Most programming languages provide a really simple and obvious way to apply default values to arguments of a function. In the function definition where you are defining the arguments most languages allow you to specify the default value byfollowing the argument declaration with an equals sign and the default value. For example in PHP we might have:

function myfunc($arg1, $arg2 = 1) {

With this default specified the function can then be called with either one or two parameters. Where it is called with only one parameter the second argument uses the specified default value (in this example it is set to 1).

JavaScript doesn't allow you to define default argument values this way and so many people do not realise that JavaScript supports default argument values at all. In fact JavaScript does support default values for arguments but the way that you code them is slightly different from the way it is done in all those other languages. While the JavaScript code is not so obvious and somewhat longer to achieve the same result the way that JavaScript handles functions is far more flexible as a result.

The JavaScript version of the PHP example that we have above looks like this:

function myfunc($arg1, $arg2) {
if (typeof $arg2 === 'undefined') $arg2 = 1;

This code produces exactly the same result in JavaScript that the earlier code does in PHP. Where there is no second parameter passed the second argument receives undefined. We simply test inside the function itself if the argument is undefined and if it is we assign the default value we want to use.

Note that to make this comparison between the PHP and JavaScript versions I have used exactly the same argument names in both. In PHP all variable names must start with a $ or they are not variables. In JavvaScript all variables must start with a letter. Fortunately in javaScript as well as a to z and A to Z, the $ is also considered to be a letter and so can be used anywhere in a variable name.

go to previous section go to next section 


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow