問號點(?.)——JavaScript 的可選串連運算子(Optional chaining operator

Larry Chien
Feb 20, 2022

相信一定有人看過自己的同事用過 ?. 這個 JS 的寫法,不好意思問同事但又不知道要怎麼 google。你不孤單,因為我也是。

Photo by Hitesh Choudhary on Unsplash

串連運算子(Optional chaining operator)是 ES2020 新增的語法糖,用來精簡判斷物件是否存在時的寫法。我們直接來看例子:

const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer.dog?.name;
// 等同於這樣寫
// const dogName = adventurer.dog && adventurer.dog.name;
console.log(dogName);

以這個情境來說,過去在讀取 adventurer.dog.name 之前,需要先判斷 adventurer.dog 是否存在,如果不存在則需要回傳 undefined,或者至少不要出現錯誤,如果沒有先判斷 adventurer.dog 就會出現以下錯誤:

const dogName = adventurer.dog.name;
// 如果不先判斷是否有 adventurer.dog,會出現以下錯誤:
// Uncaught TypeError: Cannot read properties of undefined (reading 'name')
const dogEyeColor = adventurer.dog.eye.color;
// 同理,如果不先判斷是否有 adventurer.dog 及 adventurer.dog.eye,都會出現以下錯誤:
// Uncaught TypeError: Cannot read properties of undefined (reading 'name')

但是每次要抓巢狀物件深層的 value 時,都需要一層一層判斷實在是太麻煩了,因此可以透過可選串連運算子 ?. 來簡化寫法:

const dogName = adventurer.dog?.name;
const dogEyeColor = adventurer.dog?.eye?.color;

如此一來只要 parent 是 undefined 或是 null 的話,就會直接回傳 undefined 而非跳出 Uncaught TypeError

串連運算子(Optional chaining operator)的語法目前主流瀏覽器也已支援,各位讀者下次碰到要取值且要先判斷 parent 是否存在時,可以試著開始使用 ?. 這個好用的語法囉!

Photo by Adi Goldstein on Unsplash

延伸閱讀

如果對於「為什麼這樣寫會出現 TypeError」想更深入了解,可以參考程序猿吃香蕉的《前端開發 🦏 來談 JavaScript 的 Optional Chaining 和 Nullish Coalescing (一)

--

--