Unicode in JavaScript Source Code: Escapes, Normalization and Invisible Characters
How JavaScript handles Unicode in your source code: \u escapes in strings and identifiers, why emoji have length 2, composed vs decomposed characters and normalize(), invisible and look-alike characters that create "impossible" bugs, Trojan Source attacks, and how to protect a codebase.
kvi5hnuCode Sprout team member8 min readOn this page
JavaScript source code is Unicode text. You can write "नमस्ते", "¡Hola!" or "😀" directly in a string, and even use non-English letters in variable names. Most of the time this just works. But Unicode allows the same visible text to be stored in different ways, and allows characters that are not visible at all. Both produce bugs that look impossible until you know what's going on.
This article covers:
- how to write any character using only ASCII, with escape sequences,
- why
"😀".lengthis 2, - why two strings that look identical can be
!==, and hownormalize()fixes it, - invisible and look-alike characters, and the "Trojan Source" attack,
- practical rules for keeping a codebase safe.
Code points and code units in 60 seconds
Unicode gives every character a number called a code point, written U+ followed by hexadecimal: A is U+0041, é is U+00E9, 😀 is U+1F600. Code points range up to U+10FFFF.
JavaScript strings, however, are sequences of 16-bit code units (the UTF-16 encoding). Characters up to U+FFFF fit in one code unit. Characters above it, which include most emoji, need two code units called a surrogate pair. That's why:
const smile = "\u{1F600}"; // one emoji, written as an escape
console.log(smile);
console.log(smile.length); // 2 code units
console.log([...smile].length); // 1 code point: spreading iterates by code point
console.log(smile === "😀"); // the same surrogate pair, written explicitly
console.log(smile.codePointAt(0).toString(16));
😀
2
1
true
1f600
length counts code units, not what a person would call characters. Part 3 explains how to count characters correctly, including emoji built from several code points.

Unicode escape sequences
An escape sequence lets you write any character using only ASCII characters. There are two Unicode forms:
\uXXXX: exactly four hex digits, for code points up to U+FFFF.\u{X}to\u{XXXXXX}: one to six hex digits in braces (ES2015), for any code point.
Strings also accept \xHH with two hex digits (U+0000 to U+00FF).
console.log("A\u{42}\x43"); // ABC
console.log("café" === "café"); // the escape and the literal character are the same string
console.log("\u{1F680} launch"); // above U+FFFF: needs the braces form
console.log("🚀 launch"); // or an explicit surrogate pair
ABC
true
🚀 launch
🚀 launch
Where escapes are allowed:
| Place | Escapes allowed? | Notes |
|---|---|---|
| String and template literals | yes | the most common use |
| Regular expression literals | yes | \u{...} needs the u or v flag |
| Identifiers | yes | café is the same name as café |
| Keywords | no | if is not if: it's a SyntaxError |
| Comments | ignored | escapes in comments are just text |
eval("var caf\\u00e9 = 7;"); // declares a variable named café
console.log(café);
try {
eval("var \\u0069f = 1;"); // tries to spell the keyword if with an escape
} catch (err) {
console.log(err.name + ": " + err.message);
}
7
SyntaxError: Keyword must not contain escaped characters
Escapes in identifiers are legal but almost never useful. Their real-world use is in strings, for characters that are hard to type or invisible: "\u00a0" (a no-break space) is far clearer in code review than a literal no-break space, which looks exactly like a normal one.
One visible text, two encodings: normalization
Many accented letters can be stored in two ways:
- composed: one code point,
é= U+00E9, - decomposed: a base letter plus a combining mark,
eU+0065 followed by U+0301 (combining acute accent).
They render identically, but they're different strings:
const composed = "café"; // é as one code point
const decomposed = "cafe\u0301"; // e + combining acute accent
console.log(composed, decomposed); // they look the same
console.log(composed === decomposed);
console.log(composed.length, decomposed.length);
console.log([...decomposed].map(c => c.codePointAt(0).toString(16)));
// normalize() converts both to the same canonical form:
console.log(composed.normalize("NFC") === decomposed.normalize("NFC"));
console.log(composed.normalize("NFD").length);
café café
false
4 5
[ '63', '61', '66', '65', '301' ]
true
5
Where does decomposed text come from? Some operating systems store file names decomposed (macOS's older HFS+ file system always did), some keyboards and input methods produce combining marks, and text copied from PDFs often contains them. So a user can type "café" in a search box and fail to match "café" in your database.
string.normalize(form) converts text to one of four standard forms:
| Form | What it does | Typical use |
|---|---|---|
"NFC" (default) | compose wherever possible | storing and comparing text: use this by default |
"NFD" | decompose everything | stripping accents (decompose, then remove combining marks) |
"NFKC" | compose and also fold "compatibility" variants | search and identifiers: turns ABC (full-width) into ABC and the ligature fi into fi |
"NFKD" | decompose and fold compatibility variants | like NFKC, but decomposed |
console.log("ABC".normalize("NFKC")); // full-width ABC
console.log("file".normalize("NFKC")); // the ligature fi + "le"
const stripAccents = s => s.normalize("NFD").replace(/\p{M}/gu, "");
console.log(stripAccents("Crème Brûlée à São Paulo"));
ABC
file
Creme Brulee a Sao Paulo
\p{M} in the regular expression matches any combining mark. Decomposing first separates the accents from their letters, so removing the marks leaves plain letters.
The same problem affects identifiers in your source: a variable named with a composed é and one named with a decomposed é are two different variables that look identical. JavaScript doesn't normalize source code for you. If you use non-ASCII names at all, make sure your editor saves text in NFC (most do by default).
Invisible and look-alike characters
Some characters are designed to be invisible, and JavaScript allows two of them, the zero-width joiner (U+200D) and zero-width non-joiner (U+200C), inside identifiers, because some scripts need them to spell words correctly. That means two names can look identical but differ:
const result = eval(`
var count = 1;
var co\\u200Dunt = 2; // "count" with a zero-width joiner after "co"
[count, co\\u200Dunt]
`);
console.log(result); // two different variables
[ 1, 2 ]
Similarly, many letters from different alphabets look the same. Latin a (U+0061) and Cyrillic а (U+0430) are indistinguishable in most fonts, so "pаypal" === "paypal" can be false. Such look-alikes are called homoglyphs or confusables. They're a favorite tool for phishing domain names and for sneaking bugs into code review.
Keeping a codebase safe
| Problem | Defense |
|---|---|
| Invisible whitespace in code | ESLint's no-irregular-whitespace rule (on in the recommended config); editor "render whitespace" |
| Invisible characters in strings | write them as \u escapes; ESLint no-misleading-character-class catches some regex cases |
| Look-alike identifiers | keep identifiers ASCII; review diffs in a tool that highlights non-ASCII |
| Bidirectional controls | editor and Git host warnings; reject them in CI with a simple search for U+202A to U+202E and U+2066 to U+2069 |
| Composed vs decomposed user input | normalize("NFC") before storing, comparing or using text as a key |
| File encoding | save source files as UTF-8; in HTML include <meta charset="utf-8"> |
Common questions
Can I use emoji as variable names?
No. Identifiers may contain letters (from any alphabet), digits, $, _ and a few joiner characters, but emoji are symbols, not letters. var 😀 = 1 is a SyntaxError. Emoji are fine inside strings, of course.
Does === compare strings by how they look?
No. === compares strings code unit by code unit. Two strings that render identically but use different code points (composed vs decomposed accents, Latin vs Cyrillic letters) are not equal. Normalize first to handle the accent case. Look-alike letters from different alphabets can't be fixed by normalization; that requires a "confusables" check.
Should I normalize every string in my program?
Normalize at the boundaries where it matters: when you store user-provided text, compare it, or use it as a map key or identifier. Normalizing the same text repeatedly is harmless but wasteful.
What about \n, \t and other escapes?
Those are string escape sequences, covered with strings in part 3. Unicode escapes are just one family of escapes; they're the only family that also works in identifiers.
Summary
- Source code is Unicode. Strings are sequences of UTF-16 code units, so characters above U+FFFF (most emoji) have
length2. \uXXXXand\u{X...}(plus\xHHin strings) write any character in ASCII. They work in strings, regexes and identifiers, but not in keywords, and are ignored in comments.- The same visible text can have several encodings. Use
normalize("NFC")before comparing or storing,NFKCfor search-style matching, andNFDplus/\p{M}/guto strip accents. - Invisible joiners and look-alike letters can create different names that look identical, and bidirectional controls enable Trojan Source attacks. Keep identifiers ASCII, write invisible characters as escapes, and let linters and CI flag the rest.
Practice Questions
What do "\u{1F600}".length and [..."\u{1F600}"].length return, and why do they differ?
Answer
2 and 1. length counts UTF-16 code units, and U+1F600 needs a surrogate pair. Spreading a string iterates by code point, so it yields one element.
A user registers the name "José", and later logs in typing "José", but your lookup in a Map fails. Both look identical. What is the likely cause and the fix?
Answer
One of the strings probably has a composed é (U+00E9) and the other a decomposed e + U+0301, so the keys differ. Normalize both, typically with name.normalize("NFC"), before storing and before looking up.
Is var a = 5; legal? What about var if = 5;?
Answer
The first is legal: a is a, so it declares a variable named a. The second is a SyntaxError: if spells if, and keywords may not contain escapes.
How would you remove the accents from "Ångström" to get "Angstrom"?
Answer
"Ångström".normalize("NFD").replace(/\p{M}/gu, "")
NFD separates each accent into a combining mark, and the regex removes all marks.
Why does JavaScript allow the zero-width joiner in identifiers at all, given the risk?
Answer
Some writing systems, such as several Indic scripts, need joiner and non-joiner characters to spell certain words correctly. Banning them would make some languages impossible to use in identifiers. The risk is managed by tools and conventions rather than by the grammar.
Previous: JavaScript Lexical Structure: Case, Whitespace, Comments, Literals, Identifiers and Reserved Words
Next: JavaScript Semicolons: Automatic Semicolon Insertion Rules and Traps

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.