← Back to JavaScript Course | Chapter 5: ES6+ Features | Lesson 10 of 12

JS Tagged Templates

What Is a Tagged Template

A tagged template is a template literal preceded by a function name; instead of producing a string directly, JavaScript calls that function with the literal's pieces for custom processing.

Example: What Is a Tagged Template

javascript
function tag(strings, value) {
  console.log(strings, value);
}
const name = "Sam";
tag`Hello ${name}`;

Tag Function Arguments

The tag function receives an array of the literal's string segments as its first argument, followed by each interpolated ${} value as separate additional arguments, giving it full access to both the fixed text and the dynamic pieces.

Example: Tag Function Arguments

javascript
function tag(strings, ...values) {
  console.log(strings);
  console.log(values);
}
tag`A ${1} B ${2}`;

Formatting with Tags

Because you control how the pieces are combined, a tag function can escape HTML, format currency, highlight substitutions, or apply any custom transformation before producing the final string.

Example: Formatting with Tags

javascript
function highlight(strings, ...values) {
  return strings.reduce((out, str, i) => `${out}${str}${values[i] ? `[${values[i]}]` : ""}`, "");
}
console.log(highlight`Score: ${95}`);

Reusable Tag Functions

A tag function is just a normal function, so you can write one once and reuse it across many template literals wherever that particular formatting or escaping behavior is needed.

Example: Reusable Tag Functions

javascript
function upper(strings, ...values) {
  return strings.reduce((out, str, i) => out + str + (values[i] ?? "").toString().toUpperCase(), "");
}
console.log(upper`Hello ${"world"}`);
console.log(upper`Bye ${"friend"}`);

Tagged Template Use Cases

Tagged templates power real libraries you may already use, like styled-components' CSS-in-JS syntax and SQL-templating libraries that safely escape interpolated values.

Example: Tagged Template Use Cases

javascript
// Real-world tagged templates (illustrative):
// styled.div`color: ${theme.color};`
// sql`SELECT * FROM users WHERE id = ${userId}`
console.log("Tagged templates power CSS-in-JS and safe SQL templating.");

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.