Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 106
  • Last Modified:

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?
0
brucegust
Asked:
brucegust
  • 2
2 Solutions
 
James BilousSoftware 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
 
Julian HansenCommented:
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
 
brucegustPHP DeveloperAuthor Commented:
Thank you, gentlemen!
0
 
Julian HansenCommented:
You are welcome.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now