JavaScript Tutorials

JavaScript Array toString()
Syntax & Examples

Array.toString() method

The toString() method of the Array class in JavaScript returns a string representing the calling array and its elements. It overrides the Object.prototype.toString() method.


Syntax of Array.toString()

The syntax of Array.toString() method is:

toString()

This toString() method of Array returns a string representing the calling array and its elements. Overrides the Object.prototype.toString() method.

Return Type

Array.toString() returns value of type String.



✐ Examples

1 Using toString() method to convert an array to a string

In JavaScript, we can use the toString() method to convert an array to a string representation.

For example,

  1. We define an array variable arr with elements [1, 2, 3, 4, 5].
  2. We use the toString() method on arr to convert it to a string representation.
  3. The array elements are concatenated into a single string with commas between each element.
  4. We log the string representation to the console using console.log() method.

JavaScript Program

const arr = [1, 2, 3, 4, 5];
const stringRepresentation = arr.toString();
console.log(stringRepresentation);

Output

1,2,3,4,5

2 Using toString() method on an array of strings

We can also use the toString() method on an array of strings to get a string representation.

For example,

  1. We define a string array variable strArr with elements ['apple', 'banana', 'cherry', 'date'].
  2. We use the toString() method on strArr to convert it to a string representation.
  3. The string array elements are concatenated into a single string with commas between each element.
  4. We log the string representation to the console using console.log() method.

JavaScript Program

const strArr = ['apple', 'banana', 'cherry', 'date'];
const stringRepresentation = strArr.toString();
console.log(stringRepresentation);

Output

apple,banana,cherry,date

Summary

In this JavaScript tutorial, we learned about toString() method of Array: the syntax and few working examples with output and detailed explanation for each example.