Last updated: Mar 4, 2024
Reading timeยท2 min
Use the addition (+) operator to concatenate a string with a variable, e.g.
'hello' + myVar
.
The addition (+) operator is used to concatenate strings or sum numbers.
const example = 'world'; const result = 'hello ' + example; console.log(result); // ๐๏ธ 'hello world'
We used the addition (+) operator to concatenate a string with a variable.
You can use this approach with as many strings and variables as necessary.
const example = 'world'; const result = 'hello ' + example + '!'; console.log(result); // ๐๏ธ 'hello world!'
The addition (+) operator is used to achieve 2 main goals:
If you use the addition (+) operator with a number and a string, it converts the number to a string and concatenates the strings.
const num = 100; const result = num + ' percent'; console.log(result); // ๐๏ธ '100 percent'
Note that this can be confusing if you get the types of the values wrong when trying to sum up numbers.
const num = 100; const result = '100' + num; console.log(result); // ๐๏ธ 100100
If you want to get the correct result, you have to convert the string to a number.
const num = 100; const result = Number('100') + num; console.log(result); // ๐๏ธ 200
You can also use a template literal to concatenate a string with a variable.
Template literals allow us to embed a variable into a string. The variable is then substituted with its value.
const example = 'world'; const result = `hello ${example}`; console.log(result); // ๐๏ธ 'hello world'
We wrapped the string using backticks, which makes it a template literal.
The dollar sign and curly braces part ${}
is an expression that gets
evaluated.
The syntax for template literals is ${variable}
or ${expression}
.
You can add characters before or after the variables.
const variable = 'two'; const result = `one ${variable} three`; console.log(result); // ๐๏ธ one two three
Here are some more examples of using template literals.
const example = 'world'; const result = `hello ${example}!`; console.log(result); // ๐๏ธ 'hello world!' const str = `${50 + 50} percent`; console.log(str); // ๐๏ธ '100 percent'
The expression between the curly braces gets evaluated and placed in the string.
You can learn more about the related topics by checking out the following tutorials: