The Array.toString()
method is a built-in JavaScript function that converts an array into a comma-separated string. It is a simple way to represent the contents of an array as a string, with each element of the array joined by a comma.
Syntax
arr.toString();
Parameters
The toString()
method does not take any parameters.
Return Value
The method returns a string representation of the array, where all elements are joined by a comma (,
).
Example 1: Basic Array Conversion
let arr = ['HTML', 'CSS', 'JavaScript', 'jQuery']; let str = arr.toString(); console.log(str); // Output: "apple,banana,cherry" console.log(arr); // Output: ['apple', 'banana', 'cherry']
Example 2: Numeric Array
let arr = [10, 20, 30, 40, 50]; let str = arr.toString(); console.log(str); // Output: "10,20,30,40,50"
Example 3: Handling Mixed Data Types
let arr = ['hello', 42, true, null]; let str = arr.toString(); console.log(str); // Output: "hello,42,true,"
Example 4: Nested Arrays
let arr = [1, [2, 3], [4, 5]]; let str = arr.toString(); console.log(str); // Output: "1,2,3,4,5"
Example 5: Using toString()
with Objects
let obj = [ { name: 'Alice' }, { name: 'Bob' }, { name: 'Charlie' } ]; let str = obj.toString(); console.log(str); // Output: "[object Object],[object Object],[object Object]"
Supported Browsers
Browser | Support |
---|---|
Chrome | 1+ |
Firefox | 1+ |
Safari | 1+ |
Edge | 12+ |
Opera | 4+ |
Internet Explorer | 5.5+ |