Code Fix

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

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

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

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