オプショナルチェーン演算子
「参照がnullishなら即undefinedを返すよ!」っていう演算子。プロパティアクセサーの亜種みたいなやつ。 code:example.js
const obj = {
"exist": {
"hoge": 1,
"fuga": 2,
}
};
// 参照が存在する場合は普通のプロパティアクセサーと変わらない
console.log(obj.exist?.hoge) // Expected Log Output : {Number} 1
console.log(obj.exist.hoge) // Expected Log Output : {Number} 1
// 参照が存在しない場合、通常はエラーを吐くがオプショナルチェーンはundefinedを返すことで死を回避する
console.log(obj.non_exist?.hoge) // Expected Log Output : {Undefined} undefined
console.log(obj.non_exist.hoge) // Uncaught TypeError: Cannot read properties of undefined (reading 'hoge')