Concatenate a String with a Variable in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

banner

Photo by Jean Gerber

Concatenate a String with a Variable #

Use a template literal to concatenate a string with a variable, e.g. hello ${myVar}. Template literals allow us to embed a variable into a string. The variable is then substituted with its value.

index.js
const example = 'world'; const result = `hello ${example}`; console.log(result); // ๐Ÿ‘‰๏ธ 'hello world'

An easy way to think about the template literal syntax is - the part between the curly brackets ${} gets evaluated.

Note that the string is enclosed in backticks (``), not single quotes.

Here are some more examples of using template literals.

index.js
const example = 'world'; const result = `hello ${example}!`; console.log(result); // ๐Ÿ‘‰๏ธ 'hello world!' const str = `${50 + 50} percent`; console.log(str); // ๐Ÿ‘‰๏ธ 100 percent

A common alternative is to use the addition (+) operator.

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.

index.js
const example = 'world'; const result = 'hello ' + example; console.log(result); // ๐Ÿ‘‰๏ธ 'hello world'

We used the addition (+) operator to concatenate a string to a variable.

You can use this approach as many times as you need.

index.js
const example = 'world'; const result = 'hello ' + example + '!'; console.log(result); // ๐Ÿ‘‰๏ธ 'hello world!'
The syntax of the addition (+) operator is easier to read and more beginner friendly, than using template literals.

The addition (+) operator is used to achieve 2 main goals:

  1. concatenate strings
  2. sum numbers

If you use the addition (+) operator with a number and a string, it converts the number to a string and concatenates the strings.

index.js
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 ot sum numbers.

index.js
const num = 100; const result = '100' + num; console.log(result); // ๐Ÿ‘‰๏ธ 100100
It's a matter of personal preference, however the template literal syntax is more widely used to concatenate strings with variables.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee