Skip to main content

What does a "tagged template literal" do?

What "tagged template literals" are

Normally a template string just inserts variables:

javascript
const name = 'Alex'; console.log(`Hello, ${name}!`); // -> Hello, Alex!

But if you put a function name before the template string, JavaScript calls that function and passes it:

  1. An array of the string parts (between substitutions)
  2. All the substituted values (${...})
javascript
tag`Hello, ${name}!`

This is a tagged template.


Example 1: basic

javascript
function tag(strings, ...values) { console.log(strings); // [ 'Hello, ', '!' ] console.log(values); // [ 'Alex' ] } const name = 'Alex'; tag`Hello, ${name}!`;

What happens under the hood:

javascript
// The interpreter does roughly this: tag(["Hello, ", "!"], "Alex");

Example 2: processing content

You can use a tag function to build your own template languages, format strings, or safely process data (for example, guard against XSS).

javascript
function highlight(strings, ...values) { return strings.reduce( (result, str, i) => result + str + (values[i] ? `<b>${values[i]}</b>` : ''), '' ); } const name = 'Alex'; const lang = 'JavaScript'; const message = highlight`Hello, ${name}! You love ${lang}.`; console.log(message); // -> Hello, <b>Alex</b>! You love <b>JavaScript</b>.

Here we "caught" each ${...} substitution and wrapped it in <b>…</b>.


Example 3: guarding against XSS (safe HTML)

javascript
function safeHTML(strings, ...values) { const escape = str => String(str) .replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;"); return strings.reduce( (res, str, i) => res + str + (values[i] ? escape(values[i]) : ''), '' ); } const userInput = '<script>alert("Hacked!")</script>'; const html = safeHTML`<div>User says: ${userInput}</div>`; console.log(html); // -> <div>User says: &lt;script&gt;alert("Hacked!")&lt;/script&gt;</div>

Thanks to the tag, the HTML stays safe (no <script> execution at all).


Example 4: formatting strings

javascript
function format(strings, ...values) { return strings.reduce( (res, str, i) => res + str + (values[i] !== undefined ? `[${values[i]}]` : ''), '' ); } const a = 10, b = 20; console.log(format`Sum of ${a} and ${b} is ${a + b}`); // -> Sum of [10] and [20] is [30]

Example 5: real-world uses

  1. Styled Components (React)
javascript
const Button = styled.button` background: ${props => props.primary ? 'blue' : 'gray'}; color: white; `;

Here styled.button is a tag function that receives the template and builds a CSS object. 2. GraphQL queries

javascript
const query = gql` query GetUser { user(id: 1) { name } } `;
  1. i18n (internationalization)
javascript
translate`Welcome, ${userName}!`;

How it works under the hood

When you write:

javascript
tag`Hello, ${name}!`

JS does roughly this:

javascript
tag(["Hello, ", "!"], name);

That is:

  • strings is the array of all the string parts between substitutions
  • values is the array of all the substituted values

Comparison with regular template strings

FeatureRegular template stringTagged template literal
SyntaxHello, ${name}tag\Hello, ${name}``
SubstitutionsInserted automaticallyHandled manually
FlexibilityInterpolation onlyCan filter, format, escape
Use caseSimple stringsTemplating, security, CSS-in-JS, SQL, i18n

Summary

What it doesExplanation
Tagged template literalA template string preceded by a function (the tag) that receives the strings and values
Why it's neededTo control how ${} substitutions are joined and interpreted
Where it's usedSafe HTML, CSS-in-JS, formatting, internationalization
Key parametersstrings (template parts), values (substituted values)

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.