Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Javascript Array toString()
In this tutorial, you will learn about the JavaScript Array toString() method with the help of examples.
The toString() method returns a string formed by the elements of the given array.
Example
// defining an array
let items = ["JavaScript", 1, "a", 3];
// returns a string with elements of the array separated by commas
let itemsString = items.toString();
console.log(itemsString);
// Output:
// JavaScript,1,a,3
toString() Syntax
The syntax of the toString() method is:
arr.toString()
Here, arr is an array.
toString() Parameters
The toString() method does not take any parameters.
toString() Return Value
- Returns a string representing the values of the array separated by a comma
Notes:
- The
toString()method does not change the original array. - Elements like
undefined,null, or empty array, have an empty string representation.
Example 1: Using toString() Method
let info = ["Terence", 28, "Kathmandu"];
// returns the string representation of the info array
let info_str = info.toString();
console.log(info_str);
// toString() does not change the original array
console.log(info);
Output
Terence,28,Kathmandu [ 'Terence', 28, 'Kathmandu' ]
In the above example, we have used the toString() method to convert all the elements of the info array into a string.
info.toString() returns the string representation of info which is Terence,28,Kathmandu.
Since the method does not change the original array, the info array holds the same original value.
Example 2: toString() with Nested Arrays
When we use the toString() method in a nested array, the array is flattened. For example:
// defining a nested array
let nestedArray = [1, 2, 4, ["Apple", 5]];
// returns string representation of the nested array by flattening the array
let resultingArray = nestedArray.toString();
console.log(resultingArray);
Output
1,2,4,Apple,5
Also Read: