Javascript functions can be passed as few or as many parameters as you like – the exact number of parameters specified in the function declaration is not exactly what must be passed in. This post shows how to set a default value for a parameter if it’s not passed in.
If a parameter is not passed in it will be undefined
The following example illustrates this, where the function takes three parameters and writes out to the document their values:
function foo(a, b, c) { document.write('a: ' + a + ' '); document.write('b: ' + b + ' '); document.write('c: ' + c + ' '); document.write('<br />'); }
To test it:
foo(); foo(1); foo(1, 2); foo(1, 2, 3);
And the result:
a: undefined b: undefined c: undefined a: 1 b: undefined c: undefined a: 1 b: 2 c: undefined a: 1 b: 2 c: 3
The first function call doesn’t pass any parameters, so each is undefined. The second passes just the "a" parameter so that has a value and the others are undefined and so on.
Setting a default value
To specify a default value for a parameter in a Javascript function if it is not passed, check if it is defined and if not set a default value. For example:
function foo(a, b, c) { if(typeof a == 'undefined') { a = 'AAA'; } if(typeof b == 'undefined') { b = 'BBB'; } if(typeof c == 'undefined') { c = 'CCC'; } document.write('a: ' + a + ' '); document.write('b: ' + b + ' '); document.write('c: ' + c + ' '); document.write('<br />'); }
To test it:
foo(); foo(1); foo(1, 2); foo(1, 2, 3);
And the result:
a: AAA b: BBB c: CCC a: 1 b: BBB c: CCC a: 1 b: 2 c: CCC a: 1 b: 2 c: 3
A better solution
Thanks to one of my readers I have learned a better way of setting the default value for a variable and this example here is an update in response to his email. A variable can be assigned a default if no value for it is already set like so in Javascript:
a = a || "AAA";
If it’s undefined then it will be set as "AAA" in the above example. Using this method for my earlier examples looks like this:
function foo(a, b, c) { a = a || "AAA"; b = b || "BBB"; c = c || "CCC"; document.write('a: ' + a + ' '); document.write('b: ' + b + ' '); document.write('c: ' + c + ' '); document.write('<br />'); }
This is a much more compact and readable way of writing the code to set the default values. However, please note that param || "default" will return the default value if param has a value of null, "", 0 or an empty array or object. Thanks to Hans Pufal for pointing this out.