中級 › typeof null === 'object' の罠 › パターン5
typeof null === 'object' の罠
typeof演算子はnullに対して"object"を返します。
1 function price(product) { 2 if (typeof product === "object") { 3 return product.cost * 1.1; 4 } 5 return 0; 6 } 7 console.log(price(_____________)); ^
main.js:3
return product.cost * 1.1;
^
TypeError: Cannot read properties of null (reading 'cost')
空欄を埋めて実行を通す
typeofチェックはnullでも真になるため、その後のプロパティアクセスでエラーになります。
次の問題