Why is x undefined in inner scope? [duplicate]

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?

Answers:

Answer

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

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.