Code Fix

中級 › オプショナルチェイニング(?.)でnull/undefinedアクセスのエラーを防ぐ › パターン5

オプショナルチェイニング(?.)でnull/undefinedアクセスのエラーを防ぐ

ネストしたプロパティの途中がnullやundefinedかもしれない場合、通常のドットアクセスではTypeErrorになります。

 1  const order = { customer: null };
 2  console.log(order.customer__.address);
                               ^
main.js:2 console.log(order.customer.address); ^ TypeError: Cannot read properties of null (reading 'address')

空欄を埋めて実行を通す

広告
広告スロット(未設定)

オプショナルチェイニング(?.)でnull/undefinedアクセスのエラーを防ぐ

?.を使うと、途中がnull/undefinedのときに例外を投げず、undefinedを返して処理を続けられます。

このエラーの解説と類題をまとめて見る →

広告
広告スロット(未設定)