Loose type checking
Easy to write, but 0
, ''
, false
, null
and undefined
will be converted to default value, which might not be expected outcome.
function myFunc(requiredArg, optionalArg) {
optionalArg = optionalArg || 'defaultValue';
}
Strict type checking
Longer, but covers majority of cases. Only case where it incorrectly assigns default value is when we pass undefined
as parameter.
function myFunc(requiredArg, optionalArg) {
optionalArg = typeof optionalArg !== 'undefined' ? optionalArg : 'defaultValue';
}
Checking arguments variable
Catches all cases but is the most clumsy to write.
function myFunc(requiredArg, optionalArg1, optionalArg2) {
optionalArg1 = arguments.length > 1 ? optionalArg1 : 'defaultValue';
optionalArg2 = arguments.length > 2 ? optionalArg2 : 'defaultValue';
}
ES6
Unfortunately this has very poor browser support at the moment
function myFunc(requiredArg, optionalArg = 'defaultValue') {
}