How to Do String Interpolation in JavaScript

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
const AGE = 25; console.log(`I'm ${AGE} years old!`);

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
const NUM1 = 10; const NUM2 = 5; console.log(`The sum is ${NUM1 + NUM2}`);

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
const NUM = 8.3; console.log(`The number is ${NUM}`);

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.