Sub topic 2
What a Tag Does: Turning a Literal into a Function Call
This chapter assumes you know how to write JavaScript functions with rest parameters (...args) and are comfortable with ordinary template literals that use backticks and ${} substitutions.
The Syntax
A tagged template is a template literal with an expression placed directly in front of it. That expression is the tag, and it must evaluate to a function.
function shout(strings, ...values) {
return 'tag was called';
}
const result = shout`hello ${1 + 1}`;
console.log(result); // 'tag was called'There are no parentheses. The backtick immediately after shout tells JavaScript to call shout instead of building a string. Whatever the tag returns becomes the value of the whole expression. Here the template text is never turned into a string at all, because the function decided to return something else.
What the Call Looks Like
When JavaScript sees a tagged template, it does the following:
- Evaluates the tag expression to get a function.
- Splits the literal into its static text parts, which are the pieces between substitutions.
- Evaluates each
${}substitution from left to right. - Calls the function with an array of the text parts as the first argument and each substitution value as a separate argument after it.
Roughly, these two lines do the same thing:
function tag(strings, ...values) {
return { strings: [...strings], values };
}
const a = 'Ada';
const b = 36;
console.log(tag`Name: ${a}, age: ${b}.`);
// { strings: [ 'Name: ', ', age: ', '.' ], values: [ 'Ada', 36 ] }
console.log(tag(['Name: ', ', age: ', '.'], a, b));
// { strings: [ 'Name: ', ', age: ', '.' ], values: [ 'Ada', 36 ] }The equivalence is only approximate. The real strings array is frozen, has an extra raw property, and is reused across calls. Later chapters cover each of those details.
Evaluation Order
All substitutions are evaluated before the tag runs. The tag receives finished values, never the source code of the expressions.
function track(label) {
console.log('evaluating', label);
return label;
}
function tag(strings, ...values) {
console.log('tag called with', values);
return values.length;
}
const count = tag`first ${track('x')} then ${track('y')}`;
// evaluating x
// evaluating y
// tag called with [ 'x', 'y' ]
console.log(count); // 2This means a tag cannot skip or delay a substitution. If ${expensive()} appears in the template, expensive() runs whether or not the tag uses its result.
Common Errors
| Mistake | What happens |
|---|---|
| The tag is not a function | `TypeError: tag is not a function` at the call |
| Writing `tag(`...`)` | The template is built into a plain string first, and the tag receives one string argument |
| Expecting the tag to see `${a}` as text | The tag only receives the evaluated value of `a` |
| Assuming the result is a string | The result is whatever the tag returns |
Exercise
Given function t(s, ...v) { return v.length; }, what does t\${1}${2}${3}\` return, and what does t(\${1}${2}${3}\)` return?
Show answer
The tagged form returns 3, because the three substitutions arrive as separate values. The parenthesized form returns 0, because the template is first turned into the string '123', which is passed as the only argument s, leaving v empty.
Exercise
In tag\${log('a')}\`, can tag prevent log('a')` from running?
Show answer
No. Every substitution is evaluated before the tag function is called, so log('a') has already run by the time tag starts.