6

Assigning a default value using a variable with the same name throw a reference error:

var a = 'adef';
var x = (a=a) => console.log(a);
x();
=> "ReferenceError: a is not defined"

But this is fine:

var other = 'otherdef';
var x = (a=other) => console.log(a);
x();
=> "otherdef"

My assumption was that the value of a in the outer scope would be assigned to the new scope.

I have tried using const instead of var, and class/function instead of an arrow-function, but the result is always the same (tested in chrome 63 and node 6).

I have a feeling the issue is that a is 'hoisted' during assignment and so the assignment is referring to the new 'a' (which exists but is undefined)...

Sam Adams
  • 5,327
  • 2
  • 18
  • 17
  • 1
    Yes, the `a` is indeed [hoisted](https://stackoverflow.com/q/31219420/1048572) in the [parameter scope](https://stackoverflow.com/q/44896829/1048572) – Bergi Dec 15 '17 at 14:09

1 Answers1

0

The purpose of this behavior is to allow a parameter to be default-initialized to the value of another parameter, e.g:

var a = 2;
var x = (a, b = a) => console.log(a, b);
x(42); // 42 42

Making the special case a = a work differently could be done but that would make it harder to refactor functions that use this behavior (you wouldn't be able to rename the parameter a without also renaming the variable that it depends on).

Ghabriel Nunes
  • 372
  • 1
  • 8