Borislav Hadzhiev
Wed Nov 17 2021·1 min read
Photo by Alexander Popov
Use the addition (+) operator to prepend a string to the beginning of another
string, e.g. "example" + str
. When used with strings, the addition operator
concatenates the strings and returns the result.
const str = 'world'; const result = 'hello ' + str; // 👇️ "hello world" console.log(result);
We used the addition operator to prepend a string to the beginning of another string.
When used with strings, the addition (+) operator concatenates them. When used with numbers, it sums them.
console.log('hello ' + 'world'); // 👉️ "hello world" console.log(5 + 5); // 👉️ 10
An alternative approach is to use a template literal.
To prepend a string to the beginning of another string, use a template
literal, e.g. hello ${str}
. The dollar sign and curly braces part is an
expression that gets evaluated.
const str = 'world'; // template literal const result = `hello ${str}`; // 👇️ "hello world" console.log(result);
Template literals
allow us to use expressions ${}
. In the example, the ${str}
part gets
replaced with the value of the str
variable.
This achieves the same result as using the addition operator, however in my opinion it's a bit of an overkill in this scenario.
The addition (+) operator is more direct and easier to read.