1

If we have a function as:

function add(first = second, second) { return first + second;   }

Calling it as:

add(1,2); // returns 3

Above code work fine but if we call it as:

add(undefined, 2); //throws error

I not sure how internally parameters are parsed in ES6, which result in error for the last one.

Ratnesh Lal
  • 319
  • 4
  • 6
  • 17

1 Answers1

3

second is not yet initialised when the default initialiser for first is evaluated, it's still in the temporal dead zone where accessing it will throw despite being in scope.

You should make the second parameter optional:

function add(first, second = first) { return first + second; }
// and call it as
add(2);
add(2, undefined);

If you really want to make the first one optional, you have to do it in the function body:

function add(first, second) { return first + (second === undefined ? first : second); }
Bergi
  • 513,640
  • 108
  • 821
  • 1,164
  • I am not stuck because of this error, i just want to know the behaviour. If you say second is not yet initialised then why in the first case it doesn't throws error!! add(1,2) works great!!! for that reason only i have putted working and not-working example – Ratnesh Lal Sep 27 '16 at 12:50
  • 1
    If you pass anything other than `undefined` (or nothing), the default intialiser is not evaluated at all, so the access to `second` in there doesn't happen and doesn't throw. – Bergi Sep 27 '16 at 14:47