Adarsh Konchady Adarsh Konchady - 10 months ago 43
Javascript Question

Difference between 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];; //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 Source

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



[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

// [object Object]

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