The String concat() method

By

Learn how the JavaScript concat() method joins the current string with one or more strings passed as arguments, returning the combined string as a result.

~~~

The concat() method concatenates the current string with one or more strings passed as arguments, and returns the combined string.

Example:

'Flavio'.concat(' ').concat('Copes') //'Flavio Copes'

You can specify a variable number of arguments, and if you do so all those arguments will be concatenated to the original string:

'Flavio'.concat(' ', 'Copes') //'Flavio Copes'

The original string doesn’t change

concat() returns a new string. It never modifies the one you call it on, because strings in JavaScript are immutable. No string method can change a string in place.

const name = 'Flavio'
const full = name.concat(' Copes')

name //'Flavio'
full //'Flavio Copes'

If you want to keep the result, assign it to a variable, like I did with full here.

What happens with non-string arguments?

If you pass something that’s not a string, concat() converts it to a string first:

'Total: '.concat(42) //'Total: 42'
'Items: '.concat([1, 2, 3]) //'Items: 1,2,3'

The array became 1,2,3 because that’s its string representation. This conversion is silent, so watch what you pass in. An object, for example, turns into [object Object], which is rarely what you want.

Calling concat() with no arguments returns a copy of the string:

'Flavio'.concat() //'Flavio'

Should you use concat()?

In practice, almost never. The + operator does the same job with less noise:

'Flavio' + ' ' + 'Copes' //'Flavio Copes'

And when you mix strings and variables, template literals are clearer still:

const name = 'Flavio'
`Hello ${name}` //'Hello Flavio'

I mostly meet concat() when reading older code. Knowing how it behaves helps you understand that code, but for new code I reach for + or template literals.

One thing to be careful about when you switch to +: it also performs addition. '5' + 3 gives you '53', but 5 + 3 gives you 8. The result depends on the types involved. concat() never has that ambiguity, since it always converts everything to strings.

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about js: