1

Going on from this question here: Checking for undefined

I wanted to know if an object was an Array, now I need to test to see if an Object is specifically an Object and not just a subclass of an Object

Because at the moment an Array would return true if checked to see if it is an instance of an Object. Are there any other types that would evaluate to true?

enter image description here

EXTRA INFO

I have found that if you call toString on an Array that has one string element it resolves to that string element and not "[object Array]" so you need to be careful of that. For example:

["str1", "str2"].toString() === "[object Array]"

but

["str1"].toString() === "str1"
Community
  • 1
  • 1
FabianCook
  • 20,269
  • 16
  • 67
  • 115

1 Answers1

2

Test like this:

if ({}.toString.call(obj) == '[object Object]') {
  // is object
}

if ({}.toString.call(obj) == '[object Array]') {
  // is array
}

obj is any object. Same with objects such as RegExp, Date, etc... In old IE you may need to do ({}) for it to work properly.

Demo: http://jsbin.com/exofup/2/edit

elclanrs
  • 92,861
  • 21
  • 134
  • 171
  • `obj` is any object (object, array, date, regex...) – elclanrs Mar 18 '13 at 03:52
  • You're missing the point @SmartLemon. You need to pass the object in question as context. You're using the `toString` method of `{}`. It oculd be written as `Object.prototype.toString.call(obj)`. – elclanrs Mar 18 '13 at 03:53
  • Well then you would do that anyway... `({}).toString() == '[object Object]'` results to true and `([]).toString() == '[object Object]'` results to false – FabianCook Mar 18 '13 at 03:53
  • The `toString` method of any object will evaluate to `'[object Object]` if it is an object correct? While it would evaluate to something other then that if it wasn't – FabianCook Mar 18 '13 at 03:55
  • Oh I see what you mean now. Yeah if you're **just** testing for an object type Object I guess it should work. This was more of a general answer, but use it how you need it. – elclanrs Mar 18 '13 at 03:57
  • Sweet as. That is what I was getting through. I just want its type :P. So no need for `call(obj)` correct? Thanks. – FabianCook Mar 18 '13 at 03:59
  • I wouldn't complicate things, you can use the above technique to check ANY type of object in JavaScript, for example http://jsbin.com/exofup/2/edit – elclanrs Mar 18 '13 at 04:10