Javascript - Array To String Conversion

Introduction

All objects have toLocaleString(), toString(), and valueOf() methods.

The toString() and valueOf() methods return the same value when called on an array.

The result is a comma-separated string that contains the string equivalents of each value in the array.

Demo

var colors = ["red", "blue", "green"];    //creates an array with three strings
console.log(colors.toString());    //red,blue,green
console.log(colors.valueOf());     //red,blue,green
console.log(colors);               //red,blue,green

Result

In this code, the toString() and valueOf() methods are called explicitly to return the string representation of the array.

The last line passes the array directly into console.log().

Because console.log() expects a string, it calls toString() behind the scenes to get the same result as when toString() is called directly.

When toLocaleString() is called on an array, it creates a comma-delimited string of the array values.

toLocaleString() calls each item's toLocaleString() instead of toString() to get its string value.

Demo

var person1 = {
    toLocaleString : function () {
        return "local";
    },/*from  w  w w.  j a va 2s.  c o m*/

    toString : function() {
        return "First";
    }
};

var person2 = {
    toLocaleString : function () {
        return "A";
    },

    toString : function() {
        return "B";
    }
};

var people = [person1, person2];
console.log(people);                      //First,Greg
console.log(people.toString());           //First,B
console.log(people.toLocaleString());     //local,A

Result

To construct a string with a different separator, use the join() method.

The join() method accepts the string separator and returns a string containing all items.

var colors = ["red", "green", "blue"];
console.log(colors.join(","));      //red,green,blue
console.log(colors.join("||"));     //red||green||blue