JS Tagged Templates
In this page:
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
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
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
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
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
// 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.");
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: