Curriculum Series

What are tagged templates in JavaScript?

What are tagged templates in JavaScript?

What are tagged templates in JavaScript?

JavaScript

The short answer

Tagged templates let you process template literal strings with a function. Instead of just interpolating values, the function receives the string parts and the values separately, giving you full control over how the final string is built. Libraries like styled-components and GraphQL's gql use tagged templates.

How they work

A tagged template is a function call where the argument is a template literal:

JAVASCRIPT
1function highlight(strings, ...values) {
2 return strings.reduce((result, str, i) => {
3 return (
4 result +
5 str +
6 (values[i] !== undefined
7 ? `<mark>${values[i]}</mark>`
8 : '')
9 );
10 }, '');
11}
12
13const name = 'John';
14const age = 30;
15
16highlight`My name is ${name} and I am ${age} years old`;
17// "My name is <mark>John</mark> and I am <mark>30</mark> years old"

The function receives:

  • strings — an array of the static parts: ["My name is ", " and I am ", " years old"]
  • ...values — the interpolated values: ["John", 30]

Real-world examples

styled-components:

JAVASCRIPT
1const Button = styled.button`
2 background: ${(props) =>
3 props.primary ? 'blue' : 'white'};
4 color: ${(props) => (props.primary ? 'white' : 'blue')};
5 padding: 8px 16px;
6`;

The styled.button tag function processes the CSS template, injects the dynamic values, and creates a React component.

GraphQL queries:

JAVASCRIPT
1const GET_USER = gql`
2 query GetUser($id: ID!) {
3 user(id: $id) {
4 name
5 email
6 }
7 }
8`;

The gql tag function parses the GraphQL query string into an AST (Abstract Syntax Tree) that the GraphQL client can use.

HTML escaping for security:

JAVASCRIPT
1function safeHtml(strings, ...values) {
2 const escape = (str) =>
3 String(str)
4 .replace(/&/g, '&amp;')
5 .replace(/</g, '&lt;')
6 .replace(/>/g, '&gt;');
7
8 return strings.reduce((result, str, i) => {
9 return (
10 result +
11 str +
12 (values[i] !== undefined ? escape(values[i]) : '')
13 );
14 }, '');
15}
16
17const userInput = '<script>alert("xss")</script>';
18safeHtml`<p>${userInput}</p>`;
19// "<p>&lt;script&gt;alert("xss")&lt;/script&gt;</p>"

Interview Tip

Show the basic mechanism (function receives strings array and values), then give a real-world example like styled-components or HTML escaping. The key insight is that tagged templates give you control over how interpolated values are processed, which is useful for security (escaping) and DSLs (CSS-in-JS, GraphQL).

Why interviewers ask this

This is an advanced JavaScript feature that many developers use (styled-components, GraphQL) without understanding how it works. Interviewers ask about it to see if you understand the underlying mechanism behind popular libraries.

Finished reading?

Mark this topic as solved to track your progress.