ecmascript 6 - Can we just use "if (a === undefined)" to handle default parameter values in JavaScript before ES6? -
in es6, can use
function f (x, y = 7, z = 42) { return x + y + z } console.log(f(1));
and both babel , traceur translate similar es5 code 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 true can handle it, 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 like:
var b = typeof b !== 'undefined' ? b : 1;
or a standard answer on so uses:
function foo(a, b) { = typeof !== 'undefined' ? : 42; b = typeof b !== 'undefined' ? b : 'default_b'; ... }
why don't use short , simple
if (y === undefined) y = 7;
is there subtle difference?
(it true in global scope, can't a === undefined
if a
never declared (it raise error). inside of function, can use a === undefined
because a
listed on parameter list already. both babel , traceur don't list default parameter in parameter list, however.)
can use
if (a === undefined)
handle default parameter values in javascript before es6?
yes, can that, it's totally fine.
but right, there is subtle difference (or two):
f.length
expectedargumentcount, number of parameters before first rest or initialised one.- in
function f( a=b, b=0 )
variableb
has temporal dead zone , must not used initialiser ofa
.
transpilers babel try replicate things these closely possible, that's why use arguments
objects , declare variables in function body. btw, babel fails handle function f(a=0, b)
correctly.
Comments
Post a Comment