How is NULL an Object in Javascript?

I'm still popping the hood on JavaScript, so this particular concept is bizarre to me.

With JavaScript, you've got objects and then you have properties of those objects:

var myCar = new Object();
myCar.make = "Ford";
myCar.model = "Mustang";
myCar.year = 1969;

I get that.

But recently, I've had to wrap my brain around how, in JavaScript, NULL is considered an object.

How does that work and why does that make a difference?
brucegustPHP DeveloperAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
Julian HansenConnect With a Mentor Commented:
In JS null is not an object it is a primitive type.
console.log(typeof null);

Open in new window

Having said that the reason goes back to the first version of JS - technically it is a bug but has remained to protect existing code.

In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was 0. null was represented as the NULL pointer (0x00 in most platforms). Consequently, null had 0 as type tag, hence the bogus typeof return value
source - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#null

In JavaScript, typeof null is 'object', which incorrectly suggests that null is an object (it isn’t, it’s a primitive value, consult my blog post on categorizing values for details). This is a bug and one that unfortunately can’t be fixed, because it would break existing code. Let’s explore the history of this bug.

The “typeof null” bug is a remnant from the first version of JavaScript. In this version, values were stored in 32 bit units, which consisted of a small type tag (1–3 bits) and the actual data of the value. The type tags were stored in the lower bits of the units. There were five of them:
source - http://www.2ality.com/2013/10/typeof-null.html
2
 
James BilousConnect With a Mentor Software EngineerCommented:
In JS null is not an object it is a primitive type. By assigning null to something you are saying it exists but it has no known value. Undefined, on the other hand, means that no notion of that thing exists at all. The fact that typeof(null) reveals 'Object' is an error in the implementation of JS that has not been fixed in order to prevent breaking legacy code.
0
 
brucegustPHP DeveloperAuthor Commented:
Thank you, gentlemen!
0
 
Julian HansenCommented:
You are welcome.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.