Sub topic 4
Rebuilding the Output by Interleaving Parts
This chapter assumes you know rest parameters, Array.prototype.reduce, and the shape of a tag call from the previous chapter: strings holds the static parts, values holds the evaluated substitutions, and strings.length is always values.length + 1.
A tag function receives the literal split into pieces. If you want a string back, you have to join those pieces yourself. The order always alternates: a string part, then a value, then a string part, and so on. The output starts and ends with a string part.
The Loop Version
The most direct approach starts with the first string part. Each value is then followed by the string part after it.
function identity(strings, ...values) {
let out = strings[0];
for (let i = 0; i < values.length; i++) {
out += String(values[i]) + strings[i + 1];
}
return out;
}
const item = 'tea';
const qty = 2;
console.log(identity`Order: ${qty} x ${item}.`); // 'Order: 2 x tea.'This tag gives the same result as the untagged literal, which makes it a useful starting point for writing your own tags.
The reduce Version
reduce called without an initial value uses strings[0] as the accumulator and starts at index 1. At step i, the value that belongs before strings[i] is values[i - 1].
function identity(strings, ...values) {
return strings.reduce((out, str, i) => out + String(values[i - 1]) + str);
}
console.log(identity`a${1}b${2}c`); // 'a1b2c'
console.log(identity`no substitutions`); // 'no substitutions'A template with no substitutions still works. For a one-element array, reduce returns strings[0] without calling the callback.
Transforming Values on the Way Through
The reason to rebuild the output yourself is that you control each value before it goes in. The string parts come from your source code. The values come from runtime data.
function money(strings, ...values) {
return strings.reduce((out, str, i) => {
const v = values[i - 1];
const shown = typeof v === 'number' ? v.toFixed(2) : String(v);
return out + shown + str;
});
}
const subtotal = 19.5;
const tax = 1.95;
console.log(money`Subtotal ${subtotal}, tax ${tax}`); // 'Subtotal 19.50, tax 1.95'Later chapters use this same pattern to escape HTML and to build SQL queries.
Common Errors
Passing an initial value to reduce
function broken(strings, ...values) {
return strings.reduce((out, str, i) => out + String(values[i - 1]) + str, '');
}
console.log(broken`a${1}b`); // 'undefineda1b'With '' as the initial value, the first step runs at i = 0, so values[-1] is undefined. If you need an initial value, use strings.reduce(fn, '') with values[i] placed after str, and handle the final index separately. Dropping the initial value is simpler.
Converting with + instead of String()
An untagged ${obj} converts with string preference and calls toString first. The + operator uses the default hint, which calls valueOf first on ordinary objects.
const price = { valueOf() { return 10; }, toString() { return 'ten'; } };
console.log(`${price}`); // 'ten'
console.log('' + price); // '10'
console.log(String(price)); // 'ten'Wrap values in String() if your tag should match untagged behavior.
Exercise
Write a tag brackets so that bracketsx=${1}, y=${'two'} returns 'x=[1], y=[two]'. Then explain what bracketsplain returns and why no special case is needed.
Show answer
function brackets(strings, ...values) { return strings.reduce((out, str, i) => out + '[' + String(values[i - 1]) + ']' + str); } For bracketsplain, strings is ['plain'] and values is empty. reduce on a one-element array with no initial value returns that element without running the callback, so the result is 'plain'.
Exercise
A teammate's tag returns 'undefinedHello Ada' for tagHello ${'Ada'}. What is the most likely bug?
Show answer
They passed an initial value (such as '') to reduce while still reading values[i - 1]. The first callback runs at i = 0, which inserts String(undefined) before strings[0]. Removing the initial value fixes it.