Sub topic 12
Invalid Escapes: Why Tagged Templates Allow \unicode
This chapter assumes you already know how a tag receives its strings array, and how cooked strings differ from raw ones (strings.raw). It covers a narrow rule from ES2018: what happens when a template contains a backslash sequence that is not a valid escape.
The Problem Before ES2018
In an ordinary template literal, the engine must turn every escape into its character. Some sequences cannot be turned into a character, so the parser rejects the whole script with a SyntaxError:
| Sequence | Why it is invalid |
|---|---|
| `\unicode` | `\u` must be followed by 4 hex digits or `{hex}` |
| `\xerxes` | `\x` must be followed by 2 hex digits |
| `\1`, `\01` | Octal-style escapes are not allowed in templates |
Before ES2018 this rule also applied to tagged templates. That blocked useful DSLs. A LaTeX tag could not contain \unicode. A Windows path tag could not contain C:\xampp. The tag only wanted the raw text, but the parser still refused to cook the strings.
The ES2018 Revision
The template literal revision relaxed the rule for tagged templates only:
- An untagged template with an invalid escape is still a
SyntaxError. - In a tagged template, the cooked string for that part becomes
undefined. - The raw string for that part is kept as written.
- Other parts of the same template are cooked normally.
Seeing It Run
Because an untagged invalid template stops the whole file from parsing, the example below uses eval to show the error without breaking the rest of the script.
try {
eval('`\\unicode`'); // untagged: source text is `\unicode`
} catch (err) {
console.log(err.name); // 'SyntaxError'
}
function inspect(strings, ...values) {
return strings.map((cooked, i) => ({ cooked, raw: strings.raw[i] }));
}
console.log(inspect`\unicode ${1} \u{41}`);
// [
// { cooked: undefined, raw: '\\unicode ' },
// { cooked: ' A', raw: ' \\u{41}' }
// ]The invalid escape affects only the part it appears in. The second part still cooks \u{41} to A.
Writing Tags That Cope With undefined
A tag that reads raw strings works with no changes. String.raw is one of them:
const latex = String.raw;
console.log(latex`\unicode{x} and \xerxes`); // '\unicode{x} and \xerxes'A tag that reads cooked strings needs a decision. If you just concatenate, you get the text "undefined" in your output:
function naive(strings, ...values) {
return strings.reduce((out, str, i) => out + values[i - 1] + str);
}
console.log(naive`path: C:\xampp`); // 'undefined'The usual fix is to fail loudly, or to fall back to the raw text on purpose:
function strict(strings, ...values) {
strings.forEach((s, i) => {
if (s === undefined) {
throw new SyntaxError(`Invalid escape in part ${i}: ${strings.raw[i]}`);
}
});
return strings.reduce((out, str, i) => out + values[i - 1] + str);
}
try {
strict`C:\xampp`;
} catch (err) {
console.log(err.message); // 'Invalid escape in part 0: C:\xampp'
}Exercise
What does ((s) => [s[0], s.raw[0]])\xyz` return, and what happens if you remove the tag and write just \xyz `?
Show answer
The tagged form returns [undefined, '\\xyz'], because \x is not followed by two hex digits, so the cooked part is undefined and the raw part keeps the original text. Without the tag, the script fails to parse with a SyntaxError.
Exercise
In tagok ${1} \u00e9 ${2} \u{zz}`, which entries of strings` are undefined?
Show answer
Only strings[2] ( \u{zz}) is undefined. strings[0] is 'ok ', and strings[1] cooks \u00e9 to ' é '. Each part is cooked on its own.