iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 24
1
Modern Web

JavaScript 之旅系列 第 24

JavaScript 之旅 (24):Optional Chaining Operator ( ?. 運算子)

本篇介紹 ES2020 (ES11) 提供的 Optional Chaining Operator ( ?. 運算子)。

前言

當你要存取某個變數上的 property 或是呼叫某個函數時,可能會因為該變數為 nullundefined 而拋出 TypeError exception。

而此提案提出的語法可讓短路 (short-circuits) 的寫法更簡潔。

Optional Chaining 運算子的語法 定義如下:

存取 optional property

若有一個變數 user,你假設未來會設為 Object,但在你設定初始值之前就存取其中的 property,就會拋出 TypeError exception:

let user;
console.log(user.address);
// TypeError: Cannot read property 'address' of undefined

大家應該很常遇到吧 XD,新手階段必經之路 QQ

過去你可能會用以下這些作法來檢查 user 是否為 undefinednull,若不是,才能存取其中的 property,這樣就能避開 TypeError exception。但有一些缺點:

  • 每個人的習慣不同,要解決的問題都差不多,但寫法不同,不統一
  • 每次都要寫重複的邏輯,麻煩
let address1;
if (user) {
  address1 = user.address;
}
console.log(address1);
// undefined


let address2 = user && user.address
console.log(address2);
// undefined


let address3 = user != null ? user.address : undefined;
console.log(address3);
// undefined


let address4 = (user !== null && user !== undefined)
  ? user.address
  : undefined;
console.log(address4);
// undefined

所以本篇介紹的 optional chaining 運算子 ?. 就派上用場了!很簡潔吧!

let address = user?.address;
console.log(address);
// undefined

資料來源


上一篇
JavaScript 之旅 (23):Dynamic import()
下一篇
JavaScript 之旅 (25):Nullish Coalescing Operator ( ?? 運算子)
系列文
JavaScript 之旅30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言