How toString().call() on object prototype is fetching the type of Array
Asked Answered
M

1

6

I am looking at the code to find out whether an object is an array on not, and I came across this answer.

The code is working fine, but I am not able to understand how it is performing a comparison with [object Array]

I tried to get the typeof Array, but it's throwing an error. So I am confused with this code"

if( Object.prototype.toString.call( someVar ) === '[object Array]' ) {

I am interested to know how the toString.call( _ON_AN_ARRAY_ ) method call on an Object is correctly getting the type of an Array object.

Magog answered 10/1, 2016 at 13:23 Comment(5)
The QA you link to has a link to a very complete explanation by Crowder: blog.niftysnippets.org/2010/09/say-what.html So it's hard to guess what's missing for you.Regurgitate
BTW all this is obsolete for arrays now, thanks to Array.isArray.Regurgitate
@DenysSéguret I haven't gone through the link which is very interesting an easy.....thxMagog
Possible duplicate of Check if object is array?Magog
@Jacques ok sorry, how could I resolve this ?Magog
B
3

Technically an array is an object, so when you do typeof arrayVar you get object, but it's not specific as to the class of object.

However when you look at an Object prototype.toString() it will also return "object", but when you look at an Object prototype, and pass in an object, it returns the object and the class of object.

You can see in the ECMAScript5 spec (§15.2.4.2) what it says 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 last one is the answer to the "how".

Bubbler answered 10/1, 2016 at 13:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.