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
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
return (
result +
str +
(values[i] !== undefined
? `<mark>${values[i]}</mark>`
: '')
);
}, '');
}
const name = 'John';
const age = 30;
highlight`My name is ${name} and I am ${age} years old`;
// "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
const Button = styled.button`
background: ${(props) =>
props.primary ? 'blue' : 'white'};
color: ${(props) => (props.primary ? 'white' : 'blue')};
padding: 8px 16px;
`;

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

GraphQL queries:

javascript
const GET_USER = gql`
query GetUser($id: ID!) {
user(id: $id) {
name
email
}
}
`;

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
function safeHtml(strings, ...values) {
const escape = (str) =>
String(str)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
return strings.reduce((result, str, i) => {
return (
result +
str +
(values[i] !== undefined ? escape(values[i]) : '')
);
}, '');
}
const userInput = '<script>alert("xss")</script>';
safeHtml`<p>${userInput}</p>`;
// "<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.