Sub topic 12
Invalid Escapes: Why Tagged Templates Allow \unicode
This chapter assumes you know how a tag receives its strings array and values, and that you understand the difference between cooked and raw strings from the earlier chapters. Here we look at one case where those two forms come apart: an escape sequence that JavaScript cannot interpret.
The Problem: Backslashes That Mean Something Else
A cooked string is the string part with its escape sequences processed, so \n becomes a newline. That processing assumes every backslash starts a valid JavaScript escape. Plenty of text breaks that assumption:
- LaTeX commands such as
\unicode,\xrightarrow, and\underline. - Windows paths such as
C:\users\xavier. - Regular expression sources or other mini-languages that use their own backslash rules.
In each case \u or \x is followed by characters that are not hexadecimal digits, so JavaScript cannot turn the sequence into a character. In ES2015 this was a syntax error everywhere, including inside tagged templates. That made tags like String.raw useless for exactly the text they were built to handle.
The ES2018 "Template Literal Revision" changed the rule for tagged templates only. An invalid escape in a tagged template no longer stops the parse. The cooked value for that string part becomes undefined, and the raw value keeps the original text. Untagged templates still throw.
Which Escapes Count as Invalid
In a template literal, these backslash sequences are invalid:
\unot followed by exactly four hex digits, or by{...}holding a code point up to10FFFF.\xnot followed by exactly two hex digits.- A backslash followed by a digit
1to9, or\0followed by another digit. Legacy octal escapes are never allowed in templates.
| Source text | Valid? | Cooked value | Raw value |
|---|---|---|---|
| `\u0041` | Yes | `'A'` | `'\\u0041'` |
| `\u{1F600}` | Yes | `'😀'` | `'\\u{1F600}'` |
| `\unicode` | No | `undefined` | `'\\unicode'` |
| `\u{110000}` | No (above the maximum code point) | `undefined` | `'\\u{110000}'` |
| `\xff` | Yes | `'ÿ'` | `'\\xff'` |
| `\xZZ` | No | `undefined` | `'\\xZZ'` |
| `\0` | Yes | `'\0'` (NUL) | `'\\0'` |
| `\01`, `\7`, `\8` | No | `undefined` | the text as written |
Unknown single-character escapes such as \q or \c are not invalid. They cook to the character itself ('q'), as they do in ordinary strings. Only the \u, \x, and digit forms can fail.
Tagged Versus Untagged: A Parse-Time Difference
The error for an untagged template happens when the code is parsed, not when it runs. You cannot wrap the literal in try/catch, because the script containing it never starts. To observe the difference safely, compile source code at run time with the Function constructor:
const sources = [
'String.raw`\\unicode`',
'`\\unicode`',
'String.raw`C:\\users\\xavier`',
'String.raw`a ${`\\unicode`} b`',
];
for (const src of sources) {
try {
new Function(src);
console.log('parses: ', src);
} catch (e) {
console.log(e.name + ':', src);
}
}
// parses: String.raw`\unicode`
// SyntaxError: `\unicode`
// parses: String.raw`C:\users\xavier`
// SyntaxError: String.raw`a ${`\unicode`} b`The last line is the one people miss. The exemption applies only to the string parts of the tagged literal itself. A template nested inside a ${} substitution is its own untagged literal, so it gets the strict rule and the whole script fails to parse.
Only the Affected Part Becomes undefined
The cooked value is set per string part, not for the whole literal. Other parts are processed normally, and the array keeps its usual length of one more than the number of values.
function parts(strings, ...values) {
return strings.map((cooked, i) => ({ cooked, raw: strings.raw[i] }));
}
const result = parts`ok\n${1}\xZZ${2}fine`;
console.log(result.length); // 3
console.log(result[0].cooked); // 'ok' followed by a real newline
console.log(result[1]); // { cooked: undefined, raw: '\\xZZ' }
console.log(result[2]); // { cooked: 'fine', raw: 'fine' }The middle part contains \xZZ, so its cooked value is undefined. The first part still has a real newline, and the third part is untouched.
Why String.raw Just Works
String.raw reads only strings.raw. It never looks at the cooked values, so an undefined cooked part makes no difference to it. Since ES2018 this works for LaTeX-style text:
const formula = String.raw`\unicode{x2603} \xrightarrow{f} \underline{x}`;
console.log(formula);
// \unicode{x2603} \xrightarrow{f} \underline{x}
const path = String.raw`C:\users\xavier\new`;
console.log(path);
// C:\users\xavier\newOne limit remains, and the revision does not touch it. A raw string still cannot end with a single backslash, because ` \ ` escapes the closing backtick. String.rawC:\ is an unterminated literal. Put the trailing backslash in a substitution instead: String.rawC:${'\\'} `.
The Silent Failure in Your Own Tags
The reassembly pattern from earlier chapters looks like this:
function naive(strings, ...values) {
return strings.reduce((out, str, i) => out + values[i - 1] + str);
}
console.log(naive`label: \unicode ${42}`);
// 'undefined42'Nothing throws. The first part is undefined, so reduce starts with undefined as the accumulator, and string concatenation turns it into the text "undefined". The output is wrong, and nothing tells you why. Any tag that reads cooked strings has to choose a policy for this case.
Policy 1: Reject Invalid Escapes
If your tag represents normal JavaScript text, such as an HTML or SQL tag, an invalid escape is almost certainly a typo. Fail loudly and point at the raw text:
function strictCooked(strings) {
strings.forEach((str, i) => {
if (str === undefined) {
throw new SyntaxError(
`Invalid escape sequence in template part ${i}: ${strings.raw[i]}`,
);
}
});
return strings;
}
function text(strings, ...values) {
const cooked = strictCooked(strings);
return cooked.reduce((out, str, i) => out + String(values[i - 1]) + str);
}
console.log(text`Total: ${3}\n`); // 'Total: 3' plus a newline
try {
text`path \users`;
} catch (e) {
console.log(e.message);
// Invalid escape sequence in template part 0: path \users
}This error happens at run time, when the tag is called, rather than at parse time. That is still far better than producing "undefined" in the output.
Policy 2: Fall Back to Raw
If your tag represents a language that has its own backslash rules, use the raw text where the cooked text is missing. You could also use raw text everywhere, as String.raw does.
function lenient(strings, ...values) {
const parts = strings.map((str, i) => str ?? strings.raw[i]);
return parts.reduce((out, str, i) => out + String(values[i - 1]) + str);
}
console.log(lenient`tab:\there, macro:\unicode`);
// 'tab:' + real tab + 'here, macro:\unicode'Mixing the two forms like this can be surprising: \t became a tab while \unicode stayed literal. For most DSL tags, a cleaner rule is to use strings.raw throughout and interpret backslashes yourself.
Choosing a Policy
| Tag purpose | Recommended handling | Reason |
|---|---|---|
| HTML, SQL, logging, i18n | Throw on `undefined` | An invalid escape there is a bug in the source |
| LaTeX, regex, shell, paths | Read `strings.raw` only | The embedded language owns backslash meaning |
| Generic utility tag | Throw, or document the fallback | Silent `"undefined"` output is never correct |
Exercises
Exercise
What does each line do: (a) ` String.raw\xylophone , (b) \xylophone , (c) String.raw${\xylophone} `?
Show answer
(a) Returns the string \xylophone, because the literal is tagged and String.raw reads only raw text. (b) Throws a SyntaxError at parse time, because an untagged template cannot contain the invalid escape \xy. (c) Also throws a SyntaxError at parse time, because the inner template inside ${} is itself untagged.
Exercise
Given function f(s) { return [s.length, s[0], s[1], s.raw[1]]; }, what does ` fa\n${0}\u{110000} ` return?
Show answer
[2, 'a' followed by a newline, undefined, '\\u{110000}']. There is one substitution, so there are two string parts. The first part has a valid \n escape. The second part's code point is above 10FFFF, so its cooked value is undefined and the raw value keeps the source text, which is a single backslash followed by u{110000}.
Exercise
A teammate's tag ` tSaved to C:\users\${name} ` prints "undefinedAda". Explain the cause and give two fixes.
Show answer
The \u in \users is an invalid escape, so strings[0] is undefined. reduce uses it as the starting accumulator, and concatenation turns it into the text "undefined". Fix 1: make the tag throw a clear error when a cooked part is undefined, then write the path as C:\\users\\ in the source. Fix 2: if the tag is meant for paths, build the output from strings.raw (for example with String.raw(strings, ...values)) so backslashes stay literal.