6.10 Joining an Array

Another very useful array method is join. Given an array of numbers (or anything else), join turns it into a single string, with a separator between each element. The separator parameter is optional — the question mark next to it in the documentation tells you so — and it must be a string.

const numbers = [1, 2, 3, 4];
const joined  = numbers.join(",");  // "1,2,3,4"
console.log(joined);

Notice that join returns a string, not an array. The partner of join is split — but split belongs to the String type, not to arrays. It does the opposite operation: it takes a string, splits it on a separator, and gives you back an array.

const message  = "This is my first message";
const parts    = message.split(" ");   // ["This", "is", "my", "first", "message"]
const combined = parts.join("-");      // "This-is-my-first-message"

A real-world use case: URL slugs

  • URLs cannot contain spaces — they need to be replaced with hyphens.
  • Stack Overflow turns the title "Why use Arrays in JavaScript" into why-use-arrays-in-javascript.
  • The recipe is exactly: split the title on spaces, optionally remove or replace some words, then join the parts with "-".

split + join form a tiny but extremely common pipeline in web development. Whenever you generate slugs, parse CSV-like lines, or rebuild paths, you'll reach for them. See you in the next video.

Summary

Learn the Array join() method, which concatenates all array elements into a single string using a specified separator. This lesson demonstrates joining numeric arrays and introduces the complementary String split() method, showing practical real-world applications like converting titles into URL slugs with hyphens.

Key points

  • The join() method combines array elements into a string with a custom separator (comma, hyphen, space, etc.)
  • The separator parameter is optional; omitting it defaults to a comma
  • The split() method does the opposite: it converts a string into an array by splitting on a separator
  • Combining split() and join() is essential for URL slug generation, replacing spaces with hyphens
  • These complementary methods enable string-to-array and array-to-string transformations

FAQ

What does the join() method do?

The join() method takes all elements of an array and combines them into a single string, using a specified separator (such as a comma, space, or hyphen) between elements.

What is the difference between join() and split()?

join() converts an array into a string by combining elements with a separator, while split() does the opposite—it converts a string into an array by splitting on a separator.

How are join() and split() used for URL slugs?

To create a URL slug from a title, use split(' ') to break the title into words, then join('-') to combine them with hyphens instead of spaces, removing spaces from the URL.