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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read