The typeof operator has unexpected behavior in JavaScript when it is applied to null. Specifically:
console.log(typeof null); // Outputs: "object"
Why Does typeof null Return "object"? That is, actually, a common feature in JavaScript that most developers know. Looking back to the very beginning of JavaScript, starting with dealing with the first syntax, the values were represented as type tags in bits. The type tag for objects was 0, and null lay fallow for a time and was given this type tag so it existed as an “object.” Ironically, this behavior was never fixed for the sake of backward compatibility.
Practical Implications Confusion for Beginners: The opinion on the nature of typeof null That is why many developers expect typeof null to return ‘null’ instead of ‘object’. Type Checking: If you wish to look for null in the data specifically then you should use strict equality operators
if (value === null) {
console.log("Value is null");
}
For beginners learning JavaScript, understanding quirks like these is crucial. If you're just starting your JavaScript journey, our guide on
How to Learn JavaScript Faster provides valuable tips.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
The
typeofoperator has unexpected behavior in JavaScript when it is applied to null. Specifically:Why Does
typeof nullReturn "object"?That is, actually, a common feature in JavaScript that most developers know. Looking back to the very beginning of JavaScript, starting with dealing with the first syntax, the values were represented as type tags in bits. The type tag for objects was 0, and null lay fallow for a time and was given this type tag so it existed as an “object.” Ironically, this behavior was never fixed for the sake of backward compatibility.
Practical Implications
Confusion for Beginners: The opinion on the nature of typeof null That is why many developers expect typeof null to return ‘null’ instead of ‘object’.
Type Checking: If you wish to look for null in the data specifically then you should use strict equality operators
For beginners learning JavaScript, understanding quirks like these is crucial. If you're just starting your JavaScript journey, our guide on How to Learn JavaScript Faster provides valuable tips.