2

In javascript, typeof null == “object” is true. But null instanceOf Object is false. I was confused about this until I read in Professional JavaScript for Web Developers that,

if instanceOf is used with a primitive value, it will always return FALSE, because primitives aren’t objects.

Why, if primitive data types aren't objects, will typeof null == "object" be true?

adam Kiryk
  • 1,735
  • 2
  • 14
  • 14

1 Answers1

2

The typeof operator is quirky, basically. Here is the documentation in the spec. From that table, you can see that the operator is simply defined such that the result of typeof null is "object".

In JavaScript, null is really in a type of its own. It's a special primitive type.

JavaScript primitive types are indeed not objects. They can sometimes seem like objects, because the language semantics (specifically, the semantics of the . and [ ] operators) are such that primitives are automatically "boxed" with objects of a corresponding type. That's true for boolean, number, and string primitives. For null, there is no such corresponding object type.

Because of that,

var len = "some string".length;

works, even though string primitives don't have a "length" property.

One more thing: it's somewhat common to use the "toString" function on the Object prototype as a sort of "improved" version of the typeof operator.

alert( Object.prototype.toString.call( null ) ); // [object Null]

The strings that that function returns aren't the most convenient things to deal with, but they do provide a little finer granularity than typeof.

Pointy
  • 405,095
  • 59
  • 585
  • 614