join() to Convert Arrays to Strings
You'll learn: How to transform an array into a single string by combining all its elements with a separator of your choice.
What Is join()?
The join() method takes all the elements in an array and glues them together into one string. You get to decide what character (or characters) should appear between each element—this is called the separator.
Think of it like stringing beads on a necklace: each bead is an array element, and the separator is the thread connecting them all together.
The Syntax
const fruits = ['apple', 'banana', 'cherry'];
const result = fruits.join(', ');
console.log(result); // "apple, banana, cherry"
The separator goes inside the parentheses. If you don't provide one, JavaScript uses a comma by default:
const colors = ['red', 'green', 'blue'];
console.log(colors.join()); // "red,green,blue"
Common Use Cases
Empty string separator (no space between elements):
const letters = ['H', 'e', 'l', 'l', 'o'];
console.log(letters.join('')); // "Hello"
Space separator:
const words = ['Good', 'morning', 'world'];
console.log(words.join(' ')); // "Good morning world"
Custom separator:
const items = ['eggs', 'milk', 'bread'];
console.log(items.join(' | ')); // "eggs | milk | bread"
Important Details
join()does not mutate the original array—it returns a new string- Non-string elements are automatically converted to strings
- The original array remains unchanged
Key Takeaway: Use join() when you need to convert an array into a readable string format, specifying exactly what separator should appear between each element.