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:
splitthe title on spaces, optionally remove or replace some words, thenjointhe 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.