W3docs

How to Do String Interpolation in JavaScript

Read this tutorial and learn the simplest method of doing a string interpolation in JavaScript. Also, read information about string literal and placeholder.

Replacement of placeholders with values inside of a string literal is called string interpolation.

In JavaScript, the template literals (also template string) wrapped in backticks **()** that supports the string interpolation and ${expression} ` as placeholder perform the string interpolation like this:

Javascript string interpolation and placeholder expression

javascript— editable

The placeholder has the following format: ${expressionToEvaluate} . The expression inside the placeholder can be:

  • variables: ${myVar}
  • operators: ${n1 + n2}, ${cond ? 'val 1' : 'val 2'}
  • even function calls ${myFunc('argument')}

Example of operator:

Javascript string interpolation and placeholder expression

javascript— editable

The placeholder expression output is implicitly converted to a string. For example, a number in a placeholder is converted to a string:

Javascript string interpolation and placeholder expression

javascript— editable

It is important that any string that uses interpolation be wrapped in backticks (`), not “double quotes” or ‘single quotes’. When you use backticks, you create a Template Literal, which is just a string that can accept embedded code.