0

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.

1
  • Welcome to JavaScript where the interpreter evaluates your expressions out of order. Commented Nov 10, 2017 at 19:04

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

1
var x = x = 20;

is interpreted as

var x;
x = (x = 20);

so global x is not pointed.

Comments

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

Comments

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.