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.

2
  • 1
    Which error does it throw? Please post the error message. Commented Sep 27, 2016 at 11:02
  • ERROR: Uncaught ReferenceError: second is not defined Commented Sep 27, 2016 at 12:53

1 Answer 1

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); }
Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.