Sub topic 3
Inside the Call: The Strings Array and the Values
The previous chapter showed that a tagged template is a function call. This chapter looks at the arguments that call receives. You will learn how JavaScript splits a template into parts, which rules those parts always follow, when the values are evaluated, and what form they arrive in.
This chapter assumes you know JavaScript functions and rest parameters (...values), basic array methods, and ordinary template literals with ${} substitutions.
The Shape of the Arguments
When JavaScript runs ` tagHello ${name}, you are ${age} years old. , it cuts the literal at every substitution. The text between the substitutions becomes the static parts, and the expressions inside ${}` become the values. The tag receives the static parts as one array in its first parameter, and each value as a separate argument after it.
function inspect(strings, ...values) {
console.log(strings); // [ 'Hello ', ', you are ', ' years old.' ]
console.log(values); // [ 'Ada', 36 ]
return strings.length - values.length; // always 1
}
const name = 'Ada';
const age = 36;
console.log(inspect`Hello ${name}, you are ${age} years old.`); // 1The first parameter is usually called strings. The rest parameter collects every substitution value into a normal array, usually called values.
The One-More-String Rule
Every substitution has a static part on each side of it, even when that part is empty. So for any tagged template:
strings.length === values.length + 1, always.values[i]sits betweenstrings[i]andstrings[i + 1].
The rule holds because JavaScript inserts empty strings instead of leaving parts out. A small helper makes this visible:
function dissect(strings, ...values) {
return { strings: [...strings], values };
}
console.log(dissect`plain text`);
// { strings: [ 'plain text' ], values: [] }
console.log(dissect``);
// { strings: [ '' ], values: [] }
console.log(dissect`${1} starts here`);
// { strings: [ '', ' starts here' ], values: [ 1 ] }
console.log(dissect`ends here ${2}`);
// { strings: [ 'ends here ', '' ], values: [ 2 ] }
console.log(dissect`${1}${2}`);
// { strings: [ '', '', '' ], values: [ 1, 2 ] }The table summarizes the edge cases.
| Template | `strings` | `values` |
|---|---|---|
| `` tag`plain text` `` | `['plain text']` | `[]` |
| `` tag`` `` | `['']` | `[]` |
| `` tag`${a} x` `` | `['', ' x']` | `[a]` |
| `` tag`x ${a}` `` | `['x ', '']` | `[a]` |
| `` tag`${a}${b}` `` | `['', '', '']` | `[a, b]` |
| `` tag`a${x}b${y}c` `` | `['a', 'b', 'c']` | `[x, y]` |
Because of this rule, a tag never has to check whether a part exists. It can always walk the strings and treat each gap between them as a value slot. The next chapter builds on this when it rebuilds the output.
What Goes Into a String Part
The static parts contain exactly the characters written between the backtick and the ${, or between the } and the next ${ or closing backtick. That includes spaces and line breaks:
function parts(strings) {
return strings.map((s) => JSON.stringify(s));
}
console.log(parts`line one
${'x'}
line three`);
// [ '"line one\\n "', '"\\nline three"' ]Whitespace inside the braces does not count. ${ name } and ${name} produce the same strings array, because the braces and everything between them belong to the expression, not to the text.
The strings array is a real array, so Array.isArray(strings) is true and methods like map and reduce work on it. It differs from an ordinary array in two ways that later chapters cover in detail:
- It has an extra
rawproperty holding the uncooked source text of each part (see "Cooked and Raw Strings"). - It is frozen, and the same array is reused each time the same call site runs (see "Frozen Strings Arrays and Call-Site Caching").
For now, the practical consequence is that you should treat strings as read-only. If you need a modified version, copy it with [...strings] or strings.map(...).
'use strict';
function tryMutate(strings) {
try {
strings[0] = 'changed';
} catch (err) {
return err.constructor.name;
}
return 'no error';
}
console.log(tryMutate`original`); // 'TypeError'In sloppy mode the assignment fails silently and strings[0] keeps its original value. Calling strings.push(...) throws a TypeError in both modes.
The Values Arrive Unchanged
An untagged template converts every substitution to a string. A tagged template does not. Each value reaches the tag exactly as the expression produced it: numbers stay numbers, objects stay the same object references, and functions stay callable.
function types(strings, ...values) {
return values.map((v) => (v === null ? 'null' : typeof v));
}
const list = [1, 2];
console.log(types`${42} ${null} ${list} ${() => 1} ${undefined} ${Symbol('s')}`);
// [ 'number', 'null', 'object', 'function', 'undefined', 'symbol' ]
function same(strings, value) {
return value === list;
}
console.log(same`${list}`); // trueThis is what makes tags useful. A tag can inspect a value's type, call a function value, keep an array as an array, or decide how to serialize each value itself. Compare the same expressions without a tag:
const items = [1, 2];
console.log(`${items}`); // '1,2'
try {
console.log(`${Symbol('s')}`);
} catch (err) {
console.log(err instanceof TypeError); // true: symbols cannot be converted
}The untagged template turned the array into '1,2' and threw on the symbol. The tagged version received both untouched. If a tag builds a string, converting each value is the tag's job, typically with String(value). String(symbol) works where implicit conversion throws.
When the Values Are Evaluated
All substitution expressions are evaluated left to right before the tag function runs. The tag cannot delay, skip, or re-run them. It only ever sees the results.
const log = [];
function trace(label, value) {
log.push(label);
return value;
}
function tag(strings, ...values) {
log.push('tag called');
return values;
}
tag`a${trace('first', 1)}b${trace('second', 2)}c`;
console.log(log); // [ 'first', 'second', 'tag called' ]The tag expression is evaluated first, then the substitutions, then the call happens. This means a side effect inside ${} happens even if the tag throws right away. It also happens if the tag turns out not to be a function: the TypeError for calling a non-function comes after the arguments are evaluated.
A nested template inside a substitution is evaluated completely before the outer tag sees it. In ` outerx ${innery ${z}} , the inner tag runs first, and its return value, whatever type it is, becomes one value for outer`.
Naming Parameters Instead of Using Rest
The rest parameter is the common style, but a tag is an ordinary function, so you can declare fixed parameters when the template shape is known:
function range(strings, start, end) {
return `${strings[0]}${start}..${end}${strings[2]}`;
}
console.log(range`[${1} to ${5}]`); // '[1..5]'This works, but it fails quietly if a caller writes a different number of substitutions. Extra values are dropped, and missing ones become undefined. If you take fixed parameters, check strings.length to catch misuse:
function strictRange(strings, start, end) {
if (strings.length !== 3) {
throw new TypeError('strictRange expects exactly two substitutions');
}
return `${start}..${end}`;
}
console.log(strictRange`${1}${5}`); // '1..5'Common Errors
- Forgetting the rest parameter.
function tag(strings, values)receives only the first value invalues, and as a bare value, not an array. Write...values. - Assuming the first or last string is non-empty. A template that starts or ends with
${}has''at that edge. Code that doesstrings[0].trim()[0]or checksstrings.at(-1).lengthmust handle empty parts. - Losing count of indexes.
values[i]comes afterstrings[i]. Mixing this up shifts every value one slot over. The next chapter shows a reassembly loop that gets this right. - Mutating
strings. It is frozen. Copy it before changing anything. - Expecting strings in
values. Values keep their original types. Convert them explicitly when you need text.
Exercise
For the call tag${a}-${b}${c}, what are strings.length, values.length, and the contents of strings?
Show answer
strings.length is 4 and values.length is 3. The strings array is ['', '-', '', '']: an empty part before a, '-' between a and b, an empty part between b and c, and an empty part after c.
Exercise
Given function count(strings, ...values) { return values.length; }, what does countno substitutions here return, and how many elements does strings have?
Show answer
It returns 0. The strings array has exactly one element, 'no substitutions here', which keeps the rule strings.length === values.length + 1.
Exercise
Write a tag named kinds that returns an array describing each value as 'array', 'null', or its typeof result. What does kinds${[1]} ${null} ${'x'} return?
Show answer
function kinds(strings, ...values) { return values.map((v) => Array.isArray(v) ? 'array' : v === null ? 'null' : typeof v); } The call returns ['array', 'null', 'string'], because the tag receives the array, null, and string unchanged rather than converted to text.
Exercise
In tag${sideEffect()} where tag is undefined, does sideEffect run? Explain why.
Show answer
Yes. JavaScript evaluates the tag expression, then evaluates all substitution expressions, and only then attempts the call. The TypeError for calling a non-function is thrown after sideEffect has already run.