Christophe
Christophe

Reputation: 28164

When does Object.prototype.toString.call(null) return [object Object]?

I am using Object.prototype.toString.call to identify variable types. I would expect the following behavior:

Object.prototype.toString.call({}) => [object Object]
Object.prototype.toString.call([]) => [object Array]
Object.prototype.toString.call(undefined) => [object Undefined]
Object.prototype.toString.call(null) => [object Null]

This usually works fine, but I am currently faced with a situation (in Internet Explorer) where both Object.prototype.toString.call(undefined) and Object.prototype.toString.call(null) return [object Object], and I don't understand why. I tried to replicate it on jsfiddle.net but couldn't, so I am assuming I am in a specific quirk mode.

My questions:

Upvotes: 2

Views: 2240

Answers (2)

Peter Olson
Peter Olson

Reputation: 143007

ECMAScript5 specification states in §15.2.4.2 about the Object.prototype.toString method:

When the toString method is called, the following steps are taken:

  1. If the this value is undefined, return "[object Undefined]".
  2. If the this value is null, return "[object Null]".
  3. Let O be the result of calling ToObject passing the this value as the argument.
  4. Let class be the value of the [[Class]] internal property of O.
  5. Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".

The problem you are facing is that IE7 and 8 follow the older ECMAScript3 standard, which states in the same section that

When the toString method is called, the following steps are taken:

  1. Get the [[Class]] property of this object.
  2. Compute a string value by concatenating the three strings "[object ", Result(1), and "]".
  3. Return Result(2).

That is, in older versions of IE, the method will not return [object Undefined] or [object Null] unless they are constructed from functions named Undefined or Null.

You can check for types more reliably using the following methods:

typeof x === "object"    // x is any sort of object
typeof x === "undefined" // x is undefined
x instanceof Array       // x is an array
x === null               // x is null

Upvotes: 5

andr
andr

Reputation: 16064

As others have said, null is of type Object and representing empty object reference.

More reliable way of checking the type of value is typeof operator.

As far as I know, it's been supported since IE 6. (Or earlier, I haven't checked.)

Upvotes: 0

Related Questions