Understanding the behaviour of typeof with null in JavaScript.
Understanding the behaviour of typeof with null in JavaScript.
Web Developer
I am a professional .NET developer with over 4 years of hands-on industry experience in designing, developing, and maintaining scalable web applications. I specialize in .NET Core, C#, RESTful APIs, and database-driven systems using SQL Server.
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.