Sub topic 11
Invalid Escapes in Tagged Templates
This chapter assumes you already know how tag functions receive a strings array and a list of values, and that strings.raw holds the uninterpreted source text. Both were covered in the earlier chapters on tagged templates and raw strings. Here you will see what happens when the source text contains a backslash sequence that JavaScript cannot interpret, and how a tag function should handle it.
What counts as an invalid escape
An escape sequence starts with a backslash. Most are valid, such as \n, \t, \x41, and \u0041. Some combinations are not valid in a template literal:
| Sequence | Why it is invalid |
|---|---|
| `\u` not followed by 4 hex digits or `{hex}` | Malformed Unicode escape, for example `\unicode` |
| `\u{110000}` and higher | Code point above the Unicode maximum `10FFFF` |
| `\x` not followed by 2 hex digits | Malformed hex escape, for example `\xzz` |
| `\1` to `\9`, or `\0` followed by a digit | Legacy octal escapes are forbidden in templates |
These sequences show up in real text. LaTeX has \unicode, and Windows paths such as C:\users\xavier contain both \u and \x.
Untagged templates reject them
In a plain template literal, an invalid escape is a SyntaxError. The error happens at parse time, so the whole script fails to load and a surrounding try/catch in the same script cannot catch it. You can only see it by parsing code at runtime:
try {
eval("`\\unicode`");
} catch (e) {
console.log(e.name); // SyntaxError
}The double backslash in the eval string is a normal string escape. The code being parsed is ` \unicode `.
Tagged templates tolerate them
Before ES2018, tagged templates followed the same rule, which made it impossible to write tags for languages like LaTeX. The ES2018 template literal revision relaxed the rule for tagged templates only. For each string segment that contains an invalid escape:
- the cooked entry in
stringsbecomesundefined - the raw entry in
strings.rawkeeps the exact source text
function parts(strings) {
return [strings[0], strings.raw[0]];
}
console.log(parts`\unicode`); // [ undefined, '\\unicode' ]The second element prints as '\\unicode' because Node's console escapes the backslash. The actual string is the 8 characters \unicode.
Only the affected segment is undefined
The rule applies per segment, not to the whole template. Segments are the pieces between substitutions, so a bad escape in one segment leaves the others cooked normally:
function show(strings) {
return { cooked: [...strings], raw: [...strings.raw] };
}
console.log(show`\xzz${1}\n`);
// { cooked: [ undefined, '\n' ], raw: [ '\\xzz', '\\n' ] }The first segment is undefined and the second is a real newline character.
Writing tags that cope with undefined
A tag that concatenates cooked strings without checking will turn an invalid escape into the literal word "undefined" in its output:
function naive(strings, ...values) {
return strings.reduce(
(out, str, i) => out + str + (i < values.length ? values[i] : ""),
""
);
}
console.log(naive`\unicode and ${1 + 1}`); // undefined2You have three reasonable options:
- Use raw text throughout.
String.rawdoes this, which is why `String.rawC:\users\xavier` works. - Fall back to raw for broken segments. Keep cooked text where it exists.
- Throw a clear error. Use this when your tag's language has no meaning for such sequences.
Option 2 looks like this:
function lenient(strings, ...values) {
return strings.reduce((out, str, i) => {
const text = str === undefined ? strings.raw[i] : str;
return out + text + (i < values.length ? values[i] : "");
}, "");
}
console.log(lenient`\unicode and ${1 + 1}`); // \unicode and 2
console.log(String.raw`C:\users\xavier`); // C:\users\xavierOption 3 is a short check at the top of the tag:
function strict(strings, ...values) {
const bad = strings.findIndex((s) => s === undefined);
if (bad !== -1) {
throw new SyntaxError(`Invalid escape in segment ${bad}: ${strings.raw[bad]}`);
}
return strings.reduce(
(out, str, i) => out + str + (i < values.length ? values[i] : ""),
""
);
}
try {
strict`ok ${1} \xzz`;
} catch (e) {
console.log(e.message); // Invalid escape in segment 1: \xzz
}Exercise
What does this code print, and why? const f = (s) => [s.length, s[0], s[1]]; console.log(f\u{110000}${0}ok);
Show answer
It prints [ 2, undefined, 'ok' ]. The template has one substitution, so strings has two segments. The first segment contains \u{110000}, a code point above 10FFFF, so its cooked value is undefined. The second segment, ok, has no escapes and is cooked normally. Because the template is tagged, no SyntaxError is thrown.
Exercise
A teammate's tag builds output with strings.join("") and users report seeing the word "undefined" in results. What input causes this, and what is the smallest fix that keeps normal escapes like \n working?
Show answer
A segment that contains an invalid escape, such as \users in a Windows path, has a cooked value of undefined, and join turns it into the text "undefined". The smallest fix is to substitute the raw text for missing segments: strings.map((s, i) => s ?? strings.raw[i]) before joining. Valid segments keep their cooked form, so \n still becomes a newline.