JS optional chaining(?.,可選串連)用來讀取物件的屬性或呼叫函式。如果前面的物件或函式是 null 或 undefined,運算式會短路(short-circuit),直接得到 undefined,不會丟出錯誤。
const adventurer = {
name: "Alice",
cat: {
name: "Dinah",
},
};
console.log(adventurer.dog?.name); // undefined
console.log(adventurer.someNonExistentMethod?.()); // undefined
語法
obj?.prop
obj?.[expr]
func?.(args)
obj?.prop:讀取屬性。obj?.[expr]:用方括號讀取屬性,expr的值會被轉成屬性鍵。func?.(args):呼叫函式。
回傳值:obj 或 func 是 null 或 undefined 時回傳 undefined,否則是屬性讀取或函式呼叫的結果。
讀取巢狀屬性
沒有 ?. 時,要讀取很深的屬性,得先逐層確認中間的物件存在,常見寫法是用 &&。但 MDN 指出,這種寫法在中間的值是 0 這類 falsy 值時,結果會是 0,不一定是你要的。用 ?. 只檢查 null 和 undefined:
const obj = { first: 0 };
console.log(obj.first && obj.first.second); // 0
console.log(obj.first?.second); // undefined
obj.first?.second 等於先把 obj.first 存到暫存變數,再判斷它是不是 null 或 undefined,是的話回傳 undefined,否則回傳 temp.second。只是實際上不會產生暫存變數。
?. 可以疊加使用,處理多層的巢狀結構:
const customer = {
name: "Carl",
details: {
age: 82,
location: "Paradise Falls",
},
};
console.log(customer.details?.address?.city); // undefined
console.log(customer.name?.getName?.()); // undefined
customer.details 存在、address 不存在,所以 city 沒有被讀取,結果是 undefined;字串沒有 getName 方法,所以第二行也是 undefined。
呼叫可能不存在的函式
呼叫的函式可能不存在時(例如舊版環境沒有的 API),在括號前加 ?.,函式不存在就回傳 undefined,不會丟出例外。選擇性的回呼函式(callback)也常這樣寫:
function doSomething(onError) {
try {
throw new Error("failed");
} catch (err) {
onError?.(err.message); // onError 是 undefined 時不會出錯
}
}
doSomething(); // 不會丟出錯誤
doSomething((msg) => console.log(msg)); // failed
有兩個限制要注意:
- 如果同名的屬性存在,但不是函式,
?.仍會丟出TypeError。 - 如果物件本身可能是
null或undefined,要在那個位置也加?.,寫成someInterface?.customMethod?.()。
function errorName(fn) {
try {
fn();
return "no error";
} catch (e) {
return e.name;
}
}
const api = { customMethod: 1 };
const empty = null;
console.log(errorName(() => api.customMethod?.())); // TypeError
console.log(errorName(() => empty.customMethod?.())); // TypeError
console.log(errorName(() => empty?.customMethod?.())); // no error
方括號與陣列索引
用方括號讀取屬性時,在括號前加 ?.。這對陣列特別有用,因為陣列索引一定要用方括號:
function printMagicIndex(arr) {
console.log(arr?.[42]);
}
printMagicIndex([0, 1, 2, 3, 4, 5]); // undefined
printMagicIndex(); // undefined
沒有傳入陣列時,若不用 ?.,會因為 undefined 沒有屬性可讀而丟出 TypeError。
短路求值
左邊是 null 或 undefined 時,後面的運算式不會執行。下面 x++ 沒有被計算,所以 x 維持 0:
const potentiallyNullObj = null;
let x = 0;
const prop = potentiallyNullObj?.[x++];
console.log(x); // 0
console.log(prop); // undefined
短路會延續整條屬性串連:potentiallyNullObj?.a.b 在 ?. 處就停止,後面的 .b 不會被計算,所以不會出錯。
但是用括號把串連的一部分包起來,短路就會在括號處結束,後面的屬性存取照常執行:
const potentiallyNullObj = null;
console.log(potentiallyNullObj?.a.b); // undefined
try {
console.log((potentiallyNullObj?.a).b);
} catch (e) {
console.log(e.name); // TypeError
}
搭配空值合併運算子(??)
?. 找不到值時得到 undefined,後面接 ?? 可以提供預設值:
function printCustomerCity(customer) {
const customerCity = customer?.city ?? "Unknown city";
console.log(customerCity);
}
printCustomerCity({ name: "Nathan", city: "Paris" }); // Paris
printCustomerCity({ name: "Carl", details: { age: 82 } }); // Unknown city
?? 的用法請參考它自己的語法文。
不能使用的地方
下列寫法依 MDN 說明是無效的:
- 對
?.的結果賦值,是SyntaxError。 - 把
?.當成範本字面值的標籤(tagged template),是SyntaxError。 - 把
?.用在new運算式的建構函式,是SyntaxError。 - 用在沒有宣告的變數,是
ReferenceError;但根物件的值是undefined時可以用。
function run(code) {
try {
new Function(code)();
return "no error";
} catch (e) {
return e.name;
}
}
console.log(run("const object = {}; object?.property = 1;")); // SyntaxError
console.log(run("String.raw?.`Hello, world!`;")); // SyntaxError
console.log(run("new Map?.();")); // SyntaxError
console.log(run("undeclaredVar?.prop;")); // ReferenceError
注意事項
- 只檢查
null和undefined:0、空字串、false都不會短路。 - 回傳的是
undefined:找不到值時不是null。 - 要加在每個可能是 nullish 的位置:只加在其中一個
?.,其他位置的null仍會出錯。 - 不能賦值:
object?.property = 1是SyntaxError。 - 括號會中斷短路:
(a?.b).c的.c仍會被計算。
支援版本
依 MDN 瀏覽器相容性資料(browser-compat-data 8.1.10,查詢日期 2026-11-24):?. 從 Chrome 80、Edge 80、Firefox 74、Safari 13.1 開始支援,Node.js 從 14.0.0 開始,Deno 從 1.0 開始;Internet Explorer 不支援。
BCD 另註記:Chrome 與 Edge 80 到 90,在可選串連的呼叫中,非最後一個參數使用展開語法會失敗。
補充說明:範例在 Node.js 執行。MDN 的範例是
adventurer、customer、printMagicIndex、短路求值與printCustomerCity,其餘是依 MDN 說明另外示範的。null與undefined的說明請參考各自的語法文。
發佈留言