Adarsh Konchady Adarsh Konchady - 2 months ago 6
Javascript Question

Difference between Object.prototype.toString.call(arrayObj) and arrayObj.toString()

I have gone through some materials and haven't completely grasped the concept when it comes to syntax such as the following :

var arrObj = [1,2,3];
Object.prototype.toString.call(arrObj); //Gives "[object Array]"
arrObj.toString(); // Gives "1,2,3"


How are the lines 2 and 3 different? As far as I understood, both call the toString method with current object being set to 'arrObj'.

Answer

Since toString is defined in Object.prototype, whoever inherits Object, will by default get the toString method.

But, Array objects, override the default toString method to print the array elements as comma separated string.

Object.prototype.toString doesn't know what type of Object it actually deals with. So, it is intentionally kept generic and it always prints the actual type of the Object. That is why

console.log(Object.prototype.toString.call(arrObj));

prints

[object Array]

which is the type of object passed. But, when you do arrObj.toString, you are trying to represent the array in its String form, so toString is overriden in Array objects to print the array elements as comma separated string.

That is why both the calls are different.


But in case of other objects, the toString is not overriden, so they will use the toString from the Object.prototype.toString. For example,

var obj = {
    1: 2
};

console.log(obj.toString());
// [object Object]

Read the MDN's example of Overriding the default toString method