中級 › オプショナルチェイニング(?.)でnull/undefinedアクセスのエラーを防ぐ › パターン1
オプショナルチェイニング(?.)でnull/undefinedアクセスのエラーを防ぐ
ネストしたプロパティの途中がnullやundefinedかもしれない場合、通常のドットアクセスではTypeErrorになります。
1 const user = { profile: null }; 2 console.log(user.profile__.name); ^
main.js:2
console.log(user.profile.name);
^
TypeError: Cannot read properties of null (reading 'name')
空欄を埋めて実行を通す
profileがnullのままドットアクセスするとエラーになります。?.を使うと、profileがnull/undefinedのときは例外を投げずundefinedを返します。
次の問題