11

In the code below

var x = 1;

(function () {
  console.log(x);
  var x = 2;
}());

Why is it that when console.log(x), x is undefined?

Chris Hansen
  • 7,813
  • 15
  • 81
  • 165

2 Answers2

10

Variable hoisting. The actual code is executed like this.

var x = 1;
(function() {
    var x; // x = undefined
    console.log(x);
    x = 2;
})();

Edit: On Mr Lister's advice, a bit on variable hoisting. From MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var):

"Variable declarations, wherever they occur, are processed before any code is executed. The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global."

TbWill4321
  • 8,626
  • 3
  • 27
  • 25
  • 2
    Can you explain to the OP what variable hoisting is and why `var x=1; function whatever() {console.log(x);}` does work? – Mr Lister Oct 14 '15 at 19:25
  • I know they can look it up elsewhere, but if would be nice if answers here were self-contained. – Mr Lister Oct 14 '15 at 19:26
  • @TBWill4321 This code when I do it.It gives undefined! – Endrit Shala Oct 14 '15 at 19:35
  • @EndritShala Yes, the question was not "How do I make this code...", it was asking for an explanation of why the code was acting the way it did. The code I posted is identical, just expanded version showing variable hoisting. – TbWill4321 Oct 14 '15 at 19:36
  • @TbWill4321 Oh okay I didn't understand the question because I'm new to english so I didn't understand I tought he asked that he needed to get in console number 2. – Endrit Shala Oct 14 '15 at 19:38
3

Because of the compiler, even if you initiate a var down below the code, the compiler send it to the top, just like var x;, so it first initiate as undefined "x" before running console.log, that's why is such a good practice to initate all vars you're going to use first thing in the function, so these mistakes won't happen.

Kriggs
  • 3,731
  • 1
  • 15
  • 23