中級 › オプショナルチェイニング(?.)でnull/undefinedアクセスのエラーを防ぐ › パターン3
オプショナルチェイニング(?.)でnull/undefinedアクセスのエラーを防ぐ
ネストしたプロパティの途中がnullやundefinedかもしれない場合、通常のドットアクセスではTypeErrorになります。
1 const response = { data: null }; 2 console.log(response.data__.items); ^
main.js:2
console.log(response.data.items);
^
TypeError: Cannot read properties of null (reading 'items')
空欄を埋めて実行を通す
dataがnullでもitemsに直接アクセスしようとするとエラーになります。?.でnullの可能性に安全に対処できます。
次の問題