Sub topic 7
Tagged Templates and Tag Functions
This chapter assumes you know how ${} interpolation works, how functions and rest parameters (...args) behave, and how Array.prototype.reduce works. Earlier chapters covered how a plain template literal turns its parts into one string. A tagged template does not do that joining itself. It gives the parts to a function you write, and the function decides what the result is.
What a Tagged Template Is
A tagged template is a template literal written directly after an expression, with no parentheses in between. That expression is the tag. It must evaluate to a function, which is called the tag function.
function tag(strings, ...values) {
console.log(strings); // [ 'a', ' b ', '' ]
console.log(values); // [ 1, 2 ]
return strings.reduce(
(out, str, i) => out + str + (i < values.length ? `[${values[i]}]` : ""),
""
);
}
console.log(tag`a${1} b ${2}`); // a[1] b [2]The engine splits the template at each ${} and calls the tag with two kinds of arguments:
- The first argument,
strings, is an array of the literal text pieces between the substitutions. - The remaining arguments are the evaluated substitution values, in order. A rest parameter collects them into
values.
The Shape of the Arguments
The strings array always has exactly one more element than values. A template that starts or ends with a substitution still has an empty string at that edge. In the example above, the template ends with ${2}, so the last element of strings is ''.
| Template | `strings` | `values` |
|---|---|---|
| ``tag`hello` `` | `['hello']` | `[]` |
| ``tag`${x}` `` | `['', '']` | `[x]` |
| ``tag`a${x}b${y}` `` | `['a', 'b', '']` | `[x, y]` |
| ``tag`${x}${y}` `` | `['', '', '']` | `[x, y]` |
Because of this layout, the pieces always alternate as strings[0], values[0], strings[1], values[1], and so on, ending with the last string. A common way to join them is reduce without an initial value. The accumulator then starts as strings[0] and the index starts at 1, so values[i - 1] is the value that comes before strings[i]:
function currency(strings, ...values) {
return strings.reduce((out, str, i) => {
const value = values[i - 1];
const shown = typeof value === "number" ? value.toFixed(2) : value;
return out + shown + str;
});
}
const subtotal = 19.5;
const tax = 1.6;
console.log(currency`Subtotal: $${subtotal}, tax: $${tax}`);
// Subtotal: $19.50, tax: $1.60The $ right before each ${ is ordinary text. Only the ${ pair starts a substitution.
Evaluation Order
All substitutions are evaluated before the tag runs. The tag gets finished values, not the code that produced them.
function show(strings, ...values) {
console.log("tag called");
return values;
}
const result = show`${(console.log("first"), 1)} ${(console.log("second"), 2)}`;
// first
// second
// tag called
console.log(result); // [ 1, 2 ]Tags Can Return Anything
A tag function does not have to return a string. Returning a different structure is one of the main reasons to use tags. This tag builds a parameterized database query, keeping the values separate from the SQL text:
function query(strings, ...values) {
return { text: strings.join("?"), values };
}
const id = 7;
console.log(query`SELECT * FROM users WHERE id = ${id}`);
// { text: 'SELECT * FROM users WHERE id = ?', values: [ 7 ] }The tag can be any expression that evaluates to a function, such as a property access (`db.sql... ) or the result of a call (makeTag("en")... `).
Common Errors
Other common mistakes:
- Indexing off by one. If
reducehas no initial value, the value beforestrings[i]isvalues[i - 1]. If you pass""as the initial value, the value afterstrings[i]isvalues[i], and you must checki < values.length. - Dropping the last string. If you loop over
valuesand skip the final element ofstrings, any text after the last substitution disappears. - Assuming the values are strings. Values reach the tag unconverted. A number arrives as a number and an object as an object. Convert them yourself with
String(value)if you need text.
The strings array also carries a raw property and has a fixed identity for each call site. Later chapters cover both.
Exercise
Write a tag upper that keeps the literal text unchanged but converts every interpolated value to uppercase, so that upperHi ${"ada"}, meet ${"bob"}! returns "Hi ADA, meet BOB!". What do strings and values contain for this call?
Show answer
strings is ['Hi ', ', meet ', '!'] and values is ['ada', 'bob']. One solution: function upper(strings, ...values) { return strings.reduce((out, str, i) => out + String(values[i - 1]).toUpperCase() + str); } Because reduce has no initial value, it starts with strings[0] and index 1, so values[i - 1] is the value that comes just before each later string.
Exercise
What do the calls fx${1} and f(x${1}) pass to function f(strings, ...values)?
Show answer
The tagged form passes strings = ['x', ''] and values = [1]. The parenthesized form evaluates the template first and passes the single string 'x1' as strings, with values = [].