Array toString()

In this chapter you will learn:

  1. toString(), toLocaleString() and valueOf Array
  2. toLocaleString() vs toString()

toString(), toLocaleString() and valueOf Array

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

<!DOCTYPE html><!--  j  av a  2  s  . c o m-->
<html>
<head>
    <script type="text/javascript">
    //creates an array with three strings 
    var colors = ["red", "blue", "green"]; 
    
    document.writeln(colors.toString()); //red,blue,green 
    document.writeln(colors.valueOf()); //red,blue,green 
    document.writeln(colors); //red,blue,green 
       
    </script>
</head>
<body>
</body>
</html>

Click to view the demo

toLocaleString() vs toString()

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

<!DOCTYPE html><!--   jav a 2  s. c  om-->
<html>
<head>
    <script type="text/javascript">
        var tutorial1 = {
            toLocaleString : function () {
                return "Java";
            },
            
            toString : function() {
                return "XML";
            }
        };
        
        var tutorial2 = {
            toLocaleString : function () {
                return "HTML";
            },
            
            toString : function() {
                return "CSS";
            }
        };
        
        var tutorial = [tutorial1, tutorial2];
        document.writeln(tutorial.toLocaleString()); //Java HTML

       </script>
</head>
<body>
</body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. How to use Javascript array unshift() method
Home » Javascript Tutorial » Array
Array Type
Array creation
Array type detecting
Array iterate
Array Length
Add to Array
Array join
Array concat()
Array every method
Array search from start with indexOf()
Array search from the end with lastIndexOf()
Array filter
Array mapping
Array forEach
Array pop and push
Array shift()
Array reduce()
Array reduceRight()
Array reverse()
Array slice()
Array some()
Array splice()
Array sort()
Array toString()
Array unshift()