Member-only story
How to Combine Multiple Strings with JavaScript
Combining strings is something that we have to do often with JavaScript.
In this article, we’ll look at how to combine them with JavaScript.
Plus Operator
The +
operator also lets us combine multiple strings together.
For instance, we can write:
const firstName = 'james',
lastName = 'smith';const greeting = 'hi' + ' ' + firstName + ' ' + lastName;
This is uglier than the other solutions since we have to use the +
sign for each string expression.
Mutative Concatenation
We can concatenate to existing strings.
For instance, we can write:
const firstName = 'james',
lastName = 'smith';let greeting = 'hi'
greeting += ' ' + firstName + ' ' + lastName;
Then we concatenate to the greeting
string.
We can’t use const
to declare greeting
since we’re assigning a new value to it.
Template Literals
Template literals are a newer string type that lets us interpolate expressions into them,.