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

// 當函式開始執行,var 會跑到最前面被宣告
function sayHi() {
  phrase = "Hello";

  alert(phrase);

  var phrase;
}
sayHi();

// same
function sayHi() {
  var phrase;

  phrase = "Hello";

  alert(phrase);
}
sayHi();

// same
function sayHi() {
  phrase = "Hello"; // (*)

  if (false) {
    var phrase;
  }

  alert(phrase);
}
sayHi();

// 只有宣告會跑到最前面,儲存值不會。
function sayHi() {
  alert(phrase);

  var phrase = "Hello";
}

sayHi();

Last updated