Skip to content

String Concatenation

Concatenation means joining strings end to end. JavaScript has four common ways to do it: the + operator, the concat() method, template literals and the array method join(). Template literals are the usual choice in modern code, because they show the finished string’s shape and convert values to text without surprises.

const firstName = 'Grace';
const lastName = 'Hopper';
console.log(firstName + ' ' + lastName);
console.log(firstName.concat(' ', lastName));
console.log(`${firstName} ${lastName}`);
console.log([firstName, lastName].join(' '));

This prints:

Grace Hopper
Grace Hopper
Grace Hopper
Grace Hopper

concat() takes any number of arguments, but it is rarely used, since + and template literals are shorter. join() is the natural fit when the pieces are already in an array, especially when they need a separator such as a comma.

The += operator adds to the end of a string variable. The variable needs let, because each += assigns a new string to it.

let list = 'Shopping:';
for (const item of ['eggs', 'flour', 'sugar']) {
list += ` ${item}`;
}
console.log(list);

This prints:

Shopping: eggs flour sugar

Older advice said to collect pieces in an array and join() them for speed. Modern engines handle repeated += well, so choose whichever reads more clearly.

+ adds when both sides are numbers and joins when either side is a string, working from left to right. Once a string appears, every later + joins.

console.log('Total: ' + 2 + 3);
console.log('Total: ' + (2 + 3));
console.log(2 + 3 + ' items');
console.log(`Total: ${2 + 3}`);

This prints:

Total: 23
Total: 5
5 items
Total: 5

The first line joins 2 and then 3 onto the text. Brackets force the addition first, and a template literal avoids the question, because the expression inside ${} is worked out before it is turned into text.

Each method converts non-string values to text, and the results are not always useful. null and undefined become their names, an array becomes its items joined with commas, and a plain object becomes [object Object].

console.log('a'.concat(1, null, undefined, [2, 3]));
console.log('Items: ' + ['tea', 'milk']);
console.log('Basket: ' + { items: 2 });

This prints:

a1nullundefined2,3
Items: tea,milk
Basket: [object Object]

To show an object’s contents, convert it explicitly with JSON.stringify(), which Stringify optional parameters describes.

A template literal can span several lines, and the line breaks are kept. With +, each line break has to be written as \n.

const name = 'Grace';
const items = ['notebook', 'pens'];
const message = `Dear ${name},
Your order of ${items.join(' and ')} has shipped.`;
console.log(message);

This prints:

Dear Grace,
Your order of notebook and pens has shipped.

Tagged template literals goes further with template literals.

Steve Griffith covers this topic in his video JavaScript String Concatenation.