Sub topic 11
Invalid Escapes in Tagged Templates
The earlier chapters covered tag functions, the strings and strings.raw arrays, and template object caching. This chapter covers one remaining edge case: what happens when a template contains a backslash sequence that JavaScript cannot interpret. In an untagged template literal this is a syntax error. In a tagged template, since ES2018, it is allowed: the cooked string for that part becomes undefined, and the raw text is kept.
This chapter assumes you are comfortable with:
- writing tag functions with the signature
(strings, ...values) - the difference between cooked strings (
strings[i]) and raw strings (strings.raw[i]) String.rawArray.prototype.reduce,map, andfindIndex
Why This Rule Exists
Tagged templates are often used to embed small languages: LaTeX, regular expressions, shell commands, Windows paths, or custom DSLs. Backslashes in those languages mean something that has nothing to do with JavaScript escapes.
Consider a LaTeX tag:
function latex(strings) {
return strings.raw.join("");
}
console.log(latex`\unicode{x}`); // \unicode{x}The tag only reads strings.raw, so it never needs JavaScript to interpret \unicode. Before ES2018, though, the engine still tried to cook every template part. It saw \u, expected four hex digits, found nicode, and threw a SyntaxError before the tag ever ran. The same thing happened with Windows paths such as C:\xampp\users, where \x and \u each start an escape that cannot be completed.
The ES2018 "template literal revision" relaxed the rule for tagged templates only. The engine no longer refuses to parse the code. It records that this part could not be cooked and passes the raw text through.
What Counts as an Invalid Escape
Inside a template literal, a backslash can start a valid escape, a "non-escape character" that just yields itself, or an invalid escape. The invalid ones are the escapes that start a numeric sequence and then fail to complete it, plus the legacy octal forms.
| Sequence | Example | Valid in templates? | Cooked value |
|---|---|---|---|
| `\n`, `\t`, `\\`, `` \` ``, `\$` | `` `a\tb` `` | Yes | Tab, newline, etc. |
| Non-escape letter | `` `\d` ``, `` `\a` `` | Yes | `"d"`, `"a"` (backslash dropped) |
| `\0` not followed by a digit | `` `\0x` `` | Yes | NUL character then `x` |
| `\x` + 2 hex digits | `` `\x41` `` | Yes | `"A"` |
| `\x` without 2 hex digits | `` `\xyz` `` | No | `undefined` in a tag |
| `\u` + 4 hex digits | `` `\u0041` `` | Yes | `"A"` |
| `\u{...}` up to `10FFFF` | `` `\u{1F600}` `` | Yes | Emoji |
| `\u` followed by anything else | `` `\unicode` `` | No | `undefined` in a tag |
| `\u{...}` above `10FFFF` | `` `\u{110000}` `` | No | `undefined` in a tag |
| `\0` followed by a digit | `` `\01` `` | No | `undefined` in a tag |
| `\1` through `\9` | `` `\8` `` | No | `undefined` in a tag |
Two of these rows trip people up.
First, octal escapes like \01 are always invalid in templates, even in sloppy mode where "\01" in an ordinary string still works. Templates never supported legacy octal.
Second, \d is valid and cooks to plain "d". No error and no undefined appear, so the backslash silently disappears. If you build a regular expression from a cooked template, \d becomes d. This is a separate trap from invalid escapes, and the fix is the same: read the raw strings.
Untagged vs Tagged Behavior
The relaxation applies only when a tag is present. An untagged template with an invalid escape is an early error, which means the whole script or module fails to parse and none of it runs.
// Wrap in eval so this file can still run and show the error.
try {
eval("`\\unicode`");
} catch (e) {
console.log(e.name); // SyntaxError
}
function parts(strings) {
return [strings[0], strings.raw[0]];
}
console.log(parts`\unicode`); // [ undefined, '\\unicode' ]The eval source string is ` \unicode : the doubled backslash in the JavaScript string literal produces one backslash in the evaluated code. The tagged version on its last line parses fine and gives the tag undefined` for the cooked part.
String.raw is a tag too, so it benefits from the same rule:
console.log(String.raw`C:\xampp\users`); // C:\xampp\users
console.log(String.raw`\unicode`.length); // 8String.raw reads only the raw array, so the undefined cooked entries never matter to it.
The Whole Part Becomes undefined
The cooked value is per part, where a part is the literal text between two substitutions, or between a substitution and a backtick. One invalid escape wipes out the cooked value for its whole part, including any valid escapes in the same part. Other parts are unaffected.
function inspect(strings) {
return strings.map((cooked, i) => ({ cooked, raw: strings.raw[i] }));
}
console.log(inspect`a\xyz\n${1}b\u{41}`);
// [
// { cooked: undefined, raw: 'a\\xyz\\n' },
// { cooked: 'bA', raw: 'b\\u{41}' }
// ]The first part contains a valid \n, but because \xyz is invalid in the same part, the cooked value for that part is undefined. No partially cooked string exists anywhere. The second part cooks normally.
The strings array keeps its usual length, one more than the number of values. The undefined entry sits in its slot like any other string would. The template object is still frozen and still cached per call site, as described in the previous chapter. The cached array simply contains undefined at that index every time.
Substitutions do not complete an escape
Escapes are resolved per part, before any substitution happens. An escape cannot borrow characters from an interpolated value:
function show(strings, ...values) {
return { cooked: strings[0], raw: strings.raw[0], values };
}
console.log(show`\u${"0041"}`);
// { cooked: undefined, raw: '\\u', values: [ '0041' ] }The first part is just \u, which is incomplete, so its cooked value is undefined. The "0041" value is never joined onto it to form \u0041. If you need a character from a computed code point, use String.fromCodePoint(0x41) inside the substitution.
Writing Tags That Handle undefined
Many tag functions are written as if every strings[i] is a string. Those tags break when an invalid escape appears:
function naive(strings, ...values) {
return strings.reduce(
(out, str, i) => out + str + (i < values.length ? values[i] : ""),
""
);
}
console.log(naive`Path: C:\users\${"ada"}`); // undefinedadaHere the first part, Path: C:\users\, contains \u followed by sers, so it is invalid. The naive tag concatenates undefined, which converts to the text "undefined". The output looks like a typo, and nothing tells you an escape was involved. (The second part is the empty string after the substitution.)
Wait, look again at that template: the backslash right before ${ escapes the dollar sign, so ${"ada"} would not be a substitution. Escaping $ is exactly the rule from the escaping chapter. To keep the example honest, here is a version where the substitution stays real:
function naive(strings, ...values) {
return strings.reduce(
(out, str, i) => out + str + (i < values.length ? values[i] : ""),
""
);
}
console.log(naive`Path: C:\users ${"ada"}`); // undefinedadaA tag author has three reasonable choices.
Option 1: Use only raw strings
If the tag embeds another language, ignore cooked strings entirely. This is what String.raw does, and it makes invalid escapes a non-issue.
function rawJoin(strings, ...values) {
return strings.raw.reduce(
(out, str, i) => out + str + (i < values.length ? values[i] : ""),
""
);
}
console.log(rawJoin`Path: C:\users ${"ada"}`); // Path: C:\users adaOption 2: Throw a clear error
If the tag expects normal JavaScript escapes, an invalid one is almost certainly a bug. Report it with the raw text so the author can find it.
function strict(strings, ...values) {
const bad = strings.findIndex((s) => s === undefined);
if (bad !== -1) {
throw new SyntaxError(
`Invalid escape in template part ${bad}: ${JSON.stringify(strings.raw[bad])}`
);
}
return strings.reduce(
(out, str, i) => out + str + (i < values.length ? values[i] : ""),
""
);
}
console.log(strict`Hello ${"Ada"}\n`); // Hello Ada (followed by a newline)
try {
strict`Path: C:\users ${"ada"}`;
} catch (e) {
console.log(e.message); // Invalid escape in template part 0: "Path: C:\\users "
}Check with === undefined, not a falsy test. Empty cooked strings ("") are very common, for example the last part of ` taga${x} `, and a falsy check would treat them as errors.
Because template objects are cached per call site, a tag can validate once per call site and store the result in a WeakMap keyed by strings, so the check costs nothing after the first call.
Option 3: Fall back to raw for the broken part
A forgiving tag can use the raw text for any part that failed to cook:
function cookedOrRaw(strings, ...values) {
let out = "";
strings.forEach((s, i) => {
out += s ?? strings.raw[i];
if (i < values.length) out += values[i];
});
return out;
}
const result = cookedOrRaw`C:\xampp and ${1 + 1} tabs:\t|`;
console.log(JSON.stringify(result)); // "C:\\xampp and 2 tabs:\t|"The first part is invalid and comes through raw, with its backslash intact. The second part is valid and cooked, so \t became a real tab. That mix is the weakness of this option: whether \t means "tab" or "backslash, t" now depends on whether some other escape in the same part happens to be invalid. Use this only when you document the behavior and accept that inconsistency.
| Strategy | Good for | Risk |
|---|---|---|
| Raw only | DSLs, paths, regex, LaTeX | Users cannot write `\n` to mean a newline |
| Throw on `undefined` | Tags that expect normal JS strings | Rejects input that `String.raw` would accept |
| Fall back to raw per part | Lenient formatting helpers | Escape meaning depends on neighboring escapes |
Other Details Worth Knowing
The raw strings are not completely untouched source. Line terminators are normalized: a CRLF or lone CR in the source file becomes \n in both cooked and raw values. A file saved with Windows line endings therefore produces the same raw strings as one saved with Unix line endings.
A line continuation, a backslash immediately followed by a line break, is a valid escape. It cooks to nothing, removing both characters, while the raw value keeps the backslash and the newline.
Tooling can lag behind the language. Old transpiler configurations or very old engines that predate ES2018 may still reject ` String.raw\unicode ` at parse time. If you target such environments, test that your build accepts these templates.
Exercises
Exercise
What does this code print, and why? function t(s) { return [s[0], s[1]]; } console.log(t\x4${0}\x41);
Show answer
It prints [ undefined, 'A' ]. The first part is \x4, which has only one hex digit after \x, so it is invalid and its cooked value is undefined. The substitution does not supply the missing digit, because escapes are resolved per part before substitution. The second part, \x41, is a valid hex escape and cooks to "A".
Exercise
A teammate writes a tag that checks if (!strings[i]) throw new Error("bad escape"). What goes wrong with a call such as tagHello ${name}?
Show answer
The last part of that template is the empty string "", which is falsy, so the tag throws even though nothing is invalid. The check must be strings[i] === undefined, which matches only parts that failed to cook.
Exercise
Which of these is a SyntaxError, and which runs? (1) \unicode (2) String.raw\unicode (3) \d (4) \01
Show answer
(1) and (4) are SyntaxErrors because they are untagged templates containing invalid escapes: an incomplete \u and a legacy octal escape. (2) runs and produces the 8-character string \unicode, because tagged templates allow invalid escapes and String.raw reads only raw text. (3) runs and produces "d", because \d is a non-escape character that cooks to the letter itself.
Exercise
Write a tag pathJoin so that pathJoinC:\users\${"ada"}\docs is not a problem to fix, but explain first why that exact call does not interpolate "ada".
Show answer
The backslash right before ${ escapes the dollar sign, so ${"ada"} is literal text, not a substitution. The template has no values, and its single part contains \u followed by "sers", which is invalid, so its cooked value is undefined. To interpolate, put a space or other character between the backslash and ${, or build the separator in the expression: pathJoinC:\users${"\\ada"}\docs. A suitable tag reads raw strings: function pathJoin(strings, ...values) { return strings.raw.reduce((out, s, i) => out + s + (i < values.length ? values[i] : ""), ""); }. That call returns C:\users\ada\docs.