Sub topic 10
Frozen Strings Arrays and Call-Site Caching
This chapter assumes you know how a tag function receives strings and ...values, how strings.raw relates to the cooked strings, and how WeakMap works. It covers a property of the strings array that earlier chapters only mentioned in passing. JavaScript creates the array once for each place in the source code where a tagged template appears, and it freezes the array. Together, these two facts make the strings array a reliable cache key. Several libraries rely on that to skip repeated work.
One Template Object per Call Site
A call site is one specific tagged template expression at one specific position in your source code. When the engine first evaluates that expression, it builds the strings array (the spec calls it the template object) and remembers it. Every later evaluation of the same expression receives the exact same array object. Only the values change.
const id = (strings) => strings;
function site() {
return id`x${Math.random()}y`;
}
// Same call site evaluated twice: same array, even though the value differs
console.log(site() === site()); // true
// Two call sites with identical text: two different arrays
console.log(id`x${1}y` === id`x${1}y`); // false
// eval parses fresh source each time, so each run is a new call site
console.log(eval('id`a`') === eval('id`a`')); // falseThe identity depends on the location in the source, not on the text. Two templates that look exactly the same but sit on different lines get separate arrays. One template inside a loop or a function that runs a thousand times gets one array.
| Scenario | Same strings array? |
|---|---|
| Same template evaluated repeatedly (loop, repeated function call) | Yes |
| Two templates with identical text at different positions | No |
| Same text run through `eval` or `new Function` twice | No |
| Same module code loaded in two realms (for example an iframe and its parent) | No |
| You call the tag directly as `tag(['a', 'b'], 1)` | No, you supply a new plain array each time |
Why the Array Is Frozen
Since every run of a call site shares one array, a change made during one run would leak into every later run. To prevent that, the engine freezes both the strings array and its raw array. The raw property itself is also non-writable, non-enumerable, and non-configurable.
'use strict';
function tag(strings) {
try {
strings[0] = 'changed';
} catch (e) {
console.log(e.constructor.name); // TypeError
}
try {
strings.push('extra');
} catch (e) {
console.log(e.constructor.name); // TypeError
}
console.log(Object.isFrozen(strings)); // true
console.log(Object.isFrozen(strings.raw)); // true
console.log(Object.keys(strings)); // [ '0', '1' ] (raw is not enumerable)
console.log(Object.getOwnPropertyDescriptor(strings, 'raw'));
// { value: [ 'a', 'b' ], writable: false, enumerable: false, configurable: false }
}
tag`a${1}b`;In sloppy-mode scripts, assigning to strings[0] fails silently and the old value stays. push throws in both modes because it tries to define a new index on a non-extensible array. ES modules and class bodies are always strict, so most modern code gets the TypeError.
Only the strings are frozen. The values are ordinary arguments, and an object passed as a value can be mutated like any other.
Using the Array as a Cache Key
Because the array is stable and immutable, a tag can do its expensive work once per call site. Parsing, validating, or restructuring the static parts only has to happen the first time. The result is stored in a WeakMap keyed by the strings array. Later calls look it up and only process the new values.
The example below is a dedent tag that strips the indentation after each newline in the static text. The stripping runs once per call site.
const cache = new WeakMap();
let compiles = 0;
function compile(strings) {
compiles++;
// Stand-in for expensive work: remove indentation after every newline.
return strings.map((s) => s.replace(/\n[ \t]+/g, '\n'));
}
function dedent(strings, ...values) {
let parts = cache.get(strings);
if (parts === undefined) {
parts = compile(strings);
cache.set(strings, parts);
}
return parts.reduce((out, str, i) => out + String(values[i - 1]) + str);
}
function greet(name) {
return dedent`
Hello, ${name}!
Welcome back.`;
}
greet('Ada');
greet('Grace');
greet('Linus');
console.log(compiles); // 1
console.log(greet('Ada')); // '\nHello, Ada!\nWelcome back.'The three calls to greet run the same call site, so compile runs only once. The cached parts array belongs to the tag, so the tag can build it however it likes. Only the engine-provided strings needs to stay untouched.
Why WeakMap and Not Map
A Map would keep every strings array, and the compiled results attached to it, alive forever. That matters when code is created dynamically. Each eval, each new Function, and each hot-module reload in a dev server produces new call sites with new arrays. With a WeakMap, an entry can be garbage-collected once its call site is no longer reachable. A WeakMap also never needs a key computed from the text, and computing one would bring back the content-based sharing the spec removed.
Cache Misses You Should Expect
The cache only works when the tag receives a real template object. Anything that builds a new array each time misses the cache.
// Continues the dedent example above
compiles = 0;
dedent(['a ', ' b'], 1);
dedent(['a ', ' b'], 2);
console.log(compiles); // 2: each call passed a new array literalWrapping one tag in another keeps the cache working only if the wrapper forwards the original array:
// Forwards the template object unchanged: the inner cache still hits
const logged = (strings, ...values) => {
console.log('rendering', values.length, 'values');
return dedent(strings, ...values);
};
// Builds a new array on every call: the inner cache always misses
const shouted = (strings, ...values) =>
dedent(strings.map((s) => s.toUpperCase()), ...values);If a wrapper has to change the strings, it should keep its own WeakMap from the original array to the changed array. Each call site then always maps to the same changed array, and the inner tag still sees a stable key.
How Libraries Use This
The lit library is the best-known example. Its html tag does very little work when called. It returns a TemplateResult object that holds the strings array and the values. When lit renders that result, it looks up the strings array in a cache. On a cache miss, it joins the static parts with marker placeholders, parses them into a <template> element once, and records where each value goes. On a cache hit, it reuses the prepared template. On re-renders, it updates only the slots whose values changed. For this reason a lit component's markup is parsed once per call site, however many times the component renders.
lit's static-html module lets you put static values such as tag names into the static parts. That means it has to build new strings arrays. To keep lit's main cache working, the module stores each array it builds and returns the same one whenever the same combination comes up again. This is the wrapper rule from the previous section, applied inside a real library.
Other template-tag libraries, such as CSS-in-JS and query-builder tags, often use the same approach. They parse or validate the static text once per call site, and do only per-value work after that.
Edge Cases Worth Knowing
- Values never affect identity.
id\${a}\`andid\${b}\at the same site share the same array whateveraandb` are. - Zero substitutions still produce a template object. A tag on `
tagplain` receives a frozen one-element array, and that array is also stable per site. - Realm boundaries. The same module evaluated in an iframe and in its parent page yields different arrays. A cache shared across realms won't get hits between them.
- Transpiled code. Older Babel and TypeScript output emulates the behavior with a module-level variable, created by a helper and assigned on the first call, which caches the frozen array per site. Code compiled in "loose" mode may skip freezing, so don't depend on
Object.isFrozenin tests that run against loosely compiled output.
Exercise
A function render(items) runs items.map((x) => tag\<li>${x}</li>\). render is called twice with three items each time. How many distinct strings arrays does tag receive, and how many times would a WeakMap-based cache inside tag compile?
Show answer
One distinct array and one compile. All six evaluations come from the same call site in the source, so they share a single frozen template object. The first evaluation misses the cache and compiles. The other five hit the cache.
Exercise
A teammate writes const trimmed = (s, ...v) => inner(s.map((p) => p.trim()), ...v); and notices that inner's cache never hits. Explain why, and fix it without changing inner.
Show answer
s.map creates a new array on every call, so inner gets a new key each time. (The new array also has no raw property.) The fix is to cache the transformed array per original template object: const memo = new WeakMap(); const trimmed = (s, ...v) => { let t = memo.get(s); if (!t) { t = Object.freeze(s.map((p) => p.trim())); memo.set(s, t); } return inner(t, ...v); };. Each call site now maps to one stable array, so inner's cache hits from the second call onward.
Exercise
In an ES module, a tag runs strings[0] = strings[0].toUpperCase(). What happens, and what would happen in a sloppy-mode script?
Show answer
Modules are strict, so the assignment throws a TypeError because the array is frozen. In a sloppy-mode script, the assignment fails silently and strings[0] keeps its original value. In both cases the template object stays unchanged for later calls.