中級 › typeof null === 'object' の罠 › パターン4
typeof null === 'object' の罠
typeof演算子はnullに対して"object"を返します。
1 function summarize(item) { 2 if (typeof item === "object") { 3 return item.title.length; 4 } 5 return -1; 6 } 7 console.log(summarize(________________)); ^
main.js:3
return item.title.length;
^
TypeError: Cannot read properties of null (reading 'title')
空欄を埋めて実行を通す
typeof null は "object" になるため、nullを弾いたつもりの分岐を通過してしまいます。
次の問題