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.
Object. prototype. toString() returns "[object Type]" , where Type is the object type. If the object has a Symbol. toStringTag property whose value is a string, that value will be used as the Type .
In JavaScript, the Object. prototype. toString() method is used to return a string that can represent the object. The toString() method is automatically inherited by every object which is inherited from Object.
toString . For user-defined Function objects, the toString method returns a string containing the source text segment which was used to define the function. JavaScript calls the toString method automatically when a Function is to be represented as a text value, e.g. when a function is concatenated with a string.
A toString() is an in-built method in Java that returns the value given to it in string format. Hence, any object that this method is applied on, will then be returned as a string object.
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:
- If the this value is undefined, return "[object Undefined]".
- If the this value is null, return "[object Null]".
- Let O be the result of calling ToObject passing the this value as the argument.
- Let class be the value of the [[Class]] internal property of O.
- 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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With