k01ken’s b10g

He110 W0r1d!

ES2020(ES11)に関する私的メモ

Null合体演算子(??)

左辺がnullかundefinedであれば、右の値を返し、そうでなければ、左の値を返します。
[使いどころ]
変数がnullやundefinedだった時に初期値を入れることができる。

const a = null ?? 'nullかundefinedです';
const b = undefined ?? 'nullかundefinedです';
const c = (void 0) ?? 'nullかundefinedです';
const d = false ?? 'nullかundefinedです';
console.log(a); // nullかundefinedです
console.log(b); // nullかundefinedです
console.log(c); // nullかundefinedです
console.log(d); // false

■参考リンク
Null 合体 (??)


オプショナルチェイニング演算子

チェーン先がnullish(nullかundefined)であれば、undefinedを返すというもの。エラーにはならず、そこでストップしない。
存在しないルートオブジェクトには使用できません。

// 正規の形
const book_obj = {
  title: 'Hello World',
  price: 1200,
  author_infomation: {
    name: 'JavaScript Taro',
    age: 41
  }
};

// author_infomationプロパティが抜けている不完全な形
const imcomplete_book_obj = {
  title: 'Hello World',
  price: 1200,
}

console.log(book.author_infomation.name);  // Uncaught TypeError: book.author_infomation is undefined
console.log(book.author_infomation?.name); // undefined

//もしオプショナルチェイニング演算子がなければ以下のように、いちいちチェックしないといけなかった。
console.log(book.author_infomation && book.author_infomation.name); // undefined

// 存在しないルートオブジェクトなのでUncaught ReferenceErrorになる
console.log(zock?.author); // Uncaught ReferenceError: zock is not defined

■参考リンク
Optional chaining (?.)