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

Vivek Kumar
  • 2,625
  • 2
  • 25
  • 33
  • No, as the `x` in the function is local to the function, your log use the global, which is 10 – Asons Nov 10 '17 at 18:06
  • Cause *var x* is declared first ( due to hoisting )... – Jonas Wilms Nov 10 '17 at 18:07
  • https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript you need to learn about scopes – Alper Fırat Kaya Nov 10 '17 at 18:07
  • 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. – PlayHardGoPro Nov 10 '17 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. – Teemu Nov 10 '17 at 18:14
  • @Teemu I might be wrong but, even with the same name, as the OP used `var` to create a new one. Doesn't all the changes/values/actions regarding that variable take effect only inside that function ? – PlayHardGoPro Nov 10 '17 at 18:18
  • @PlayHardGoPro Yep, but if the `var` wasn't hoisted, the result would be `20` when logging. The execution order of `x = x = 20` is put 20 to (global)x, put 20 to (local)x, but hoisting of `var`ed variable messes up what you see. Block-scoped declaration would trigger an error when meeting a line like this. – Teemu Nov 10 '17 at 18:24
  • 1
    @AlperFıratKaya It's not that simple. Read this if you really want to understand scope and hoisting(http://davidshariff.com/blog/what-is-the-execution-context-in-javascript/#first-article). – Vivek Kumar Nov 10 '17 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. – Teemu Nov 10 '17 at 19:00
  • In `var a = b = 0;`, `b` becomes a global variable, yes. I don't see how this matters though - you have `var a = a = 0`? – Bergi Nov 11 '17 at 13:56

1 Answers1

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.
Ori Drori
  • 183,571
  • 29
  • 224
  • 209