JavaScript Array toString: The Complete Guide

 For Array objects, the toString() method joins an array and returns one string that contains each array element separated by the commas.

Javascript array toString

JavaScript array toString() is a built-in function that returns a string representing the specified array and its elements. The toString() method converts an array into a String and returns the result. The array toString() method returns a string with all the array values, separated by commas, and does not modify the original array.

Syntax

The syntax of the Javascript Array ToString() method is the following.

array.toString()

Let’s take an example.

// app.js

let arr = ['krunal', 'ankit', 'rushabh', 'dhaval'];
console.log(arr.toString());

The output is the following.

Javascript Array ToString Example

So, that means it has returned the comma-separated values.

JavaScript automatically calls a toString() method when the array is represented as the text value or when the array is referred to in a string concatenation.

The returned string will separate the elements in the array with commas.

A slightly less common approach is to use the Javascript Array join() method. By default, it adds the comma to resulting values, though you can specify that it adds nothing or some other separator value.

Javascript Array join() method creates and returns the new string by concatenating all of the elements of an array.

You can also take advantage of JavaScript’s type coercion: the + operator can either add the two numbers or concatenate the two strings.

But what happens when we try to join the object (the array [] is also the object) with something else? Again, javaScript is forgiving, so it will not crash the program.

Instead, it knows how to concatenate the strings so that it will convert everything into a string.

Convert Array of Arrays to String

To convert an array of arrays to String in JavaScript, use the array.toString() method.

// app.js

let arr = [['krunal', 'ankit', ['hello']], ['rushabh', 'dhaval']];
console.log(arr.toString());

The output will be a single string with all the items comma separated. Notice that also, subarrays are separated by a comma as well.

See the below output.

Convert Array of Arrays to String

That’s it for this tutorial.

1 thought on “JavaScript Array toString: The Complete Guide”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.