Course contentsShow
← JavaScript
Lesson 152 of 2,7235. StringsFree lesson

Tagged Template Literals

Use functions to process template literals and customize string interpolation.

Tagged Template Literals

What you'll learn: How to use functions to process template literals and customize how strings are built from expressions.

What Are Tagged Template Literals?

A tagged template literal lets you pass a template literal through a function that can inspect and transform it before producing the final string. Instead of JavaScript automatically creating the string, you control the process.

The syntax looks like this: you write a function name directly before the template literal (no parentheses):

myFunction`Hello ${name}!`;

How the Tag Function Works

When you "tag" a template literal, JavaScript calls your function with special arguments:

  1. First argument: An array of the literal string parts (the non-interpolated text)
  2. Remaining arguments: The values of each ${} expression, in order
function greet(strings, nameValue) {
  console.log(strings); // ["Hello ", "!"]
  console.log(nameValue); // "Alice"
  return strings[0] + nameValue.toUpperCase() + strings[1];
}

const name = "Alice";
const result = greet`Hello ${name}!`;
console.log(result); // "Hello ALICE!"

Why Use Tagged Templates?

Tagged templates let you customize interpolation. You might want to:

  • Sanitize user input for security
  • Format numbers or dates consistently
  • Build SQL queries safely
  • Create styled text

Key Takeaway: Tagged template literals run template literals through a function, giving you full control over how strings and expressions are combined—turning simple interpolation into a powerful, customizable tool.