JavaScript String Interpolation

Feb 17, 2021

JavaScript template literals support string interpolation. For example, suppose you wanted to implement a function greet() that says "Hello" to the given name. You implement greet() using string concatenation:

function greet(name) {
  return 'Hello ' + name + '!';
}

But this approach can get messy if you have multiple variables you want to insert into a string. You can instead use a template literal, which is an alternative syntax for declaring a string. A template literal is enclosed using backticks "`":

function greet(name) {
  return `Hello ${name}!`;
}

const str = greet('World');
typeof str; // "string"
str; // "Hello World!"

The ${name} part of the string is called a placeholder. You can put any JavaScript expression in a placeholder, like a function call:

function capitalize(name) {
  return `${name.slice(0, 1).toUpperCase()}${name.slice(1)}`;
}

function greet(name) {
  return `Hello ${capitalize(name)}!`;
}

const str = greet('wOrLd');
typeof str; // "string"
str; // "Hello World!"

With Custom Classes

Remember that JavaScript expressions evaluate to a value. If your placeholder expression evaluates to a non-null object, JavaScript will try to call the object's toString() function to convert it to a string.

Here's how JavaScript handles objects in placeholders:

class User {
  constructor(name) {
    this.name = name;
  }

  toString() {
    return this.name;
  }
}

const user = new User('Bill');

const str = `Hello ${user}!`; // "Hello Bill!"

Error Cases

Template literals don't throw errors if a placeholder expression evaluates to null or undefined.

`Hello ${null}!`; // "Hello null!"
`Hello ${void 0}!`; // "Hello undefined!"

The only case where string interpolation can throw a runtime error is if your placeholder expression evaluates to an object whose toString() function throws an error. For example, JavaScript symbols throw an error when you try to convert them to strings:

const sym = Symbol('test symbol');
// Throws "TypeError: Cannot convert a Symbol value to a string"
const str = `Hello ${sym}!`;

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials