Why is x undefined in inner scope?
This question already has an answer here:
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."
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.
上一篇: JavaScript:我可以在切换案例中声明变量吗?
下一篇: 为什么x在内部范围内未定义?