Reputation: 2889
Why does z()
execution context not override global x
variable?
var x = 10;
function z(){
var x = x = 20;
}
z();
console.log(x); // Why is 10 printed? Shouldn’t it be 20.
var a = b = c = 0;
It means b
and c
are being declared as globals, not locals as intended.
For example:
var y = 10;
function z(){
var x = y = 20; // Global y is overridden.
}
z();
console.log(y); // Value is 20.
Going by above logic, x = x = 20
in z()
means x
is global which overrides the local x
variable but still global value of x
is 10
.
Upvotes: 0
Views: 40
Reputation: 63
var x = 10;
function z(){
var x = x = 20;
}
z();
console.log(x)
The local first x. The second x will not be hoisted because we already have x hoisted. So the x will be 20 locally but 10 as global.
For
var y = 10;
function z(){
var x = y = 20; // global y is overridden
}
z();
console.log(y); // value is 20
The x will be hoisted locally but the y will not hoist locally because it is not declared so it will leak to the global scope which is assigned 10. The global scope got changed locally to become 20. So that is why you are getting 10.
Upvotes: 0
Reputation: 85012
function z(){
var x = x = 20;
}
Due to hoisting, this effectively gets turned into:
function z(){
var x;
x = x = 20;
}
So every instance of x in that function is referring to the local variable, not the global variable.
Upvotes: 3
Reputation: 3233
var x = x = 20;
is interpreted as
var x;
x = (x = 20);
so global x is not pointed.
Upvotes: 1