In ES6, we can use
function f (x, y = 7, z = 42) {
return x + y + z
}
console.log(f(1));
and both Babel and Traceur translate it to similar ES5 code this way:
"use strict";
function f(x) {
var y = arguments.length <= 1 || arguments[1] === undefined ? 7 : arguments[1];
var z = arguments.length <= 2 || arguments[2] === undefined ? 42 : arguments[2];
return x + y + z;
}
console.log(f(1));
isn't it true that we can just handle it, as on http://es6-features.org/#DefaultParameterValues by:
function f (x, y, z) {
if (y === undefined)
y = 7;
if (z === undefined)
z = 42;
return x + y + z;
}
console.log(f(1));
even Mozilla's website uses something like:
var b = typeof b !== 'undefined' ? b : 1;
or a standard answer on SO uses:
function foo(a, b)
{
a = typeof a !== 'undefined' ? a : 42;
b = typeof b !== 'undefined' ? b : 'default_b';
...
}
Why don't we use the short and simple
if (y === undefined)
y = 7;
is there any subtle difference?
(It is true in the global scope, we can't just say a === undefined
if a
was never declared (it would raise an error). But inside of a function, we can just use a === undefined
because a
is listed on the parameter list already. Both Babel and Traceur don't list the default parameter in the parameter list, however.)