Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does console.log(z) throw NaN?

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(); 
like image 346
Shane Avatar asked Sep 28 '26 19:09

Shane


1 Answers

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.

like image 105
Bergi Avatar answered Oct 02 '26 14:10

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!