Tagged Template

Learn the functions, uses, and perks of tagged templates.

A template literal may be untagged or tagged.

Tags

Tags are functions that receive the contents of the provided template literal in two parts:

  1. The template object
  2. The evaluated expressions

The template literals you have seen so far are untagged, but we have the option of placing a tag in front of a template literal.

svg viewer

Built-in tagged template function raw()

Before you learn how to write your own tagged template functions, let’s use a built-in tagged template function called raw(). Suppose we want to create a string with some embedded special characters.

In the next example, we create a regular string, but we escape each special character with a backslash.

Press + to interact
'use strict';
//START:ONE
console.log('some special characters: \\ \\n \\b \'');
//END:ONE

The string captures all the special characters in the output, but creating those characters required repetitive use of \ before each special character. Let’s ...

Access this course and 1400+ top-rated courses and projects.