Code Fix

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

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

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

 1  const account = { owner: null };
 2  console.log(account.owner__.email);
                              ^
main.js:2 console.log(account.owner.email); ^ TypeError: Cannot read properties of null (reading 'email')

空欄を埋めて実行を通す

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

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

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

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

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