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