Last updated on Sep 3, 2020 by Suraj Sharma
In this tutorial, you will learn 4 different ways to convert an array of values to a string in JavaScript
Array.forEach
method iterates through all the elements in an Array, each iteration concates an array element to a previously stored string.
let str = '';
['Hello', 'World', 1, 2, 3].forEach(ele=>{
str += ele;
})
console.log(str); // "HelloWorld123"
Array.toString
method is a built-in function that converts an array of elements to a string. By default, it separates the elements with a comma (",").
console.log(['Hello', 'World', 1, 2, 3].toString())
// "Hello,World,1,2,3"
console.log([{}, null, undefined, NaN].toString())
// "[object Object],,,NaN"
Array.join
method takes an argument, which acts as a separator between the array elements in the newly created string. If no argument is passed, the array elements are separated with a comma (",") in the string.
console.log(["JavaScript", "is", "fun"].join('-'))
// JavaScript-is-fun
console.log(["React", "Angular", "Vue"].join())
// React,Angular,Vue
Array.reduce
method iterates through an array of elements and finally returns a single accumulated value or a string.
console.log(["s","u","r","a","j"].reduce((acc, val)=>acc+val, ''))
// "suraj"
Related Solutions
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.