🟢 EasyModern JS📖 Theory Question

What are tagged template literals and what are they used for?

💡

Hint

A function that processes the template — receives string parts and interpolated values separately

Full Answer

A tagged template is a function placed before a template literal — it receives the string parts and interpolated values separately, allowing custom processing.

function highlight(strings, ...values) {
  // strings: ['User ', ' scored ', '%']
  // values:  ['Alice', 95]
  return strings.reduce((result, str, i) =>
    result + str + (values[i] !== undefined
      ? `${values[i]}`
      : ''), '');
}

const user = 'Alice', score = 95;
highlight`User ${user} scored ${score}%`;
// 'User Alice scored 95%'

// Real-world uses:
// 1. styled-components
const Button = styled.div`
  background: ${props => props.primary ? 'blue' : 'white'};
`;

// 2. SQL sanitization (prevents injection!)
const result = sql`SELECT * FROM users WHERE id = ${userId}`;
// tag function escapes userId before inserting

// 3. GraphQL queries
const query = gql`
  query GetUser { user(id: ${id}) { name } }
`;
💡 Tagged templates are how styled-components and sql template libraries work. The tag function is called before string interpolation, enabling sanitization and custom processing.

More Modern JS Questions

🟡 MediumWhat are generators and when would you use them?→🟢 EasyWhat is optional chaining (?.) and nullish coalescing (??)?→🟢 EasyExplain destructuring for objects and arrays — including defaults, renaming, rest, and nesting.→🟢 EasyWhat are Symbols and what are their main use cases?→

Practice this in a timed sprint →

5 free questions, no signup required

âš¡ Start Sprint