1

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

10
  • No, as the x in the function is local to the function, your log use the global, which is 10 Commented Nov 10, 2017 at 18:06
  • 1
    In the context of var x = 10. Here X is a global variable, right ? Now, inside your z function, its a LOCAL Variable. if you remove the var from your function. It will print 20. Because it will be refering to the global one and not the local variable. Commented Nov 10, 2017 at 18:12
  • 1
    @PlayHardGoPro It's not that simple. According to the operator precedence, OP's code should actually print 20. See Ori Drori's answer. Commented Nov 10, 2017 at 18:14
  • 1
    @AlperFıratKaya It's not that simple. Read this if you really want to understand scope and hoisting(davidshariff.com/blog/…). Commented Nov 10, 2017 at 18:34
  • 1
    @VivekKumar Notice, that in the edited question, var a = b = c = 0; only a is declared, other variables refer to earlier declared variables or to an outer scope. If you want a single line declaration, you use comma to separate the declarees. Commented Nov 10, 2017 at 19:00

1 Answer 1

4

The internal x declaration is hoisted to the top of the function, and overshadows the x of the external scope. Your code actually does this:

var x = 10;

function z(){
  var x;
  x = x = 20;
}
z();
console.log(x); // why is 10 printed? Shouldn’t it be 20.

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

3 Comments

This is a special case, which might be a good addition to the accepted answer in the linked dup ..?
@Teemu - it's more related related to hoisting than scoping.
Well, it messes up the expected scoping (considering the operator precedence), if you're not aware of hoisting.

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.