JavaScript Glossary - Lesson #10

JavaScript Array .join() Method

The join method combines all the elements contained in an array and returns it as a string separated by a comma (,) or any specified string separator.

The method will return an empty string if the length of the array is 0.

javascript
// create an array
const words = ['Hello', 'there', 'world!'];

// join the array with spaces in between
const greeting = words.join(' WOW ');

// display string
console.log(greeting); // Hello WOW there WOW world!
js
// create new array
const newArray = ['a', 'new', 'array']

// join array with no spaces
const simpleString = newArray.join('')

// join array with dashes
const dashedString = newArray.join('-')

// display new strings
console.log(simpleString) // anewarray
console.log(dashedString) // a-new-array

The join method:

  • Takes an optional separator.
  • Concatenates the elements of the array separated by the provided separator or the default separator which is a comma.

This method takes one parameter:

separator This is a string provided to be used as a separator while concatenating the elements - optional.

The method will return a string containing all the elements contained in the array or an empty string if the array is empty.

js
// create a string
const names = ['John', 'Peter', 'James', 'Pammy'];

const myName = names.join();
// output: 'James, Peter, James, Pammy'

The simplest use of the .join() method is to concatenate elements in an array with a separator.

js
// new array
const words = ['Hello', 'world!'];

// join elements in array
const greeting = words.join(' ');

console.log(greeting);
// output: Hello world!

Some of the popular use cases of .join() is in combination with the .split() string method.

js
// new string with commas
const stringWithCommas = 'I, want, to, come, home';

// split string by the commas into an array
const wordArray = stringWithCommas.split(', ')

// join array into a string with a space as separator.
const stringWithoutCommas = wordArray.join(' ');

console.log(stringWithoutCommas)
// output: I want to come home

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)