Code Fix

中級オプショナルチェイニング(?.)で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')

空欄を埋めて実行を通す

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

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

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

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

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