The old "var"
“var” has no block scope
// var 沒有 {...} 的限制
if (true) {
var test = true; // use "var" instead of "let"
}
alert(test); // true, the variable lives after if
for (var i = 0; i < 10; i++) {
// ...
}
alert(i); // 10, "i" is visible after loop, it's a global variable
// var 在函式內有作用域
function sayHi() {
if (true) {
var phrase = "Hello";
}
alert(phrase); // works
}
sayHi();
alert(phrase); // Error: phrase is not defined (Check the Developer Console)“var” are processed at the function start
Last updated
Was this helpful?