Understanding the behaviour of typeof with null in JavaScript.
The behaviour of typeof with null in JavaScript.
345
23-Dec-2024
Updated on 30-Dec-2024
Khushi Singh
28-Dec-2024The
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.