Sub topic 10
Template Object Caching per Call Site
This chapter assumes you have read the earlier chapters on tagged templates and raw strings. You should already know that a tag function receives a strings array of literal parts, a strings.raw array, and the evaluated substitutions as further arguments. You should also be comfortable with Map, WeakMap, and Object.isFrozen.
Here we look at one specific property of the strings argument: its identity. JavaScript does not build a new strings array every time a tagged template runs. It builds one array per location in the source code, freezes it, and passes that same object on every evaluation. Libraries depend on this behavior, and it has some edge cases that can surprise you.
What a Call Site Is
A call site is one specific tagged template expression written in your source code: a tag, a backtick, some text, and a closing backtick at a particular position in a particular file. The engine identifies the site by its place in the parsed program, not by the text it contains.
Each time execution reaches that expression, the engine does three things:
- It looks up the template object for that site, creating it on the first evaluation only.
- It evaluates every
${}expression fresh, in order. - It calls the tag with the template object first and the fresh values after it.
The template object is the strings array together with its raw property. It is fixed for the site. The values change on every call.
Same Site, Same Object
The simplest way to see the cache is a tag that returns its strings argument unchanged.
function id(strings) {
return strings;
}
const fromLoop = [];
for (let i = 0; i < 3; i++) {
fromLoop.push(id`hello ${i}`);
}
console.log(fromLoop[0] === fromLoop[1]); // true
console.log(fromLoop[1] === fromLoop[2]); // true
const siteA = id`hello ${1}`;
const siteB = id`hello ${1}`;
console.log(siteA === siteB); // false
console.log(fromLoop[0] === siteA); // false
console.log(siteA[0] === siteB[0]); // true (equal strings, different arrays)The loop body holds one call site, so all three iterations receive the identical array. siteA and siteB contain the same characters, but they are written in two different places, so each gets its own template object. Their elements are equal strings because strings compare by value. The arrays that hold them are separate objects.
The rule also holds for function boundaries. A call site inside a function body belongs to the source code, not to a particular function object. Every call to the function, and every closure created from the same code, shares the template object.
function id(strings) {
return strings;
}
function makeGreeter() {
return (name) => id`Hi ${name}!`;
}
const greetA = makeGreeter();
const greetB = makeGreeter();
console.log(greetA === greetB); // false: two closures
console.log(greetA("Ada") === greetB("Bob")); // true: one call site
console.log(greetA("Ada") === greetA("Eve")); // truegreetA and greetB are different function objects, but they were created from the same arrow function in the source. They share one call site, so they share one template object.
The Template Object Is Frozen
Because many evaluations share one object, the language prevents anyone from changing it. Both the cooked array and the raw array are frozen. The raw property itself is non-writable, non-configurable, and non-enumerable.
"use strict";
function id(strings) {
return strings;
}
const s = id`a${1}b`;
console.log(Object.isFrozen(s)); // true
console.log(Object.isFrozen(s.raw)); // true
console.log(Object.keys(s)); // [ '0', '1' ]
console.log(Object.getOwnPropertyDescriptor(s, "raw").enumerable); // false
try {
s[0] = "changed";
} catch (err) {
console.log(err.constructor.name); // TypeError
}
try {
s.push("extra");
} catch (err) {
console.log(err.constructor.name); // TypeError
}
console.log(s[0]); // aIn strict mode, which includes all ES modules and class bodies, writing to a frozen array throws a TypeError. In sloppy-mode scripts the write fails silently and the value stays the same. Either way the shared object cannot change.
Freezing makes the cache safe. If the array were mutable, one call could modify it and every later call at that site would see the change. The freeze guarantees that the strings argument for a site always has the same contents.
Using the Strings Array as a Cache Key
A stable, frozen identity per site makes the strings array a good cache key. A tag can do its expensive work once per site, store the result in a WeakMap keyed by strings, and reuse it on later calls. Only the cheap part, combining the cached structure with new values, runs every time.
HTML templating libraries such as lit-html use this approach. They parse the markup of a template once per site and afterwards only update the parts that hold values. The example below uses the same idea on a smaller scale. A sql tag turns a template into a parameterized query with ? placeholders and builds the query text only once per site.
const queryCache = new WeakMap();
let builds = 0;
function sql(strings, ...values) {
let text = queryCache.get(strings);
if (text === undefined) {
builds++;
text = strings.reduce((out, str) => out + "?" + str);
queryCache.set(strings, text);
}
return { text, values };
}
function findUser(id) {
return sql`SELECT * FROM users WHERE id = ${id}`;
}
function findOrders(userId, status) {
return sql`SELECT * FROM orders WHERE user_id = ${userId} AND status = ${status}`;
}
console.log(findUser(1));
// { text: 'SELECT * FROM users WHERE id = ?', values: [ 1 ] }
findUser(2);
findUser(3);
console.log(findOrders(7, "open"));
// {
// text: 'SELECT * FROM orders WHERE user_id = ? AND status = ?',
// values: [ 7, 'open' ]
// }
findOrders(8, "closed");
console.log(builds); // 2The program makes five calls but builds is only 2, one for each call site. The values never enter the cache. They are returned separately on every call, which is also why this pattern stays safe from injection: user data never becomes part of the query text.
Why WeakMap and Not Map
A Map would work for a fixed set of sites, but it holds its keys strongly. Some code creates new call sites while it runs: code loaded through eval, new Function, or modules loaded and discarded during development with hot reloading. Each new site brings a new template object. A Map would keep all of them, and everything cached for them, alive forever. A WeakMap lets the engine collect an entry once nothing else references its template object.
| Cache choice | Key held | Behavior with many dynamically created sites |
|---|---|---|
| `Map` keyed by `strings` | Strongly | Grows without bound |
| `WeakMap` keyed by `strings` | Weakly | Entries can be collected with their sites |
| `Map` keyed by `strings.join(...)` | By text | Merges different sites with the same text and can confuse different templates |
The last row is a trap of its own. Keying on joined text erases the boundaries between parts. The templates ` sqla${x}b and sqla${x}${y}b , with the parts joined by an empty string, both produce the key "ab"`. Use the object as the key.
Gotchas
Calling a Tag Directly Bypasses the Cache
A tag is an ordinary function. Nothing prevents you from calling it with a hand-built array, and some code does so to reuse a tag's logic. That array is a fresh, mutable object with no raw property unless you add one.
function id(strings) {
return strings;
}
const real = id`x${1}y`;
const fake = ["x", "y"];
console.log(Object.isFrozen(real)); // true
console.log(Object.isFrozen(fake)); // false
console.log(real.raw); // [ 'x', 'y' ]
console.log(fake.raw); // undefined
// String.raw only needs an object with a raw property:
console.log(String.raw({ raw: ["x", "y"] }, 1)); // x1yDirect calls cause two problems for a caching tag:
- Every call passes a new array, so the cache misses every time. With a
WeakMapthis only wastes work. With aMapit leaks memory. - The array is mutable. If the caller changes it after the first call, the cached result no longer matches the array's contents.
A careful tag can check whether its input looks like a real template object before caching:
const cache = new WeakMap();
function isTemplateObject(strings) {
return Array.isArray(strings) &&
Object.isFrozen(strings) &&
Array.isArray(strings.raw) &&
Object.isFrozen(strings.raw);
}
function upperTag(strings, ...values) {
let parts = isTemplateObject(strings) ? cache.get(strings) : undefined;
if (parts === undefined) {
parts = strings.map((s) => s.toUpperCase());
if (isTemplateObject(strings)) cache.set(strings, parts);
}
return parts.reduce((out, str, i) => out + values[i - 1] + str);
}
console.log(upperTag`hello ${"world"} bye`); // HELLO world BYE
console.log(upperTag(["a ", " b"], 42)); // A 42 BThis check is a heuristic. A caller could freeze a hand-made array that has a frozen raw array attached. A TC39 proposal for Array.isTemplateObject aims to provide an exact test. Until engines support it, a frozen-shape check is the practical option.
Same Text Does Not Mean Same Object
Tests sometimes compare template objects from two places and expect them to be equal because the text matches. They will not be equal. If you need text-based equality, compare strings.raw element by element and accept that different sites will then be treated as one.
Dynamically Evaluated Code
Under the specification, code passed to eval or new Function is parsed each time, and each parse produces new call sites. Engines also keep internal compilation caches for repeated source strings, so whether two evaluations of identical code yield the same template object is not something portable code should depend on. In both cases, assume nothing about the identity of template objects across separately evaluated code.
Do Not Store Per-Call State on the Template Object
Because the object is frozen, you cannot attach properties to it, and code that tries to fails, sometimes silently. Keep any per-site data in a side table such as a WeakMap. Keep per-call data in local variables.
A Short History
The caching rule has changed once, and older articles may describe the earlier behavior.
| Edition | Cache key | Effect |
|---|---|---|
| ES2015 to ES2018 | The raw strings, shared across the whole realm | Two sites with identical raw text received the same object |
| ES2019 onward | The call site itself | Each site has its own object, even if the text is identical |
The original design caused problems. Its realm-wide cache could never release an entry because any future code might produce the same text. It also merged unrelated templates that happened to look alike, which confused libraries that cached per template. The change to per-site identity solved both issues. All current engines implement the per-site rule.
Summary of the Rules
- Each tagged template call site has exactly one template object, created on its first evaluation.
- Every later evaluation of that site, including from other calls, loop iterations, and closures, receives the same object.
- The
stringsarray and itsrawarray are both frozen, andrawis non-enumerable. - Substitution values are evaluated fresh on every evaluation and are never cached.
- A
WeakMapkeyed bystringsis the standard way to cache per-site work. - Direct calls with hand-made arrays get no caching and no freezing, so a caching tag should be prepared for them.
Exercise
The code below defines function id(s) { return s; }, then runs const a = []; for (const n of [1, 2]) { a.push(idv${n}); } const b = idv${1};. What do a[0] === a[1], a[0] === b, and a[0][0] === b[0] print, and why?
Show answer
a[0] === a[1] is true because both come from the single call site inside the loop body. a[0] === b is false because b comes from a different call site, even though the text is identical. a[0][0] === b[0] is true because both elements are the string "v", and strings compare by value.
Exercise
A colleague writes a caching tag with const cache = new Map() and keys it on strings.join("|"). Name two problems with this design and describe a better one.
Show answer
First, a Map holds keys strongly, so a program that keeps creating call sites (eval, new Function, hot reloading) makes the cache grow forever. Second, joining by text merges different call sites with matching text, and a separator can collide with literal content: the single part "a|b" and the two parts "a" and "b" both produce "a|b". Use a WeakMap keyed by the strings object itself, which gives exact per-site identity and lets entries be garbage-collected.
Exercise
Inside an ES module, a tag does strings.cachedResult = compute(strings); return strings.cachedResult;. What happens on the first call, and how should the tag be rewritten?
Show answer
Modules run in strict mode, and the template object is frozen, so assigning a new property throws a TypeError on the first call. Store the result in a side table instead: const cache = new WeakMap(); and then let r = cache.get(strings); if (r === undefined) { r = compute(strings); cache.set(strings, r); } return r;.