2

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.)

Community
  • 1
  • 1
nonopolarity
  • 146,324
  • 131
  • 460
  • 740

2 Answers2

2

Can we just use if (a === undefined) to handle default parameter values in JavaScript before ES6?

Yes, you can do that, it's totally fine.

But you are right, there is a subtle difference (or two):

  • f.length is the ExpectedArgumentCount, that is the number of parameters before the first rest or initialised one.
  • In function f( a=b, b=0 ) the variable b has a temporal dead zone and must not be used by the initialiser of a.

Transpilers like Babel try to replicate things like these as closely as possible, that's why they use the arguments objects and declare the variables in the function body. Btw, Babel fails to handle function f(a=0, b) correctly.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

Yes you can, that's the way I've always done it(roughly 15 years) and it never gives errors. By adding it in the parameter list you always have access to it as a declared variable, and i've never encountered a browser that couldn't handle it.

I prefer to use typeof varname == 'undefined' though, because I've had some issues with === undefined in some obscure browsers in the past.

I always tend to stay as far away as possible from the arguments property as I can.

Tschallacka
  • 27,901
  • 14
  • 88
  • 133