Sub topic 2
What a Tag Does: Turning a Literal into a Function Call
This chapter assumes you can write JavaScript functions with rest parameters (...args) and that you know basic template literals: backticks, ${} substitutions, and multiline strings. We will look at what JavaScript does when an expression sits directly in front of a template literal, in what order the pieces are evaluated, and what the call returns. Later chapters cover the arguments in detail and how to work with them.
The Core Idea
A tagged template is a template literal with an expression placed directly before it. That expression is the tag. JavaScript does not build a string from the literal. It calls the tag as a function and passes it the pieces of the literal.
function tag(strings, ...values) {
console.log('tag called with', strings.length, 'strings and', values.length, 'values');
return 'whatever the tag returns';
}
const x = 10;
const result = tag`x is ${x}, doubled is ${x * 2}`;
// logs: tag called with 3 strings and 2 values
console.log(result); // 'whatever the tag returns'The syntax has no parentheses, yet tag runs as a normal function call. The whole expression ` tag... evaluates to whatever the function returns. Here that is a fixed string that has nothing to do with the template. The tag has full control, and JavaScript never builds the interpolated string 'x is 10, doubled is 20'` for you.
Roughly, the call above behaves like this:
tag(['x is ', ', doubled is ', ''], x, x * 2);The first argument holds the static text, split wherever a ${} appears. The remaining arguments are the evaluated substitutions, in order. The equivalence is only approximate. The real first argument is a special frozen array with an extra raw property, and JavaScript reuses it across calls. Later chapters explain those details.
Evaluation Order
Three things happen, always in this order:
- JavaScript evaluates the tag expression to get the function.
- It evaluates every
${}substitution from left to right. - It calls the function with the strings array and the values.
The example below logs each step so you can see the order.
const log = [];
function getTag() {
log.push('tag expression');
return (strings, ...values) => {
log.push('tag body');
return values;
};
}
function v(label) {
log.push('value ' + label);
return label;
}
const out = getTag()`${v('a')} and ${v('b')}`;
console.log(log); // [ 'tag expression', 'value a', 'value b', 'tag body' ]
console.log(out); // [ 'a', 'b' ]The example also shows that the tag can be any expression that produces a function, including the result of another call. ` getTag()... calls getTag` first and then tags the template with the function it returned.
Each Evaluation Is a New Call
A tagged template is an expression, so the tag runs every time the expression is evaluated. Inside a loop or a function body, you get one call per evaluation.
let calls = 0;
function count(strings, ...values) {
calls++;
return values[0];
}
const results = [];
for (let i = 0; i < 3; i++) {
results.push(count`item ${i}`);
}
console.log(calls); // 3
console.log(results); // [ 0, 1, 2 ]Tagged Versus Untagged: What Changes
An untagged template converts every substitution to a string and joins everything together. A tagged template does no conversion and no joining. Values reach the tag exactly as they were evaluated.
const obj = { n: 1 };
console.log(`${obj}`); // '[object Object]'
function keep(strings, ...values) {
return values[0];
}
console.log(keep`${obj}` === obj); // true: the object itself, not a stringThis difference matters in practice. Libraries depend on getting real objects, functions, and arrays as values. It also changes some failure modes. A Symbol cannot be converted to a string implicitly, so an untagged template throws, while a tagged template simply passes the symbol along:
const sym = Symbol('id');
try {
`${sym}`;
} catch (e) {
console.log(e instanceof TypeError); // true
}
console.log(typeof keep`${sym}`); // 'symbol'| Aspect | Untagged `` `...` `` | Tagged `` tag`...` `` |
|---|---|---|
| Result | Always a string | Whatever the tag returns |
| Substitutions | Converted with string conversion | Passed through unchanged |
| Static text | Joined with the values | Passed as a separate array |
| Who decides the output | The language | The tag function |
| Invalid escapes like `\unicode` | Syntax error | Allowed (covered in a later chapter) |
Edge Cases of the Syntax
Templates with no substitutions
A tag still gets called when the template has no ${}. The strings array then has exactly one element and there are no values. An empty template gives a single empty string.
function inspectArgs(strings, ...values) {
return { strings: [...strings], valueCount: values.length };
}
console.log(inspectArgs`hello`); // { strings: [ 'hello' ], valueCount: 0 }
console.log(inspectArgs``); // { strings: [ '' ], valueCount: 0 }Substitutions at the edges
If the template starts or ends with ${}, the strings array gets an empty string at that end. The strings array therefore always has one more element than there are values, which the next chapter relies on.
console.log(inspectArgs`${1}${2}`); // { strings: [ '', '', '' ], valueCount: 2 }The tag must be callable
The tag is called like any other function. If the expression evaluates to something that is not a function, you get a TypeError at runtime, not a syntax error:
const notAFunction = 42;
try {
notAFunction`hi`;
} catch (e) {
console.log(e instanceof TypeError); // true
console.log(e.message); // e.g. 'notAFunction is not a function'
}Whitespace and line breaks between tag and backtick
Spaces and even line breaks are allowed between the tag and the opening backtick. This creates a trap in code that leaves out semicolons. Automatic semicolon insertion does not happen before a backtick, so a line ending in an expression joins with a following line that starts with a template:
let caught = null;
try {
const label = 'x'
`template`.length
} catch (e) {
caught = e;
}
console.log(caught instanceof TypeError); // true: parsed as 'x'`template`.lengthThe engine reads this as tagging the template with the string 'x', which is not a function. If you leave out semicolons, put one before any line that starts with a backtick, or use a linter rule that catches it.
The tag can ignore its arguments
The tag's only job is to be a function. It may use all of its arguments, some of them, or none. The tag function in the first example ignored the values entirely. This flexibility is why a tag can return a DOM template, a query object, or a parsed syntax tree instead of a string.
Calling a Tag Function Directly
A tag is an ordinary function, so you can also call it with parentheses. This is handy for quick tests:
function joinAll(strings, ...values) {
return strings.reduce((out, str, i) => out + values[i - 1] + str);
}
console.log(joinAll`a${1}b${2}c`); // 'a1b2c'
console.log(joinAll(['a', 'b', 'c'], 1, 2)); // 'a1b2c'The two calls only look alike. A hand-made array has no raw property, is not frozen, and is a new array on every call. Tags that read strings.raw or cache on the array's identity behave differently when called this way. Write tags for the template syntax, and use direct calls only when you know the tag doesn't depend on those features.
Exercise
What does this code log, and in what order? const t = (s, ...v) => { console.log('T'); return v.length; }; const f = () => { console.log('F'); return t; }; const g = (n) => { console.log('G' + n); return n; }; console.log(f()${g(1)}-${g(2)});
Show answer
It logs F, G1, G2, T, and then 2. The tag expression f() is evaluated first, then the substitutions left to right, then the tag is called. The tag returns the number of values, which is 2.
Exercise
Given function first(strings, ...values) { return values[0]; }, what does ` typeof first${[1, 2]} evaluate to, and what would typeof ${[1, 2]} ` evaluate to? Why do they differ?
Show answer
The tagged version gives 'object', because the array reaches the tag unchanged. The untagged version gives 'string', because an untagged template converts each substitution to a string, which here gives '1,2'.
Exercise
How many elements are in the strings array and how many values are passed for the template ` tag${a} `? What are the strings?
Show answer
Two strings and one value. Both strings are empty: [ '', '' ], one before and one after the substitution. There is always one more string than there are values.