3

When it's able to pick up w from the outer scope, why is it not able to pick up z?

var w = 1, z = 2;
function foo( x = w + 1, y = x + 1, z = z + 1 ) {
 console.log( x, y, z );
}
foo(); 
OrangeDog
  • 36,653
  • 12
  • 122
  • 207
Shane
  • 5,517
  • 15
  • 49
  • 79

3 Answers3

5

it's able to pick up w from the outer scope

Yes, because you don't have a variable w inside your function.

why is it not able to pick up z?

Because your parameter declares a local variable with the name z, and that shadows the global one. However, the local one is not yet initialised with a value inside the default expression, and throws a ReferenceError on accessing it. It's like the temporal dead zone for let/const,

let z = z + 1;

would throw as well. You should rename your variable to something else to make it work.

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

The first one works because the w in the w + 1 looks for w in the formal parameters but does not find it and the outer scope is used. Next, The x in the x +1 finds the value for x in formal parameters scope and uses it, so the assignment to y works fine.

In the last case of z + 1, it finds the z as not yet initialized in the formal parameter scope and throws an error before even trying to find it from outer scope.

Changing the variable z to something else as pointed out by @bergi, should do the trick.

var w = 1, z = 2;
function foo( x = w + 1, y = x + 1, a = z + 1 ) {
 console.log( x, y, a );
}
foo(); 
Thalaivar
  • 23,282
  • 5
  • 60
  • 71
0

you have
function foo( x = w + 1, y = x + 1, z = z + 1 )

during x=w+1 x is undfined and then w is undefined also so it look into local execution context didnt find any value so it goes outerscope and find w=1 so in local space w also become 1

now during z = z + 1 the z which is at the left side of = is undefine and then the z which is at the right side of = also undifine so it looks for z inside local execution context and find one the z which was at the left side of the equation so it do not need to go to outer space. so z become undifine

however if you write this way z=this.z+1 you will get z= 3 cause this.z wont look into localscope directly go to outerscope and find z=2

monesul haque
  • 351
  • 1
  • 11