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