What are tagged templates in 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:
1function highlight(strings, ...values) {2 return strings.reduce((result, str, i) => {3 return (4 result +5 str +6 (values[i] !== undefined7 ? `<mark>${values[i]}</mark>`8 : '')9 );10 }, '');11}1213const name = 'John';14const age = 30;1516highlight`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:
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:
1const GET_USER = gql`2 query GetUser($id: ID!) {3 user(id: $id) {4 name5 email6 }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:
1function safeHtml(strings, ...values) {2 const escape = (str) =>3 String(str)4 .replace(/&/g, '&')5 .replace(/</g, '<')6 .replace(/>/g, '>');78 return strings.reduce((result, str, i) => {9 return (10 result +11 str +12 (values[i] !== undefined ? escape(values[i]) : '')13 );14 }, '');15}1617const userInput = '<script>alert("xss")</script>';18safeHtml`<p>${userInput}</p>`;19// "<p><script>alert("xss")</script></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.