Sunday 26 March 2017

javascript - Why is x undefined in inner scope?





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?


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



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...