Array.toString()

The Array.toString() method in JavaScript converts an array into a string. The elements of the array are joined into a single string, separated by commas. This method does not modify the original array.

Syntax

</>
Copy
array.toString()

Parameters

The toString() method does not take any parameters.

Return Value

A string representing the elements of the array, separated by commas.


Examples

1. Converting an Array to a String

This example demonstrates how to convert a simple array of numbers into a string using the toString() method.

</>
Copy
const numbers = [1, 2, 3, 4, 5];
const result = numbers.toString();

console.log(result);

Output

1,2,3,4,5
  1. numbers.toString() converts the array into a comma-separated string.

2. Using toString() on a Mixed Array

The toString() method works on arrays containing different types of elements, including strings, numbers, and booleans.

</>
Copy
const mixedArray = [42, "hello", true];
const result = mixedArray.toString();

console.log(result);

Output

42,hello,true
  1. Elements are converted to strings and concatenated, separated by commas.

3. Using toString() on Nested Arrays

When used on nested arrays, the toString() method converts inner arrays into strings as well.

</>
Copy
const nestedArray = [1, [2, 3], 4];
const result = nestedArray.toString();

console.log(result);

Output

1,2,3,4

Inner arrays are flattened into a single string representation, separated by commas.

4. Using toString() in a Function

This example demonstrates how the toString() method can be used in a function to return a string representation of an array.

</>
Copy
function arrayToString(arr) {
    return arr.toString();
}

const fruits = ["apple", "banana", "cherry"];
console.log(arrayToString(fruits));

Output

apple,banana,cherry

The function arrayToString() uses toString() to create a comma-separated string from the input array.