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.length
or using the ||
operator to provide default values - one can also explicitly check the arguments for undefined
via argument2 === undefined
or typeof 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 to false
, which means it might actually be undefined
, null
, false
, 0
, ''
(or anything else for which Boolean(...)
returns false
).
So the question is when to use which check, as they all yield slightly different results.
Checking arguments.length
exhibits the 'most correct' behaviour, but it might not be feasible if there's more than one optional argument.
The test for undefined
is next 'best' - it only 'fails' if the function is explicitly called with an undefined
value, 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.length
is possible by falling through the labels of a switch statement:
function test(requiredArg, optionalArg1, optionalArg2, optionalArg3) {
switch(arguments.length) {
case 1: optionalArg1 = 'default1';
case 2: optionalArg2 = 'default2';
case 3: optionalArg3 = 'default3';
case 4: break;
default: throw new Error('illegal argument count')
}
// do stuff
}
This has the downside that the programmer's intention is not (visually) obvious and uses 'magic numbers'; it is therefore possibly error prone.