# Tagged Template Literals

> What are tagged template literals in JavaScript? What are practical use cases?

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-tagged-templates
Last updated: 2026-11-28

Difficulty: Advanced

## Question

What are tagged template literals in JavaScript? What are practical use cases?

## Answer

Tagged template literals allow a function (the tag) to process a template literal. The tag function receives the static string parts as an array and the interpolated values as separate arguments.

Syntax: tag`template ${expr} string`

Tag function signature: tag(strings, ...values)

Practical uses:

- SQL query builders: escape values to prevent SQL injection
- HTML sanitization: escape user content to prevent XSS
- i18n/translation: localize strings
- styled-components: CSS-in-JS
- GraphQL: gql tag in Apollo Client

**A tag function receives the pieces. Change the values under Tweak; the tag decides how they're combined.**

1. **tag\`...\` is a function call**: tag(strings, ...values).
2. **strings has one more item than values**: Even when the template ends with an expression.
3. **strings.raw**: The unescaped original text.
4. **Uses**: HTML escaping, safe SQL, styled-components, i18n.

## Code examples

### HTML Escaping with Tagged Templates

```
function html(strings, ...values) {
  return strings.reduce((result, str, i) => {
    const value = values[i - 1];
    const escaped = String(value ?? '')
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;');
    return result + escaped + str;
  });
}

const userInput = '<script>alert("XSS")</script>';
const username = 'Alice & Bob';

const unsafe = `<div>Hello ${userInput}</div>`;
console.log(unsafe);

const safe = html`<div>Hello ${userInput}, ${username}</div>`;
console.log(safe);
```

The html tag automatically escapes interpolated values. This prevents XSS when building HTML strings from user input.

### SQL Builder Pattern

```
function sql(strings, ...values) {
  let query = '';
  const params = [];
  strings.forEach((str, i) => {
    query += str;
    if (i < values.length) {
      params.push(values[i]);
      query += `$${params.length}`;
    }
  });
  return { query, params };
}

const userId = 42;
const role = 'admin';

const { query, params } = sql`
  SELECT * FROM users
  WHERE id = ${userId} AND role = ${role}
`;

console.log(query);
console.log(params);
```

The sql tag creates parameterized queries - values are passed as parameters, not concatenated, preventing SQL injection.

## Key points

- strings.raw gives the raw string without processing escape sequences
- styled-components and Emotion use tagged templates for CSS-in-JS
- Apollo GraphQL uses gql\`\` to parse GraphQL query strings
- strings.length === values.length + 1 always

## Common follow-up questions

- How does String.raw use tagged templates?
- How do styled-components use tagged templates with props?
- What is the relationship between strings.length and values.length?

## Interview tips

- The security use case (XSS, SQL injection) is the most compelling real-world example
- Show the tag function signature: (strings, ...values) - interviewers check if you know the API
- Mention styled-components and gql - shows awareness of ecosystem usage

## Concepts covered

Tagged Templates, XSS Prevention, SQL injection, styled-components

Previous: [JavaScript Performance Optimization](https://www.internhack.in/learn/interview/javascript-interview/js-performance-optimization) · Next: [Intersection Observer and Mutation Observer](https://www.internhack.in/learn/interview/javascript-interview/js-intersection-observer) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Async Iterators and for await...of](https://www.internhack.in/learn/interview/javascript-interview/js-async-iterators)
- [Advanced Object Patterns and Mixins](https://www.internhack.in/learn/interview/javascript-interview/js-object-patterns)
- [ES Modules vs CommonJS](https://www.internhack.in/learn/interview/javascript-interview/js-modules-advanced)
- [Promise Combinators](https://www.internhack.in/learn/interview/javascript-interview/js-promise-combinators)
- [Variables: var, let, const](https://www.internhack.in/learn/interview/javascript-interview/js-var-let-const)
- [Data Types & Type Checking](https://www.internhack.in/learn/interview/javascript-interview/js-data-types)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
