Skip to content

Template literals

Template literals is an expression interpolation for single and multiple-line strings.

In other words, it is a new string syntax in which you can conveniently use any JavaScript expressions (variables for instance).

Sample code

1
2
3
4
const name = "Nick";
`Hello ${name}, the following expression is equal to four : ${2+2}`;

// Hello Nick, the following expression is equal to four: 4

External resources

Tagged template literals

Template tags are functions that can be prefixed to a template literal. When a function is called this way, the first parameter is an array of the strings that appear between the template's interpolated variables, and the subsequent parameters are the interpolated values. Use a spread operator ... to capture all of them. (Ref: MDN).

Note : A famous library named styled-components heavily relies on this feature.

Below is a toy example on how they work.

function highlight(strings, ...values) {
  const interpolation = strings.reduce((prev, current) => {
    return prev + current + (values.length ? "<mark>" + values.shift() + "</mark>" : "");
  }, "");

  return interpolation;
}

const condiment = "jam";
const meal = "toast";

highlight`I like ${condiment} on ${meal}.`;
// "I like <mark>jam</mark> on <mark>toast</mark>."

A more interesting example:

function comma(strings, ...values) {
  return strings.reduce((prev, next) => {
    let value = values.shift() || [];
    value = value.join(", ");
    return prev + next + value;
  }, "");
}

const snacks = ['apples', 'bananas', 'cherries'];
comma`I like ${snacks} to snack on.`;
// "I like apples, bananas, cherries to snack on."

External resources 2