String interpolation in JavaScript

Published June 1, 2020

In JavaScript, there are three ways to create strings, or string literals.

We can use single quotes:

const hello = 'Hello, World!';

We can use double quotes:

const hello = "Hello, World";

We can use a pair of backticks, which permits string interpolation.

const hello = `Hello, World!`;

String Interpolation

String interpolation consists of replacing placeholders with values in a string.

String interpolation in JavaScript is done by using template literals or template strings. These are strings with placeholders within the backticks.

const value = 10;
const message = `The value is ${value}.`;
console.log(message); // The value is 10.

The Placeholder

The placeholder can contain string variables.

const hello = 'Hello';
const world = 'World';
const message = `${hello}, ${world}!`;
console.log(message); // Hello, World!

The placeholder can contain operators.

const first = 2;
const second = 3;
const message = `The sum of ${first} and ${second} is ${first + second}.`;
console.log(message); // The sum of 2 and 3 is 5.

The placeholder can contain function calls.

function sum(first, second) {
  return first + second;
}

const first = 2;
const second = 3;
const message = `Sum: ${sum(first, second)}.`;
console.log(message); // Sum: 5.

Placeholder String Conversion

The expression in a placeholder is implicitly converted to a string.

A number in a placeholder is transformed into a string:

const value = 11.2;
const message = `Number is ${value}.`;
console.log(message); // Number is 11.2.

The expression in the placeholder ${value} is transformed into a string and inserted into the interpolation.

If the placeholder contains an object, the object is converted to a string as well. The toString() method of the object is called to get the string representation of the object.

What if we insert an array into a template string?

const myArray = [2, 4, 6];
const message = `The array values are ${myArray}.`;
console.log(message); // The array values are 2,4,6.

The toString() method on an array will do a join(',') on the array when it is converted to a string.

Escaping placeholders

Since the placeholder ${} holds a special meaning in interpolated strings, if we want to use a sequence of characters with ${}, they must be escaped.

const mySymbol = `Symbol ${xyz}`;
console.log(mySymbol); // ReferenceError: xyz is not defined

Using ${xyz} directly will throw an error because ${xyz} is expected to be a placeholder. Adding a backslash \ before the placeholder will treat it as a sequence of characters instead.

const mySymbol = `Symbol \${xyz}`;
console.log(mySymbol); // Symbol ${xyz}

The same is true for the following sequences of characters.

const mySymbols = `Symbols \${xyz} \${xyz \${`;
console.log(mySymbols); // Symbols ${xyz} ${xyz ${