How to join two strings in JavaScript
By Flavio Copes
Learn how to join two strings in JavaScript using the + operator, the += operator to append in place, or the String concat() method to combine them.
To join two strings in JavaScript you use the + operator. There are a couple of alternatives too, and we’ll look at all of them.
If you have a string name and a string surname, you can assign them to the fullname variable like this:
const name = 'Flavio'
const surname = 'Copes'
const fullname = name + surname
console.log(fullname) // 'FlavioCopes'
Notice the two words are glued together. + does not add any separator, so if you want a space in between you concatenate one yourself:
const fullname = name + ' ' + surname
console.log(fullname) // 'Flavio Copes'
If you don’t want to instantiate a new variable, you can use the += operator to add the second string to the first:
let name = 'Flavio'
name += ' Copes'
Notice that name is declared with let here. += reassigns the variable, so if name was a const you’d get TypeError: Assignment to constant variable.
Alternatively you can also use the concat() method of the String object, which returns a new string concatenating the one you call this method on, with the argument of the method:
const fullname = name.concat(surname)
When you’re joining strings with other text around them, a template literal is often the cleanest option:
const greeting = `Hello ${name} ${surname}!`
console.log(greeting) // 'Hello Flavio Copes!'
And if you have more than two strings, you can put them in an array and call join() with the separator you want:
const parts = ['Flavio', 'Copes']
console.log(parts.join(' ')) // 'Flavio Copes'
Watch out for numbers
One thing that trips people up: + also does addition. If one of the two operands is a string, JavaScript converts the other to a string and concatenates:
const price = 10
const label = price + '2'
console.log(label) // '102'
You expected 12, you got the string '102'. If a value might be a number, convert it explicitly with String() (or the number with Number()) so the intent is clear.
I generally recommend the simplest route, which is using the + (or +=) operator, and template literals when you’re building a longer string out of several pieces.
Related posts about js: