Sub topic 4
Rebuilding the Output by Interleaving Parts
A tag function receives the static string parts and the substitution values as separate pieces. To produce a string, it has to put them back together. This chapter covers how to do that correctly, how to change values or strings along the way, and the edge cases that break simple implementations.
This chapter assumes you know rest parameters, Array.prototype.reduce, and the previous chapter's rule: a tag gets strings and ...values, and strings.length === values.length + 1.
The Interleaving Rule
Every template literal alternates between static text and substitutions. The static text always comes first and last, even when it is an empty string. So the original string is always:
strings[0] + values[0] + strings[1] + values[1] + ... + strings[n]
where n is values.length.
Because there is always exactly one more string than there are values, the reassembly loop has a fixed shape. You start with strings[0], then repeatedly append one value followed by the string after it.
A Plain Loop Implementation
The clearest version is an explicit loop. It is easy to read, and it is easy to add logic to later.
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 = 'apples';
const count = 3;
console.log(identity`I have ${count} ${item}.`); // 'I have 3 apples.'The loop runs once per value. Each pass appends a value and then the string that follows it, so the last string, strings[values.length], is appended on the final pass. A tag with no substitutions skips the loop entirely and returns strings[0].
The reduce Idiom
Most tag functions you see in libraries and blog posts use reduce instead:
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'The trick is leaving out the initial value. When reduce gets no initial value, it uses strings[0] as the starting accumulator and begins calling the callback at index 1. At index i, the value that comes before strings[i] is values[i - 1]. That is why the callback reads values[i - 1] and not values[i].
When strings has only one element, which happens with a template that has no substitutions, reduce with no initial value returns that element without calling the callback. strings is never empty, so the TypeError that reduce throws on an empty array cannot happen here.
The Initial-Value Bug
Adding an initial value of '' looks harmless, but it shifts every index:
function broken(strings, ...values) {
return strings.reduce((out, str, i) => out + values[i - 1] + str, '');
}
console.log(broken`a${1}b`); // 'undefineda1b'With an initial value, the callback starts at index 0, reads values[-1] (which is undefined), and puts the text "undefined" at the front. If you want an explicit initial value, start from strings[0] and reduce over values:
function identity(strings, ...values) {
return values.reduce((out, value, i) => out + String(value) + strings[i + 1], strings[0]);
}
console.log(identity`a${1}b${2}c`); // 'a1b2c'This version indexes into strings with i + 1, which matches the plain loop exactly.
Coercion: Why String(value) Matters
An untagged template converts each substitution with the spec's ToString operation. The + operator converts differently. It asks objects for a primitive with the hint "default" instead of "string". For most values the result is the same. For objects that define Symbol.toPrimitive, it is not:
const temp = {
[Symbol.toPrimitive](hint) {
return hint === 'string' ? '21°C' : 21;
},
};
console.log(`${temp}`); // '21°C'
console.log('' + temp); // '21'
console.log(String(temp)); // '21°C'If you write out + values[i - 1] + str, your tag can produce different output than the same template without a tag. Wrapping the value in String(value) gives the same result an untagged template would.
String also handles symbols, which untagged templates do not:
| Value | Untagged `${value}` | `'' + value` | `String(value)` |
|---|---|---|---|
| `42` | `'42'` | `'42'` | `'42'` |
| `null` | `'null'` | `'null'` | `'null'` |
| `[1, 2]` | `'1,2'` | `'1,2'` | `'1,2'` |
| `{}` | `'[object Object]'` | `'[object Object]'` | `'[object Object]'` |
| `Symbol('x')` | throws `TypeError` | throws `TypeError` | `'Symbol(x)'` |
| object with `Symbol.toPrimitive` | uses hint `"string"` | uses hint `"default"` | uses hint `"string"` |
Transforming Values While You Rebuild
The point of writing a tag is usually to change something during reassembly. The interleaving loop stays the same, and the value-handling function changes. The example below formats numbers as currency and leaves everything else alone:
const money = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
function price(strings, ...values) {
return strings.reduce((out, str, i) => {
const value = values[i - 1];
const text = typeof value === 'number' ? money.format(value) : String(value);
return out + text + str;
});
}
const product = 'Keyboard';
const cost = 49.5;
console.log(price`${product} costs ${cost} today.`); // 'Keyboard costs $49.50 today.'A common need is a renderer that drops "empty" values and flattens arrays. Untagged templates print null and undefined literally, which is rarely what you want in generated text:
function render(value) {
if (value == null || value === false) return '';
if (Array.isArray(value)) return value.map(render).join('');
return String(value);
}
function text(strings, ...values) {
return strings.reduce((out, str, i) => out + render(values[i - 1]) + str);
}
const items = ['a', 'b', 'c'];
const note = null;
console.log(text`List: ${items.map((x) => `[${x}]`)}${note}`); // 'List: [a][b][c]'The way this tag handles arrays explains how many HTML template libraries let you place a mapped list directly into a template.
Transforming the String Parts
You can also change the static parts. They are written by the developer, so a tag can treat them differently from the values. The example below collapses runs of whitespace in the static text only, which lets you write a long message across several lines:
function oneLine(strings, ...values) {
const clean = strings.map((s) => s.replace(/\s+/g, ' '));
const joined = clean.reduce((out, str, i) => out + String(values[i - 1]) + str);
return joined.trim();
}
const file = 'report final.txt';
console.log(oneLine`
Could not open ${file}.
Check that it exists.
`); // 'Could not open report final.txt. Check that it exists.'The spaces inside file survive because the tag only rewrote the strings. Keeping that boundary between developer-written text and runtime data is the basis of the escaping patterns covered later in this tutorial.
strings is frozen, so you cannot edit it in place. strings.map returns a new, ordinary array, which is why the example builds clean.
A Shortcut with String.raw
String.raw already does the interleaving. It reads its first argument's raw property and alternates those parts with the remaining arguments. Passing the cooked strings array as the raw property lets you reuse that logic:
function shout(strings, ...values) {
return String.raw({ raw: strings }, ...values.map((v) => String(v).toUpperCase()));
}
const who = 'world';
console.log(shout`hello\t${who}!`); // 'hello' + tab + 'WORLD!'Passing strings and not strings.raw keeps processed escapes such as \t as real characters. If you pass the original strings object directly to String.raw, you get the raw text instead, with a backslash and a t. The next chapters explain that difference in detail. String.raw also converts values with ToString, so a symbol passed to it throws. In the example above, String(v) runs first, so symbols are converted before they reach it.
Edge Cases to Test
A tag function should handle every shape of template. These cases catch most bugs in the indexing:
| Template | `strings` | `values` |
|---|---|---|
| `` tag`plain` `` | `['plain']` | `[]` |
| `` tag`${a}` `` | `['', '']` | `[a]` |
| `` tag`${a}${b}` `` | `['', '', '']` | `[a, b]` |
| `` tag`x${a}` `` | `['x', '']` | `[a]` |
| `` tag`` `` | `['']` | `[]` |
Empty strings at the start, the end, or between adjacent substitutions are real elements. Never filter them out. Removing them breaks the one-to-one alignment between strings[i + 1] and values[i]. A quick check is to confirm that your tag, with a value function that does nothing, returns the same result as the untagged template for each row.
Exercise
What does broken return for the template a${1}b${2}c when it is defined as strings.reduce((out, str, i) => out + values[i] + str, '')?
Show answer
It returns 'a1b2cundefined'. With the initial value, the callback runs for i = 0, 1, 2 and appends values[0], values[1], and then values[2], which is undefined, before each string: '' + 1 + 'a'... More precisely, the steps are: '' + 1 + 'a' = '1a', then '1a' + 2 + 'b' = '1a2b', then '1a2b' + undefined + 'c' = '1a2bundefinedc'. So the result is '1a2bundefinedc'. Values land before their own preceding strings, and an extra 'undefined' appears.
Exercise
Write a tag bracket that wraps each substitution in square brackets, so that bracketx=${1}, y=${'two'} returns 'x=[1], y=[two]', and bracketnone returns 'none'.
Show answer
function bracket(strings, ...values) { return strings.reduce((out, str, i) => out + '[' + String(values[i - 1]) + ']' + str); } With no substitutions, reduce returns strings[0] without calling the callback, so 'none' comes back unchanged.
Exercise
Why does a tag written as strings.reduce((out, str, i) => out + values[i - 1] + str) give different output from the untagged template for an object with a Symbol.toPrimitive method, and how do you fix it?
Show answer
The + operator asks for a primitive with the hint "default", while template substitution uses ToString, which uses the hint "string". An object that returns different values per hint therefore renders differently. Wrapping the value in String(values[i - 1]) uses the "string" hint and matches the untagged template.