I have now seen 2 methods for determining if an argument has been passed to a JavaScript function. I’m wondering if one method is better than the other or if one is just bad to use?
function Test(argument1, argument2) { if (Test.arguments.length == 1) argument2 = 'blah'; alert(argument2); } Test('test');
Or
function Test(argument1, argument2) { argument2 = argument2 || 'blah'; alert(argument2); } Test('test');
As far as I can tell, they both result in the same thing, but I’ve only used the first one before in production.
Another Option as mentioned by Tom:
function Test(argument1, argument2) { if(argument2 === null) { argument2 = 'blah'; } alert(argument2); }
As per Juan’s comment, it would be better to change Tom’s suggestion to:
function Test(argument1, argument2) { if(argument2 === undefined) { argument2 = 'blah'; } alert(argument2); }
There are several different ways to check if an argument was passed to a function. In addition to the two you mentioned in your (original) question – checking
arguments.lengthor using the||operator to provide default values – one can also explicitly check the arguments forundefinedviaargument2 === undefinedortypeof argument2 === 'undefined'if one is paranoid (see comments).Using the
||operator has become standard practice – all the cool kids do it – but be careful: The default value will be triggered if the argument evaluates tofalse, which means it might actually beundefined,null,false,0,''(or anything else for whichBoolean(...)returnsfalse).So the question is when to use which check, as they all yield slightly different results.
Checking
arguments.lengthexhibits the ‘most correct’ behaviour, but it might not be feasible if there’s more than one optional argument.The test for
undefinedis next ‘best’ – it only ‘fails’ if the function is explicitly called with anundefinedvalue, which in all likelyhood should be treated the same way as omitting the argument.The use of the
||operator might trigger usage of the default value even if a valid argument is provided. On the other hand, its behaviour might actually be desired.To summarize: Only use it if you know what you’re doing!
In my opinion, using
||is also the way to go if there’s more than one optional argument and one doesn’t want to pass an object literal as a workaround for named parameters.Another nice way to provide default values using
arguments.lengthis possible by falling through the labels of a switch statement:This has the downside that the programmer’s intention is not (visually) obvious and uses ‘magic numbers’; it is therefore possibly error prone.