Why is x undefined in inner scope? [duplicate]

In the code below

var x = 1;

(function () {
  var x = 2;

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



Variable hoisting. The actual code is executed like this.

var x = 1;
(function() {
    var x; // x = undefined
    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."


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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.