中級 › オプショナルチェイニング(?.)で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')
空欄を埋めて実行を通す
customerがnullの場合も、?.を挟めば例外を投げずにundefinedを返します。
次の問題