中級 › typeof null === 'object' の罠 › パターン3
typeof null === 'object' の罠
typeof演算子はnullに対して"object"を返します。
1 function describeUser(user) { 2 if (typeof user === "object") { 3 return user.name.toUpperCase(); 4 } 5 return "unknown"; 6 } 7 console.log(describeUser(______________)); ^
main.js:3
return user.name.toUpperCase();
^
TypeError: Cannot read properties of null (reading 'name')
空欄を埋めて実行を通す
userがnullでもtypeofチェックは通過してしまい、name.toUpperCase()の手前で例外になります。
次の問題