- Array.prototype.toString()
- Try it
- Syntax
- Return value
- Description
- Examples
- Using toString()
- Using toString() on sparse arrays
- Calling toString() on non-array objects
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- 5 Ways To Convert JavaScript Array To String
- 1. Convert Array To String Using join() Method
- 2. Using toString() Method
- 3. Stringifying array to string
- 4. Using String() Method
- 5. Using Coercion
- JavaScript array to string with commas
- JavaScript array to string without commas
- Conclusion
- Converting Arrays to Strings in JavaScript
- Getting Started
- To string, or Not to String.
- Join Together
- Speaking of HTML
- Conclusion
Array.prototype.toString()
The toString() method returns a string representing the specified array and its elements.
Try it
Syntax
Return value
A string representing the elements of the array.
Description
The Array object overrides the toString method of Object . The toString method of arrays calls join() internally, which joins the array and returns one string containing each array element separated by commas. If the join method is unavailable or is not a function, Object.prototype.toString is used instead, returning [object Array] .
const arr = []; arr.join = 1; // re-assign `join` with a non-function console.log(arr.toString()); // [object Array] console.log(Array.prototype.toString.call( join: () => 1 >)); // 1
JavaScript calls the toString method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation.
Array.prototype.toString recursively converts each element, including other arrays, to strings. Because the string returned by Array.prototype.toString does not have delimiters, nested arrays look like they are flattened.
const matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; console.log(matrix.toString()); // 1,2,3,4,5,6,7,8,9
When an array is cyclic (it contains an element that is itself), browsers avoid infinite recursion by ignoring the cyclic reference.
const arr = []; arr.push(1, [3, arr, 4], 2); console.log(arr.toString()); // 1,3,,4,2
Examples
Using toString()
const array1 = [1, 2, "a", "1a"]; console.log(array1.toString()); // "1,2,a,1a"
Using toString() on sparse arrays
Following the behavior of join() , toString() treats empty slots the same as undefined and produces an extra separator:
Calling toString() on non-array objects
toString() is generic. It expects this to have a join() method; or, failing that, uses Object.prototype.toString() instead.
.log(Array.prototype.toString.call( join: () => 1 >)); // 1; a number console.log(Array.prototype.toString.call( join: () => undefined >)); // undefined console.log(Array.prototype.toString.call( join: "not function" >)); // "[object Object]"
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jun 15, 2023 by MDN contributors.
Your blueprint for a better internet.
5 Ways To Convert JavaScript Array To String
In this article, we are going to see how to convert Javascript array to string in 5 different ways. You will see converting an array to a string with commas, without commas, using the join() method, etc.
We need to convert an array to a string in JavaScript for various reasons like: the need to send an array to the server for processing, the need to store an array in local storage, the data set stored in an array to be displayed on a web page, etc.
For your quick answer, convert the Javascript array to string using join() method .
The join() method will join all the elements of an array into a string by separating them with a specified character. Here is an example:
var arr = ["a", "b", "c", "d", "e"]; var str = arr.join(); console.log(str); // a,b,c,d,e // join array elements // without separator str = arr.join(""); console.log(str);
The code above demonstrates how you can easily convert an array to a string in JavaScript. We discuss more methods to convert an array to a string below and also explore the join() method in detail.
1. Convert Array To String Using join() Method
The join() is an array method in JavaScript. It is used to join all the elements of an array into a string by separating them with a given character.
The method takes one argument, which is the separator. The separator is used to separate the elements of an array. The default separator is a comma (,).
arr.join(); // or arr.join(separator);
After joining all the elements the string is returned.
var arr = ["a", "b", "c", "d", "e"]; // join array elements var str = arr.join(); console.log(str); // a,b,c,d,e // join with underscore str = arr.join("_"); // a_b_c_d_e console.log(str);
In the above example when we do not pass any separator, the array is joined with a comma (,) as the default separator. And when you passed underscore (_) as the separator, the array is joined with an underscore as the separator.
Let’s try adding multiple characters as the separator.
var arr = ["John", "is", "a", "good", "coder"]; var str = arr.join("###"); console.log(str);
2. Using toString() Method
The toString() method is a Javascript method that converts an array to a string by separating the elements with commas.
The method takes no arguments and returns a string.
var arr = ["John", "is", "a", "good", "coder"]; // convert array to string var str = arr.toString(); console.log(str); // John,is,a,good,coder
In the above example, the toString method converts an array to a string by separating the elements with a comma (,) .
Later if you want then you can replace these commas with any other character using the replaceAll() method.
The following example shows how to replace the commas with an underscore.
var arr = ["John", "is", "a", "good", "coder"]; // using toString() method var str = arr.toString(); str = str.replaceAll(",", "_"); console.log(str); // John_is_a_good_coder
Note: If the array element itself contains a comma then you have to take care of it using your own logic.
3. Stringifying array to string
You can directly convert an array to a string by using the JSON.stringify() method.
The method takes every element of an array wraps it in double-quotes, separates them with a comma, and returns a string with a square bracket at the beginning and a square bracket at the end.
var arr = ["John", "is", "a", "good", "coder"]; // using JSON.stringify() method var str = JSON.stringify(arr); console.log(str); // ["John","is","a","good","coder"]
JSON.stringify() method is mostly used to convert a data structure to a string before sending it to the server. Or the data sent by the server is stringified before sending it to the client.
4. Using String() Method
The String() method in Javascript is can convert any value to a string and can so do for an array. It converts an array to a string by separating the elements with commas.
The method takes a array itself as an argument and returns a string.
var arr = ["John", "is", "a", "good", "coder"]; // using String() method var str = String(arr); console.log(str); // John,is,a,good,coder
5. Using Coercion
Coercion is the process of converting a value to a different type.
In Javascript using an operator over an operand can change the data type of the operand. For example, the operator + can be used to convert a string to a number, adding an empty string to a number will convert the number to a string.
In the same way, if you add a blank array to any existing array, the existing array will be converted to a string. The same happens if you add a string to an array.
Here is an example to show this in action.
var arr = ["John", "is", "a", "good", "coder"]; var str1 = arr + []; // John,is,a,good,coder console.log(str1); console.log(typeof str1); // string var str2 = arr + ""; // John,is,a,good,coder console.log(str2); console.log(typeof str2); // string
John,is,a,good,coder string John,is,a,good,coder string
The above method methods to convert Javascript array to string can be generalized into 2 categories:
JavaScript array to string with commas
Methods that can be used to convert an array to a string with commas are:
- Using toString() method
- Using join() method
- Using String() method
- Using coercion process
JavaScript array to string without commas
Methods that can be used to convert an array to a string without commas is using the arr.join(» «) with any separator other than a comma or leave it blank.
var arr = ["Ja", "va", "S", "cript"]; var str = arr.join(""); console.log(str); // JavaScript
Conclusion
In this short guide, you have learned 5 different ways to convert Javascript array to string. Among all these methods, the join() method is robust and most commonly used for this purpose.
Converting Arrays to Strings in JavaScript
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Arrays are a powerful feature of any language. They let you house multiple pieces of information easily. They will maintain the order of items being added and can even be sorted. In modern web browsers, they even handle auto-magically converting themselves into human readable strings. Even with the modern niceties, it’s still good to know how to convert an array to a string for those times when you need to massage an array into another format, or want to do something more than simply comma separating the values (the default behavior).
Getting Started
No special tools required. You can hack along in either your web browser’s console or using the Node.js REPL. The commands utilized are baked into the Array Object’s prototype.
To string, or Not to String.
You would receive an alert with the message 1,2,3 without any additional work on your part. If all you need to do is display the contents of an array in this format, this can get you pretty far. This even works when referencing array objects inside of template literals. Under the hood, the array items are being joined together as a string, using the comma , character as the delimiter. It’s the same as running either of the following:
Both result in the same 1,2,3 string. In fact, that’s all that the .toString() method can do for us. It accepts no parameters so it’s usefulness is fairly limited. Even though arrays are actually objects in JavaScript, the .toString() method for an array overrides the object’s .toString() method, that’s why we don’t end up with the pesky and way less useful [object Object] string.
Join Together
While it’s default behavior (without any passed parameters) is the same as .toString() , the .join() method is significantly more robust. Let’s say you wanted to include a space after the comma when creating your string, you can tell .join() the exact string to use:
Want HTML breaks AND new lines. Okay, you get the idea. The .join() method accepts an optional parameter that lets you define the separator character or characters you’d like to use to join the array items together.
Speaking of HTML
One of my favorite .join() tricks, before template literals and JSX made it extremely easy to work with multiple line blocks of markup, was to use .join() to assemble an array of HTML tags into a string:
[ '', '', '', 'Name ', 'Level ', ' ', '', '', '', 'Alligator ', '9001 ', ' ', '', '
', ].join('');
Passing in an empty string to .join() simply joins the array items without any additional characters. Still pretty handy for dealing with multiple line strings and/or markup when you don’t have access to some of the more modern syntax options.
Conclusion
Even if all you’re trying to do is display a comma separated list of array items to a user, you can still benefit from using the .join() method. It gives you more control over the output which will make things easier to read for your users. Working with a back-end server that doesn’t understand arrays being passed-in? Join your array items into a single value and you’re good to go!
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us