6

Possible Duplicate:
Null object in javascript

Null is an object right? So if i set x to null, why can't i get the constructor value?

 var x = null; alert(typeof x); alert(x.constructor); 
2
  • 1
    also a possible duplicate of <a href="stackoverflow.com/questions/3662952/… null an object in JavaScript?</a> Commented Dec 6, 2010 at 20:22
  • @birryree, it's not a duplicate of that topic. That one is about the difference between null and undefined, while this is about the question if null itself is an object. Commented Dec 6, 2010 at 20:22

2 Answers 2

10

null in JS is a primitive value. It wasn't constructed by any constructor function, so it doesn't have a constructor property. typeof null being 'object' is basically a horrible lie retained for historical reasons. Don't expect too much consistency from JS, you'll be disappointed!

Primitive values can often behave like objects in JS due to autoboxing: (1).constructor works despite 1 also being a primitive value, because it implicitly calls new Number(1). But there is no Object form of null (or undefined) to automatically convert to, so in this case you get an error.

In general you should avoid using constructor. For many class/instance models built on top of JS it doesn't do what you think at all. instanceof typically works better.

Sign up to request clarification or add additional context in comments.

1 Comment

"Don't expect too much consistency from JS..." This needs to be supported.
0

Null is not an object in Javascript - null is the singular instance of the null primitive type, and as such has no constructor.

1 Comment

Yep, but there's only one of it, and only nothing can be nothing - nothing else can be nothing, and if you make anything something it's not nothing anymore.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.