How to Join All Elements of an Array in JavaScript

Tyler Tyler (291)
5 minutes

This guide will teach you how to concatenate, or join, all elements of an array into a single string.

Posted in these interests:
h/javascript27 guides
h/code68 guides
h/webdev60 guides

The JavaScript Array class provides a method called join that allows you to concatenate all elements of an array into a single string. By default this method separates the elements by a comma.

var primes = [0, 1, 2, 3, 5, 7, 11];
var primeStr = primes.join();
// > "0,1,2,3,5,7,11"

An optional second parameter to the join method is the separator you wish to use. Suppose you have an array of words that you want to join into a sentence (separated by spaces).

var words = ['The', 'rain', 'in', 'Spain', 'stays', 'mainly', 'in', 'the', 'plain'];
var sentence = words.join(' ');
// > "The rain in Spain stays mainly in the plain"
Make your object readable in console.
Zach Zach (236)
2 minutes

This short guide will show you how to pretty print a JSON object in the Chrome Developer Tools console.