Sub topic 7
Tagged Templates and Tag Functions
This chapter assumes you know JavaScript functions, rest parameters (...values), and the array methods reduce, map, and join. It also assumes you have read the earlier chapters on ${} interpolation and string conversion. So far, a template literal has always produced a string. Tagged templates change that. You put a function in front of the template, and that function decides what the template produces.
What a Tagged Template Is
A tagged template is a template literal written directly after an expression, with no parentheses between them:
function shout(strings, ...values) {
return strings[0].toUpperCase() + values[0] + strings[1].toUpperCase();
}
const name = "Ada";
console.log(shout`hello ${name}, welcome`);
// HELLO Ada, WELCOMEThe expression in front, here shout, is the tag. The function it refers to is the tag function. The engine does not build a finished string. It splits the template into its literal text and its substitution values and calls the tag function with those pieces. Whatever the tag function returns becomes the value of the whole expression.
The Call Signature
A tag function always receives the same kind of arguments:
- A
stringsarray holding the literal text segments, in order. - One extra argument for each
${}substitution, holding the evaluated value.
Most tag functions collect the values with a rest parameter, as in (strings, ...values).
function inspect(strings, ...values) {
console.log(strings.length, values.length);
console.log(strings);
console.log(values);
}
inspect`Total: ${3 + 4} items for ${"Ada"}.`;
// 3 2
// [ 'Total: ', ' items for ', '.' ]
// [ 7, 'Ada' ]The values arrive as they are, with no conversion. The number 7 arrives as a number, not as the string "7". The string conversion rules from the previous chapter apply only when a template is untagged, or when your tag converts values itself.
The One-More-String Rule
The strings array always has exactly one more element than there are values. Every substitution sits between two string segments, even when a segment is empty:
function shape(strings, ...values) {
return JSON.stringify({ strings: [...strings], values });
}
console.log(shape`plain text`);
// {"strings":["plain text"],"values":[]}
console.log(shape`${1}${2}`);
// {"strings":["","",""],"values":[1,2]}
console.log(shape`a${1}`);
// {"strings":["a",""],"values":[1]}This rule lets you treat the template as an alternating sequence: strings[0], values[0], strings[1], values[1], and so on, ending with the last string. You never have to check whether the template starts or ends with a substitution.
What Else Is on the Strings Array
The strings array is a little unusual. It is frozen, and it carries a non-enumerable raw property with the uninterpreted source text of each segment. Because raw is non-enumerable, console.log does not show it. Later chapters cover raw, why the same array comes back on every call from one call site, and how invalid escapes behave. For now, treat strings as a read-only array of text segments.
Reassembling the Pieces
Most tag functions do some work on the values and then rebuild a string. The alternating structure makes a small helper useful:
function interleave(strings, values, format) {
let out = strings[0];
for (let i = 0; i < values.length; i++) {
out += format(values[i], i) + strings[i + 1];
}
return out;
}
function usd(strings, ...values) {
return interleave(strings, values, (v) =>
typeof v === "number" ? `$${v.toFixed(2)}` : String(v)
);
}
console.log(usd`Subtotal: ${12} Tax: ${0.96} Total: ${12 + 0.96}`);
// Subtotal: $12.00 Tax: $0.96 Total: $12.96Notice $${v.toFixed(2)}. The first $ is ordinary text because it is not followed by {. The second $ begins the substitution.
Many tags use reduce for the same job. Without an initial value, reduce starts with strings[0] as the accumulator and index 1. So the value that belongs before strings[i] is values[i - 1]:
function brackets(strings, ...values) {
return strings.reduce((out, str, i) => out + `[${values[i - 1]}]` + str);
}
console.log(brackets`a${1} b ${2}`); // a[1] b [2]
console.log(brackets`no values`); // no valuesWhen there are no values, strings has one element, so reduce returns it without calling the callback. The rest of this tutorial uses both styles. Choose whichever you find easier to read.
Tags Can Return Anything
A tag function is an ordinary function, so its return value does not have to be a string. This is how libraries build queries, styled components, or parsed objects from template syntax. Here is a tag that turns a template into a parameterized query object. The values stay separate from the query text:
function sql(strings, ...values) {
return {
text: strings.reduce((out, str, i) => out + "$" + i + str),
values,
};
}
const id = 42;
const status = "active";
const query = sql`SELECT * FROM users WHERE id = ${id} AND status = ${status}`;
console.log(query.text);
// SELECT * FROM users WHERE id = $1 AND status = $2
console.log(query.values);
// [ 42, 'active' ]A database driver can send text and values separately, so the values never become part of the SQL text. A later chapter applies the same idea, where a tag decides how values enter the output, to HTML escaping.
Evaluation Order
When the engine meets a tagged template, it works in this order:
- It evaluates the tag expression to get the function.
- It gets the strings array for this call site.
- It evaluates every substitution, left to right.
- It calls the tag function with the strings array and the values.
So every substitution has already run by the time your tag starts:
function log(msg) {
console.log("evaluating", msg);
return msg;
}
function tag(strings, ...values) {
console.log("tag called");
return values.join(" ");
}
console.log(tag`${log("a")} ${log("b")}`);
// evaluating a
// evaluating b
// tag called
// a bA tag cannot skip or delay a substitution. If you want lazy evaluation, pass functions and let the tag decide when to call them:
function lazy(strings, ...values) {
return (enabled) =>
strings.reduce((out, str, i) => {
const v = values[i - 1];
return out + (enabled && typeof v === "function" ? v() : "-") + str;
});
}
const report = lazy`cost: ${() => 2 ** 10}`;
console.log(report(false)); // cost: -
console.log(report(true)); // cost: 1024What Can Be a Tag
The tag can be any member expression or call expression that evaluates to a function. That allows three common forms.
Methods and `this`
When the tag is a property access, the function is called as a method. Inside it, this refers to the object:
const fmt = {
sep: " | ",
join(strings, ...values) {
return values.join(this.sep);
},
};
console.log(fmt.join`${1}${2}${3}`); // 1 | 2 | 3Tag Factories
A call that returns a function can also be a tag. This lets you configure a tag before you use it:
const wrap = (open, close) => (strings, ...values) =>
strings.reduce((out, str, i) => out + open + values[i - 1] + close + str);
console.log(wrap("<", ">")`a ${1} b ${2}`); // a <1> b <2>
console.log(wrap("**", "**")`Hello ${"Ada"}`); // Hello **Ada**wrap("<", ">") runs first and returns the tag function. The template then tags that result.
Forms That Do Not Work
Optional chaining cannot be combined with a tagged template. obj?.tag followed by a template is a SyntaxError, because the language does not allow a template to continue an optional chain. Check for the function first, then tag it.
Tagged and Untagged Templates Compared
| Aspect | Untagged template | Tagged template |
|---|---|---|
| Result | Always a string | Whatever the tag function returns |
| Value conversion | Each value converted with string conversion | Values passed unchanged; the tag decides |
| Literal text | Joined automatically | Passed as a frozen `strings` array |
| Escape sequences | Interpreted; invalid ones are a `SyntaxError` | Interpreted in `strings`, raw text in `strings.raw` |
| Typical use | Building display text | Formatting, escaping, DSLs, query builders |
Common Errors
Calling the Tag with Parentheses
tag(\...\) is an ordinary function call. The untagged template is evaluated first, so the function receives one finished string instead of the separate parts:
function count(strings, ...values) {
return `${values.length} values`;
}
const n = 5;
console.log(count`n is ${n}`); // 1 values
console.log(count(`n is ${n}`)); // 0 valuesInside the second call, strings is the string "n is 5", not an array.
Off-by-One When Rebuilding
Indexing errors are the most common bug in tag functions. With a for loop starting at strings[0], pair values[i] with strings[i + 1]. With reduce and no initial value, pair values[i - 1] with strings[i]. A mismatch either drops the last segment or inserts undefined.
Using `strings.join(values)`
join takes a single separator, so strings.join(values) converts the entire values array to one string and puts it between every pair of segments. It only looks correct when there is exactly one value.
Mutating the Strings Array
The strings array is frozen. Assigning to it fails silently in sloppy mode and throws a TypeError in strict mode, which includes all modules and classes. Copy it with [...strings] if you need a modifiable version.
Accidental Tags from Missing Semicolons
Automatic semicolon insertion does not end a statement before a backtick. A line that starts with a template literal therefore becomes a tag call on the previous line's expression:
const label = "start"
`next line`
// TypeError: "start" is not a functionThe engine parses this as "start" tagged with the template. If your style omits semicolons, put one at the start of any line that begins with a backtick.
Exercises
Exercise
What do strings and values contain for the call `t${a}-${b} when a = 1 and b = 2`? How many elements does each array have?
Show answer
strings is ["", "-", ""] with 3 elements, and values is [1, 2] with 2 elements. The template starts and ends with a substitution, so the first and last segments are empty strings, which keeps the one-more-string rule.
Exercise
Write a tag upperValues that leaves the literal text alone and converts each value to an uppercase string, so that `upperValueshi ${"ada"}, you are ${"admin"} returns "hi ADA, you are ADMIN"`.
Show answer
function upperValues(strings, ...values) { return strings.reduce((out, str, i) => out + String(values[i - 1]).toUpperCase() + str); } The reduce call starts with strings[0]. At each later index it appends the uppercased previous value and then the current segment.
Exercise
A colleague writes const msg = format(\Total: ${sum}\); and finds that their tag function format receives a string instead of an array. Why, and how do you fix it?
Show answer
The parentheses make it an ordinary call. The untagged template is evaluated to a finished string first, and that string becomes the only argument. Remove the parentheses and write `formatTotal: ${sum} so the engine calls format with the strings array and the value of sum`.
Exercise
In `tag${f()} ${g()} , g throws an error. Does the tag function run? Does f` run?
Show answer
f runs, because substitutions are evaluated left to right before the tag is called. The tag function never runs, because the exception from g propagates out of the expression before the call happens.