Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 483
Tech Solvr Avatar asked Jan 10 '16 13:01

Tech Solvr


People also ask

What is prototype toString call?

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 .

What is the correct prototype of toString method of an object class?

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.

What is the function toString () method?

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.

What is the return value of the toString () method of an object?

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.


1 Answers

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".

like image 164
Jacques ジャック Avatar answered Oct 28 '22 07:10

Jacques ジャック