オプショナルチェーンはブラケティング記法でも使える.js
2024-07-21
code:example.js
obj.val?.prop
obj.func?.(args)
の4パターンがあるっぽい。
obj.val?.prop
一番馴染みがある(?)
code:ex_1.js
console.log(null?.hoge) // Expected Log Output : {Undefined} undefined ※エラーにならない
obj.val?.expr
プロパティアクセサーのブラケット表記法を使用している式のプロパティにアクセスする際にも、オプショナルチェーン演算子を使用することができます。
へ〜〜、それやっていいんだ
code:ex_2.js
console.log(null?."hoge") // Expected Log Output : {Undefined} undefined ※エラーにならない obj.val?.index
配列のアクセスも本質はプロパティアクセスなので、同じようにオプショナルチェーンが使える
code:ex_3.js
console.log(null?.7 * 3) // Expected Log Output : {Undefined} undefined ※エラーにならない obj.func?.(args)
関数がなかったらundefinedを返せるらしい、そんなこともできたのかお前
code:ex_4.js
console.log(maybe_array.at?.(0)) // Expected Log Output : {Undefined} undefined ※エラーにならない