How to Concatenate Strings with a Separator in JavaScript
A frequent task in programming is to join several strings together into a single string, with a separator character between each element. You might need to create a comma-separated list for a CSV file, a hyphenated string for a URL slug, or simply join a first and last name with a space. The modern and most effective way to do this in JavaScript is with the Array.prototype.join() method.
This guide will teach you how to use the join() method, how to handle common edge cases like empty or null values, and why this approach is superior to manual string concatenation.
The Core Method: Array.prototype.join()
The join() method is the standard tool for this job. It creates and returns a new string by concatenating all of the elements in an array, separated by a specified separator string.
The logic:
- Place all the strings you want to join into an array.
- Call the
.join()method on the array, passing your desired separator as the argument.
Syntax: ['string1', 'string2', 'string3'].join(separator)
Basic Example: Joining Strings with Different Separators
This example demonstrates how to join an array of strings with a comma and a hyphen.
Problem: you have several separate strings that you need to combine into one.
// Problem: How to join these into "tutorial-reference-com"?
const part1 = 'tutorial';
const part2 = 'reference';
const part3 = 'com';
Solution:
const parts = ['tutorial', 'reference', 'com'];
// Join with a comma
const commaSeparated = parts.join(',');
console.log(commaSeparated); // Output: "tutorial,reference,com"
// Join with a hyphen
const hyphenSeparated = parts.join('-');
console.log(hyphenSeparated); // Output: "tutorial-reference-com"
// Join with a space and a separator string
const spacedSeparated = parts.join(' | ');
console.log(spacedSeparated); // Output: "tutorial | reference | com"
If you call join() with no separator (parts.join()), it will default to using a comma. If you provide an empty string (parts.join('')), it will join the elements with no separator at all ('tutorialreferencecom').
How to Handle null, undefined, or Empty String Values
A common issue arises when your array contains "empty" values. The join() method converts null and undefined to empty strings, which can result in confusing output with extra separators.
Problem:
const data = ['tutorial', '', 'reference', null, 'com', undefined];
// This produces undesirable double separators.
const result = data.join('-');
console.log(result); // Output: "tutorial--reference--com-"
The Solution: Filter the Array First
The best practice is to filter out any "falsy" values from the array before joining it. This ensures a clean and predictable result. Falsy values in JavaScript include '' (empty string), null, and undefined.
const data = ['tutorial', '', 'reference', null, 'com', undefined];
const cleanResult = data
.filter(element => element) // The `Boolean` function could also be used: .filter(Boolean)
.join('-');
console.log(cleanResult); // Output: "tutorial-reference-com"
How it works: The filter(element => element) trick works because falsy values like '', null, and undefined will evaluate to false and be removed by the filter, while truthy string values will be kept.
Why join() is Better Than Manual Concatenation
Before join() was widely used, developers would build strings with a loop and the + operator.
The Old, Clumsy Method
const parts = ['tutorial', 'reference', 'com'];
let result = '';
for (let i = 0; i < parts.length; i++) {
result += parts[i];
// We have to add this messy logic to avoid a trailing separator
if (i < parts.length - 1) {
result += '-';
}
}
console.log(result); // Output: "tutorial-reference-com"
The join() method is superior because it is:
- More Concise: It's a single, declarative method call.
- More Readable: Its intent is immediately clear.
- Less Error-Prone: It automatically handles the logic of not adding a separator after the last element.
Conclusion
For concatenating a list of strings with a separator, the Array.prototype.join() method is the standard, most effective tool in JavaScript.
- The basic syntax is straightforward:
['a', 'b'].join('-'). - For arrays that may contain empty,
null, orundefinedvalues, the recommended best practice is to filter them out first:array.filter(Boolean).join(separator). - Always prefer
join()over manual concatenation with aforloop and the+operator.
By using join() correctly, you can write cleaner, more declarative, and more maintainable code.