變數提升(Hoisting)讓變數可以「不宣告就使用」或「先用後宣告」,這個設計讓許多人困惑——不只是新手,寫了好幾年 JavaScript 的人一樣會栽。好消息是,ES6 的 let/const 出現後,這類問題基本消失了。
function test() {
alert(notDefined);
}
test();
報錯是理所當然的。

function test() {
alert(declaredButNotAssigned); // undefined
var declaredButNotAssigned;
}
test();
輸出 undefined。結果比上一例「好」——沒報錯、程式跑得下去——但值恐怕不是我們期望的。
function test() {
alert(declaredAndAssigned); // undefined
var declaredAndAssigned = 1;
}
test();
結果與第二例相同。很明顯,賦了值並不會讓它輸出 1。
二、三兩例都發生了提升。簡單的定義是:在指定作用域裡,從程式碼順序看是「先用後宣告」,但執行時該變數的「可訪問性」被提升到當前作用域的頂端,其值為 undefined,並不具備「可用性」。
這裡強調「程式碼順序」與「執行順序」,是因為多數時候我們寫的程式都是順序執行,兩者一致,也符合人的思考方式。有 C 語言經驗的人對此很清楚:
#include <stdio.h>
int main() {
int x = 1;
printf("%d, ", x); // 1
}
先宣告整數 x 再輸出,程式碼順序與執行順序一致,正常運作。順序顛倒過來:
#include <stdio.h>
int main() {
printf("%d, ", x); // error
int x = 1;
}
連編譯都過不了。但在 JavaScript 裡可以反過來寫,於是 C 的經驗搬過來就產生了困惑。
function test() {
alert(func); // undefined
var func = function () { };
}
test();
但若真的想使用它,就行不通了:
function test() {
alert(func); // undefined
func(); // 拋出例外
var func = function () { };
}
test();
這裡可以清楚區分兩個概念:
可訪問性——alert(func) 輸出 undefined,程式能跑,可以存取 func。
可用性——func() 拋出例外,無法正常呼叫,不具可用性。
二、三、四都是 var 宣告的變數。而函數宣告也會提升,只是這個「變數」比較特殊:它是 function 型別(可作為函數、方法或建構子),它的識別字同樣會被提升到當前作用域頂端。
function test() {
alert(f1); // function f1();
f1(); // "called"
function f1() { alert('called'); }
}
test();
宣告 f1 在程式碼最末、使用在前,但 alert(f1) 與 f1() 都正常執行,可見可訪問性與可用性兼具。這也是「提升」經常被拿來考的地方:var 宣告只提升可用性的一半,函數宣告則兩者都提升。
// 題 1
var a = 1;
function fn() {
if (!a) {
var a = 2;
}
alert(a); // ?
}
fn();
fn 內部的 var a 被提升到函數頂端並初始化為 undefined,!undefined 為 true,於是進入 if 指派 2,最終輸出 2。外層那個 a 完全沒被用到。
// 題 2
var a = 1;
function fn() {
a = 2;
return;
function a() { }
}
fn();
alert(a); // ?
函數宣告 a 被完整提升到函數頂端,於是 a = 2 指派的是那個本地函數,而非全域的 a。全域 a 依然是 1,輸出 1。
把 var 換成 let,提升就不復存在:
function test() {
alert(declaredButNotAssigned1); // 拋出例外
alert(declaredButNotAssigned2); // 拋出例外
alert(func); // 拋出例外
let declaredButNotAssigned1;
let declaredButNotAssigned2 = true;
let func = function () { };
}
test();
這強制養成好習慣:變數必須「先宣告再使用」,否則報錯。以下摘自 MDN 對 let 不再發生提升的描述:
In ECMAScript 6, let does not hoist the variable to the top of the block. If you reference a variable in a block before the let declaration for that variable is encountered, this results in a ReferenceError, because the variable is in a "temporal dead zone" from the start of the block until the declaration is processed.
if (condition) {
alert(typeof num); // Error!
let num = 100;
}
以前我們常用 typeof x == 'undefined' 來判斷某個函式庫有沒有被引入,例如:
// 判斷 jQuery 是否已引入
if (typeof $ !== 'undefined') {
// do something
}
jQuery 沒引入時,$ 未宣告,這句話不會報錯,後面的程式照樣執行。但若 $ 是用 let 宣告的,同樣的寫法就會拋出例外。這是在遷移舊程式碼到 let/const 時必須留意的一點。
總結:變數提升是語言實作上的副作用,並非有意設計的優點。養成「先宣告、後使用」的習慣,並在新程式碼中全面採用 let/const,就能徹底避開這一整類問題。