Code Fix

中級 › 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 === 'object' の罠

これは言語仕様初期からのバグ扱いの挙動で、修正すると既存コードが壊れるため現在も残っています。オブジェクトかどうかの判定にtypeofだけを使うとnullをすり抜けさせてしまいます。

このエラーの解説と類題をまとめて見る →

広告
広告スロット(未設定)