join()
ES3+Creates and returns a new string by concatenating all elements in an array.
Syntax
array.join(separator)Parameters
separator string optionalString to separate each element (default: comma)
Return Value
A string with all array elements joined
Examples
const words = ['Hello', 'World'];
console.log(words.join(' '));
console.log(words.join('-')); 📌 When to Use
Use join() when you need to convert an array into a string with elements separated by a custom delimiter. Perfect for creating CSV lines, building paths, formatting display text, or generating readable lists.
⚠️ Common Mistakes
Forgetting that null and undefined values become empty strings in the result
Using join() without a separator when you want no separator - pass empty string: join("")
Using string concatenation in a loop instead of array.push() then join()
✅ Best Practices
Use join("\n") to create multi-line strings from array elements
For building HTML, filter out falsy values first: arr.filter(Boolean).join("")
Use join() with map() for formatted output: items.map(i => i.name).join(", ")
⚡ Performance Notes
join() is highly optimized and faster than repeated string concatenation. When building strings in loops, always prefer pushing to an array and joining at the end. For very large arrays, join() is still efficient.
🌍 Real World Example
Building a File Path
Create a properly formatted file path from an array of path segments
const pathSegments = ['users', 'john', 'documents', 'report.pdf'];
const filePath = pathSegments.join('/');
// filePath: 'users/john/documents/report.pdf'
// Creating a comma-separated list with "and" before the last item
const authors = ['Alice', 'Bob', 'Charlie'];
const formatted = authors.length > 1
? `${authors.slice(0, -1).join(', ')} and ${authors.slice(-1)}`
: authors[0];
// formatted: 'Alice, Bob and Charlie'