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:
- Is this a known “behavior”, and when does this happen?
- is there a more reliable way to check object types (I need to support IE7+)?
ECMAScript5 specification states in §15.2.4.2 about the Object.prototype.toString method:
The problem you are facing is that IE7 and 8 follow the older ECMAScript3 standard, which states in the same section that
That is, in older versions of IE, the method will not return
[object Undefined]or[object Null]unless they are constructed from functions namedUndefinedorNull.You can check for types more reliably using the following methods: