オプショナルチェーン(?.)

(式と演算子)
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Optional_chaining

オプショナルチェーンは、「?.」の前の部分が undefined または null である可能性がある場合に、プログラムの記載を簡単化できるものである。
オブジェクトのプロパティが存在しない場合でも、エラーを起こさずにプロパティを参照できる安全な方法とも言える。

const book = undefined;
const title = book?.title;
console.log(title);
>> undefined

const book = { title: "あいうえおかきくけこ" };
const title = book?.title;
console.log(title);
>> “あいうえおかきくけこ”

オプショナルチェーンはネストして使うこともできる。

const book = undefined;
const authorEmail = book?.author?.email;
console.log(authorEmail);
>> undefined

const book = { author: { email: "alice@example.com" } };
const authorEmail = book?.author?.email;
console.log(authorEmail);
>> “alice@example.com”

もしも?.に先行する変数やプロパティの値がnullまたはundefinedのときは、その先のプロパティは評価されず、undefinedが返る。

const book = null;
console.log(book?.title);
>> undefined

const book = { author: null };
console.log(book.author?.name);
>> undefined

関数を呼び出すときにもオプショナルチェーンが使える。関数に使う場合は、引数カッコの前に?.を書く。

const increment = undefined;
const result = increment?.(1);
console.log(result);
>> undefined

const increment = (n) => n + 1;
const result = increment?.(1);
console.log(result);
>> 2

メソッドを呼び出すときも同様の書き方である。

const book = { getPrice: undefined };
console.log(book.getPrice?.());
>> undefined

const book = {
  getPrice() {
    return 0;
  },
};
console.log(book.getPrice?.());
>> 0

配列要素を参照する際にもオプショナルチェーンが使える。要素を参照する場合は、カギカッコの前に?.を書く。

const books = undefined;
const title = books?.[0];
console.log(title);
>> undefined

const books = ["あいうえおかきくけこ"];
const title = books?.[0];
console.log(title);
>> “あいうえおかきくけこ”
inserted by FC2 system