You have several choices, you have already discovered typeof
. If the data is not going to be falsy unless skipped, you can use a logical OR ||
, the ternary conditional operator a?b:c
or an if
with a logical NOT to check whether to set it or not.
You also have the choice of comparing against undefined or void 0
, both of which will still work even if the parameter is expected to be falsy, with the exception of passing undefined itself as the argument.
function foo(op0, op1, op2, op3, op4, op5, op6) {
// if with logical NOT
if (!op0) op0 = 'default0';
// logical OR
op1 || (op1 = 'default1');
op2 = op2 || 'default2';
// ternary
op3 = op3 ? op3 : 'default3';
// compare, below this line with falsy args too (except explicit `undefined`)
if (op4 === undefined) op4 = 'default4';
if (op5 === void 0) op5 = 'default5';
// compare combined with logical OR
(op6 !== undefined) || (op6 = 'default6');
// log parameters to see what we have now
console.log(op0, op1, op2, op3, op4, op5, op6)
}
foo(); // default0 default1 default2 default3 default4 default5 default6
Please note that in older browsers, undefined
was writeable in the global scope and that in all browsers, if you're not in the global scope, undefined
can be var
d or set as a parameter and so have a value which is not undefined.
If you're not okay with that, choose using the void
operator over undefined.
If you understand that it can happen and don't have to worry about someone shadowing undefined
, feel free to use it.
If you ever see someone do it, ask them if they could var
Array for you too, or something similar, so they realise they have been silly.