Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 156 ยท Data Types

Tagged Template Literals in Depth

Learn how tag functions really work - the strings and raw arrays, safe HTML escaping, parameterized SQL, dedent and currency tags, invalid escapes and chaining.

You already know that a template literal can fill in ${placeholders}. A tagged template goes one step further: instead of building the string itself, JavaScript hands the pieces to a function you choose, and that function decides what to return. It can be a string, a number, an object, even another function. That one idea powers some of the safest and most expressive code in the language: HTML that escapes itself, SQL queries that cannot be injected, styles written inside JavaScript, translated messages and more.

Template Literals introduced the syntax and String.raw. This lesson goes deeper. You will see exactly what a tag function receives, then write practical tags for safe HTML, parameterized queries, dedenting and formatting, and learn the rules about raw strings, invalid escapes and chained tags.

What a tag function receives

Writing a function name directly in front of a backtick calls that function. There are no parentheses:

JavaScript
tag`Hello ${name}, you have ${count} messages`;

The browser splits the template at every placeholder and calls tag(strings, ...values):

  • strings is an array of the text pieces between placeholders. It always has exactly one more item than there are values. The first and last items can be empty strings.
  • The remaining arguments are the evaluated values, one per placeholder.

For the template above, strings is ["Hello ", ", you have ", " messages"] and the values are name and count. Two extra facts make tags more powerful than they first look:

  • strings also has a raw property: the same pieces before escape sequences such as \n were processed.
  • strings is frozen, and the very same array object is passed every time that particular spot in the source is evaluated. A tag can use it as a cache key.
JS Look inside a tag call

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the output, strings holds a real tab and newline, while raw still shows the two characters \t and \n. The loop proves the identity rule: the array depends on the location in the source, not on the values.

The standard recipe: zip strings and values

Almost every tag that returns a string follows the same pattern. Start with the first piece, then append "value, next piece" for each value:

JavaScript
function zip(strings, values, transform = (v) => v) {
  let out = strings[0];
  values.forEach((value, i) => {
    out += transform(value) + strings[i + 1];
  });
  return out;
}

Because you can transform each value on its way in, tags are ideal for anything where values must be treated differently from the surrounding text. That difference is the whole point: the text between placeholders was written by you (trusted), while the values may come from users (untrusted).

Safe HTML

The classic problem: putting user text into HTML lets an attacker inject markup. A tag can escape every value automatically, so developers cannot forget:

JS A tag that escapes HTML

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The attacker's <img onerror> becomes harmless text, the nested list renders correctly, and only markup you explicitly wrap in SafeHtml is left alone. Libraries such as lit-html build on exactly this design. This is a great pattern, but it is not a replacement for understanding output encoding: the escaping above is right for HTML text and quoted attribute values, not for URLs, inline scripts or CSS (see XSS, CSRF and Safe DOM Updates).

Parameterized queries

The same idea defeats SQL injection. Never glue user input into SQL text. Send the SQL with placeholders and the values separately. A tag can build both from one readable template:

JS A tag that builds a parameterized query

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The glued string now contains an attack that changes the meaning of the query. The tagged version keeps the injected text in the values array, where the database driver treats it strictly as data. Libraries for Postgres and other databases use exactly this API (sql\...``), and you pass query.text and query.values to the driver. The reduce call has no initial value, so it starts with strings[0] and then receives each later piece with its index i, which lines up with the value number.

Utility tags: dedent and money

Tags are also handy for ordinary formatting chores. A dedent tag lets you indent multi-line text in your source without carrying that indentation into the string, and a money tag can format every number the same way using Intl:

JS Two utility tags

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first tag keeps the relative indentation (the second line stays indented by two spaces) and removes the shared four. In the second one, the type of each value decides how it is printed. Notice both use reduce without a starting value, which is the shortest form of the zip recipe: the callback runs for each piece after the first and reads the preceding value as values[i - 1].

Tags can return anything

A tag is just a function, so its result does not have to be a string. This one returns a structure that another part of the program can walk, which is how template engines and CSS-in-JS libraries work:

JS Return an object, not a string

Press Run (or Ctrl + Enter) to see the console output here.

No output.

msg returns an object whose template could be used as a translation key ("Moved {} files to {}") while render can produce plain text or markup. In the last line, repeat(3) returns a function, and that function is used as the tag, a pattern known as a curried tag. It also shows that String.raw is just a tag function you can call yourself with an object that has a raw array.

Raw strings and invalid escapes

Inside an ordinary template literal, an escape such as \u followed by something that is not a valid Unicode escape is a syntax error. Tagged templates relax this rule, so tags can process languages that use backslashes freely, like LaTeX or Windows paths. In that case the strings entry for that piece is undefined, while strings.raw always has the original text:

JS Cooked versus raw

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first call has undefined for the cooked piece, because \u must be followed by four hex digits and \x by two, but the raw version is perfect. (A plain \U would not be a problem: unknown escapes just drop the backslash.) Use strings.raw whenever backslashes must survive untouched, as String.raw does.

When tags are the right tool

Reach for a tag when:

  • values need different treatment from the template text (escaping, parameterizing, formatting);
  • you want readable syntax for a small language (HTML, SQL, CSS, GraphQL, regular expressions, messages to translate);
  • the template shape is static and reusable, so you can cache work by the strings array.

Skip them when plain interpolation is enough. A tag can hide surprising behavior, so give it a clear name (html, sql, css), keep it small, document what it does with values, and never silently ignore a value you could not handle.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. For the call taga${1}b${2}c, how many items are in the strings array?

    There is always one more text piece than values. Two values give three pieces: "a", "b" and "c".
  2. 2. Why is an html tag that escapes every inserted value safer than building markup with ordinary template literals?

    The tag treats the template text as trusted and every value as untrusted, escaping it automatically.
  3. 3. What is strings.raw for?

    strings.raw keeps the original source text, including backslashes. String.raw is built on it.
  4. 4. Why does a parameterized query tag return both text and values?

    Keeping user-supplied values separate from the query text is what prevents SQL injection.
  5. 5. What does a tag function have to return?

    A tag is an ordinary function. Its return value is the value of the whole tagged template expression.

Summary

  • A tag function is called by writing its name right before a template literal: it receives a frozen array of text pieces (with a raw property) and then the values.
  • There is always one more piece than values; the standard recipe zips them: first piece, then value, next piece, and so on.
  • The strings array is the same object each time a given source location runs, so it can be cached.
  • Tags can escape HTML, build parameterized SQL, dedent text, format numbers or return any structure, and they can be curried or chained.
  • In tagged templates invalid escapes are allowed: the cooked piece becomes undefined, and strings.raw keeps the original text.
  • Treat the template text as trusted, the values as untrusted, and name your tags clearly.

Next, continue with Booleans, the simplest data type of all.