What Are Tagged Template Literals?
Learn how tagged template literals work in JavaScript, how tag functions receive strings and values, with real examples.
Expected Interview Answer
A tagged template literal is a template string prefixed with a function name, which causes JavaScript to call that function with the literal split into an array of static string segments plus the interpolated expression values as separate arguments, letting the function process or transform the string before producing the final result.
Normally, a template literal like `` `Hello ${name}` `` is just string interpolation evaluated immediately. Tagging it, as in `` tag`Hello ${name}` ``, instead invokes `tag(strings, ...values)`, where `strings` is an array of the literal text pieces (with a `.raw` property giving the unescaped source text) and `values` are the evaluated expressions in order. The tag function has full control: it can escape values for safety (this is exactly how styled-components and other CSS-in-JS libraries build scoped styles, and how libraries sanitize against SQL/HTML injection), localize text, or build a completely different data structure like a GraphQL query AST. Because the tag function receives the static and dynamic parts separately rather than a single concatenated string, it can apply different treatment to user-supplied values (e.g., always HTML-escape them) versus the literal template text (trusted, author-written), which is the core safety property that makes tagged templates useful for things like a `html` sanitizing tag.
- Separates trusted static text from dynamic interpolated values automatically
- Enables safe escaping/sanitization of interpolated values (e.g., against XSS or SQL injection)
- Powers DSLs like styled-components CSS, GraphQL query builders, and i18n tagging
- Gives access to raw, unescaped source text via `strings.raw`
AI Mentor Explanation
A tagged template literal is like handing a match report to an editor as two separate stacks โ the fixed commentary sentences and the live stat numbers plugged in โ instead of one merged paragraph. The editor can then apply a rule, like bolding every stat number but leaving the commentary text untouched, because the two stacks stay separate until the editor decides how to combine them. If it had all been one merged string already, the editor could not tell which parts were numbers versus prose. That separation of fixed text from dynamic values, handed to a processing function, is exactly what a tag function receives.
Step-by-Step Explanation
Step 1
Write a tag function
Define `function tag(strings, ...values) { ... }` that will receive the split parts.
Step 2
Apply it to a template literal
Prefix the backtick string with the function name: `` tag`Hi ${name}!` ``, no parentheses or call syntax needed.
Step 3
Engine splits and invokes
JavaScript calls `tag(["Hi ", "!"], name)` โ static segments as an array, interpolated values as remaining arguments.
Step 4
Tag function returns the result
The function processes/escapes/transforms the parts and returns whatever value it wants (string, object, anything) as the expression's result.
What Interviewer Expects
- Correct explanation of how strings and values arrive as separate arguments
- Awareness of `strings.raw` for accessing unescaped source text
- A concrete real-world use case (styled-components, SQL/HTML sanitization, i18n)
- Understanding that the tag function can return any value, not just a string
Common Mistakes
- Thinking tagged templates just concatenate strings like normal template literals
- Forgetting the tag function receives values as separate arguments, not pre-interpolated
- Not knowing about `strings.raw` for accessing the literal, unescaped source
- Assuming a tag function must return a string when it can return any type
Best Answer (HR Friendly)
โTagged template literals let you put a function name right before a template string, and that function gets to see the fixed text and the inserted values separately before deciding how to combine them. It is how tools like styled-components turn a CSS-looking string into actual styling logic, and how some libraries automatically escape user input for safety.โ
Code Example
function escapeHtml(value) {
return String(value)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
}
function html(strings, ...values) {
return strings.reduce((result, str, i) => {
const value = i < values.length ? escapeHtml(values[i]) : ''
return result + str + value
}, '')
}
const userInput = '<script>alert(1)</script>'
const safe = html`<p>Comment: ${userInput}</p>`
console.log(safe)
// <p>Comment: <script>alert(1)</script></p>Follow-up Questions
- How does styled-components use tagged templates to generate scoped CSS?
- What is the difference between `strings` and `strings.raw` in a tag function?
- How would you build a simple SQL-injection-safe query tag function?
- Can a tag function return a non-string value? Give an example.
MCQ Practice
1. What does a tag function receive as its first argument?
The first argument is always an array of the literal text pieces between interpolations.
2. What is `strings.raw` used for?
strings.raw preserves the source exactly as written, including unprocessed escape sequences.
3. Which library famously uses tagged templates to author CSS in JS?
styled-components uses a tag function on template literals to parse CSS and generate scoped class names.
Flash Cards
What is a tagged template literal? โ A template literal prefixed with a function that receives the static and dynamic parts separately.
What arguments does the tag function get? โ An array of string segments, followed by the interpolated values as separate arguments.
What does strings.raw give you? โ The unescaped, literal source text of the template segments.
Name a real-world use. โ styled-components uses it to parse CSS written as a template literal.