Convert Array to String in JavaScript
Last Updated :
14 Aug, 2024
In JavaScript, converting an array to a string involves combining its elements into a single text output, often separated by a specified delimiter. This is useful for displaying array contents in a readable format or when storing data as a single string. The process can be customized to use different separators based on your needs.
Prerequisites
These are the following approaches to convert an array to a string in JavaScript:
Using the JavaScript toString() method
The array.toString() method converts the array elements to strings and then concatenates them with commas as a separator. This method is generally preferred when we don't need any customization with the separators and formatting.
Syntax:
array.toString()
Example: The below mentioned code describes the approach along with an example of considering a sample array.
JavaScript
const array = [ 1, 2, 3, 4, 5 ];
const str = array.toString();
console.log('Resultant string: ', str);
console.log('Type of resultant string: ', typeof(str));
OutputResultant string: 1,2,3,4,5
Type of resultant string: string
Using JavaScript join() method
The array.join(separator) method is used to join the elements of an array using the 'separator' operator provided. If no separator is provided then it uses the default separator as comma. This method is very useful when one needs to apply custom separator.
Syntax:
array.join(separator)
Example: In this approach we would be illustrating the usage of join method to convert an array elements to string using different separators.
JavaScript
const array = ['a', 'b', 'c'];
const str1 = array.join(); // Default separator (comma)
console.log('Using default separator: ', str1);
const str2 = array.join(' '); // Space as separator
console.log('Using space as a separator: ', str2);
const str3 = array.join('-'); // Hyphen as separator
console.log('Using hyphen as a separator: ',str3);
console.log('Type of str1: ', typeof(str1), ', Type of str2: ',
typeof(str2), ', Type of str3: ', typeof(str3));
OutputUsing default separator: a,b,c
Using space as a separator: a b c
Using hyphen as a separator: a-b-c
Type of str1: string , Type of str2: string , Type of str3: string
Using JavaScript JSON.stringify() method
The JSON.stringify() method converts an array including even the nested arrays and objects to a JSON string. This method is very useful especially in the case while preserving the structure of the complex data or even arrays over the network.
Syntax:
JSON.stringify(array)
Example: The code converts the array to a JSON string using JSON.stringify().
JavaScript
const array = [1, 'Hello', true, { key: 'value' }];
const str = JSON.stringify(array);
console.log('The resulted string is: ',str);
console.log("The type of generate 'str' is: ",typeof(str));
OutputThe resulted string is: [1,"Hello",true,{"key":"value"}]
The type of generate 'str' is: string
Using JavaScript String() method
- The String() method converts the array elements to string and then concatenates them with commas as a separator.
- This method is generally preferred when we don't need any customization with the separators and formatting.
- This method is similar to array.toString() method but the major difference is that array.toString() will show an error message
- if the array value if null but the String(array) method will display a message reading 'null' and won't throw any error.
- So, it depends on the user to use the method according to their needs.
Syntax:
String(array)
Example: The code converts both array (which is null) and array1 to strings using String().
JavaScript
const array = null;
const array1 = [1, 2, 3, 4, 5]
let str = String(array);
console.log('Resultant string (null value of array): ', str);
console.log('Type of resultant string (null value of array): ', typeof(str));
str = String(array1);
console.log('Resultant string: ', str);
console.log('Type of resultant string: ', typeof(str));
OutputResultant string (null value of array): null
Type of resultant string (null value of array): string
Resultant string: 1,2,3,4,5
Type of resultant string: string
Using JavaScript reduce() method
The reduce() method in general executes the reducer function for each and every element of an array and finally returns an accumulated value as a resulting value. It skips the array elements that are empty and it does not modify the original array which makes this method useful in such case. Here, we modified it and made it iterate over all the array elements and accumulate the result in an accumulator.
Syntax:
array.reduce(callback(accumulator, currentValue), initialValue)
Example: The code uses reduce to concatenate the elements of array into a string, separated by ", ".
JavaScript
const array = [1, 2, 3, 4, 5];
// Instead of ", " one can use any separator
const str = array.reduce((acc, curr) => acc + ", " + curr);
console.log('Resultant string: ', str);
console.log('Type of resultant string: ', typeof(str));
OutputResultant string: 1, 2, 3, 4, 5
Type of resultant string: string
Using JavaScript map() with join() method
- The map() method generates an entirely new array by applying the given function for each and every element of an array.
- It does not modify the original array instead creates a new array to store after making all the necessary operations from the function given.
- One most important feature of map() method is that it skips the empty element i.e. it skips the execution of the callback function when it finds an empty element and it focuses only on the non-empty values.
- Here, in this approach we transform each and every element using 'map()' method and then join it using 'join()' method.
- This method is very useful when you need to apply some transformation before converting to string.
Syntax:
array.map(callback(element)).join(separator)
Example: The code converts each element of the array to a string using map and then joins them with different separators (default comma, space, and hyphen).
JavaScript
const array = [1, 2, 3, 4, 5];
// Default separator (comma)
const str1 = array.map(num => `${num}`).join();
console.log('Using default separator: ', str1);
// Space as separator
const str2 = array.map(num => `${num}`).join(' ');
console.log('Using space as a separator: ', str2);
// Hyphen as separator
const str3 = array.map(num => `${num}`).join('-');
console.log('Using hyphen as a separator: ',str3);
console.log('Type of str1: ', typeof(str1), ',
Type of str2: ', typeof(str2), ', Type of str3: ', typeof(str3));
OutputUsing default separator: 1,2,3,4,5
Using space as a separator: 1 2 3 4 5
Using hyphen as a separator: 1-2-3-4-5
Type of str1: string , Type of str2: string , Type of str3: string
Using JavaScript foreach() method with string concatenation
- The foreach() method of JavaScript calls a callback function and performs operations specified on each and every element.
- Basically, it neither creates new array nor modifies the original array. It basically performs operations on each and every element.
- Here, in this approach the foreach() method iterates over each and every element and manually concatenates them into the string.
- This type of method is very useful when one needs to build a string manually with the specific logic for each and every element.
Syntax:
array.forEach(callback(element))
Example: The code concatenates the elements of array into a single string str using forEach, and then logs the resultant string and its type.
JavaScript
const array = [1, 2, 3, 4, 5];
let str = '';
array.forEach(num => {
str += num;
});
console.log('Resultant string: ', str);
console.log('Type of resultant string: ', typeof(str));
OutputResultant string: 12345
Type of resultant string: string
Using JavaScript flat() with join()
- The flat() method in JavaScript creates a new array with all the elements of the original sub array and joins them up to a certain depth.
- Depth is specified as a parameter while calling flat() method. If no depth is mentioned then it by default considers the value of depth as 1.
- Here, in this approach the flat() method flattens the nested or normal array and then using the join() method it joins all of them with the separator mentioned as a parameter.
Syntax:
array.flat().join(separator)
Example: The code flattens the `array` and joins the elements into strings using different separators (default comma, space, and hyphen), then logs the resulting strings and their types.
JavaScript
const array = [1, 2, [3, 4], 5];
// Default separator (comma)
const str1 = array.flat().join();
console.log('Using default separator: ', str1);
// Space as separator
const str2 = array.flat().join(' ');
console.log('Using space as a separator: ', str2);
// Hyphen as separator
const str3 = array.flat().join('-');
console.log('Using hyphen as a separator: ',str3);
console.log('Type of str1: ', typeof(str1), ', Type of str2: ',
typeof(str2), ', Type of str3: ', typeof(str3));
OutputUsing default separator: 1,2,3,4,5
Using space as a separator: 1 2 3 4 5
Using hyphen as a separator: 1-2-3-4-5
Type of str1: string , Type of str2: string , Type of str3: string
Similar Reads
JavaScript - Convert String to Array
Strings in JavaScript are immutable (cannot be changed directly). However, arrays are mutable, allowing you to perform operations such as adding, removing, or modifying elements. Converting a string to an array makes it easier to:Access individual characters or substrings.Perform array operations su
5 min read
JavaScript - Convert Byte Array to String
Here are the various methods to convert Byte Array to string in JavaScript.1. Using WebAPI TextDecoder.decode() MethodThe TextDecoder API is a modern and efficient way to convert a byte array (Uint8Array) to a string. Itâs supported in both browsers and Node.js.JavaScriptconst byteA = new Uint8Array
2 min read
Convert a JavaScript Enum to a String
Enums in JavaScript are used to represent a fixed set of named values. In JavaScript, Enumerations or Enums are used to represent a fixed set of named values. However, Enums are not native to JavaScript, so they are usually implemented using objects or frozen arrays. In this article, we are going to
2 min read
Convert an Array to JSON in JavaScript
Given a JavaScript Array and the task is to convert an array to JSON Object. Below are the approaches to convert an array to JSON using JsvaScript: Table of ContentJSON.stringify() methodObject.assign() methodJSON.stringify() methodThe use of JSON is to exchange data to/from a web server. While send
2 min read
Convert a Number to a String in JavaScript
These are the following ways to Convert a number to a string in JavaScript:1. Using toString() Method (Efficient and Simple Method)This method belongs to the Number.Prototype object. It takes an integer or a floating-point number and converts it into a string type.JavaScriptlet a = 20; console.log(a
1 min read
Convert a String to Number in JavaScript
To convert a string to number in JavaScript, various methods such as the Number() function, parseInt(), or parseFloat() can be used. These functions allow to convert string representations of numbers into actual numerical values, enabling arithmetic operations and comparisons.Below are the approache
4 min read
Convert base64 String to ArrayBuffer In JavaScript
A Base64 string represents binary data in an ASCII string format by translating it into a radix-64 representation. Often used to encode binary data in text-based formats like JSON or HTML, it needs to be converted back into its original binary format for further processing. An ArrayBuffer in JavaScr
2 min read
Convert a String to an Integer in JavaScript
These are the following ways to convert string to an integer in JavaScript:1. Using Number() MethodThe number() method converts a string into an integer number. It works similarly to the unary plus operator. JavaScriptlet s = "100.45"; console.log(typeof Number(s));Outputnumber 2. Using Unary + Oper
2 min read
JavaScript - Convert a String to Boolean in JS
Here are different ways to convert string to boolean in JavaScript.1. Using JavaScript == OperatorThe == operator compares the equality of two operands. If equal then the condition is true otherwise false. Syntaxconsole.log(YOUR_STRING == 'true');JavaScriptlet str1 = "false"; console.log(str1 == 'tr
3 min read
How to Convert String of Objects to Array in JavaScript ?
This article will show you how to convert a string of objects to an array in JavaScript. You have a string representing objects, and you need to convert it into an actual array of objects for further processing. This is a common scenario when dealing with JSON data received from a server or stored i
3 min read