Code Fix

中級typeof null === 'object' の罠 › パターン1

typeof null === 'object' の罠

typeof演算子はnullに対して"object"を返します。

 1  function describe(value) {
 2    if (typeof value === "object") {
 3      return value.label;
 4    }
 5    return "primitive";
 6  }
 7  console.log(describe(________________));
                                 ^
main.js:3 return value.label; ^ TypeError: Cannot read properties of null (reading 'label')

空欄を埋めて実行を通す

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

typeof null === 'object' の罠

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

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

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