0

In the following code:

function outer() {
  var x = 'foo';

  function inner() {
    var y = x;     // y == 'foo'
    var x = 'bar'; // x == 'bar', y == undefined
  }
}

Why does the variable y become undefined within inner()? shouldn't it refer to x in outer()?

If the line var x = 'bar'; is removed then y does indeed have the value 'foo'.

Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
jay.lee
  • 19,388
  • 8
  • 39
  • 38

1 Answers1

2

The inner function is interpreted as if it were written like this:

  function inner() {
    var y;
    var x;
    y = x;     // y == undefined
    x = 'bar'; // x == 'bar'
  }

The declarations are hoisted, but the initializations are processed top to bottom. Thus, throughout the entire inner function, the symbols x and y both refer to the variables declared locally in that function; in particular x is the local x, not the one in the enclosing context. When the initializer expression for y is evaluated, therefore, x is the local x, which has not yet been initialized; its initializer expression comes after the initializer for y.

Pointy
  • 405,095
  • 59
  • 585
  • 614