Concatenate a String with a Variable in JavaScript

avatar

Borislav Hadzhiev

2 min

banner

Photo from Unsplash

Concatenate a String with a Variable in JavaScript #

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 with a variable.

You can use this approach with as many strings and variables as necessary.

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

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 to sum numbers.

index.js
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.

index.js
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.

Concatenate a String with a Variable using a template literal #

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'

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.

index.js
const variable = 'two'; const result = `one ${variable} three`; console.log(result); // ๐Ÿ‘‰๏ธ one two three
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'

The expression between the curly braces gets evaluated and placed in the string.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2023 Borislav Hadzhiev