中級 › オプショナルチェイニング(?.)で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')
空欄を埋めて実行を通す
ownerがnullのままドットアクセスするとエラーになります。?.でnullの可能性に安全に対処できます。
次の問題