What is Unicode? — Universal Character Encoding Explained

What is Unicode? — Universal Character Encoding Explained

Definition

Unicode is a standard that assigns a number, called a code point, to every character in every writing system, along with symbols and emoji. Unicode itself is only the numbering. Encodings such as UTF-8 and UTF-16 turn those code points into bytes, and most bugs come from confusing the two.

Unicode is maintained by the Unicode Consortium. Version 16.0 defines over 154,000 characters.

Code points and UTF-8 bytes

ASCII is the first 128 Unicode code points, so UTF-8 encodes ASCII text in one byte per character. Other characters take two to four bytes. This script prints the code point and the UTF-8 bytes for four characters, then covers the other sections below. It needs Node.js 18 or later and nothing else. Save it as unicode.mjs and run node unicode.mjs.

const hex = (n) => "U+" + n.toString(16).toUpperCase().padStart(4, "0");
const utf8 = (s) =>
  [...new TextEncoder().encode(s)].map((b) => b.toString(16).toUpperCase().padStart(2, "0")).join(" ");
 
console.log("== code points and UTF-8 bytes");
for (const ch of ["A", "€", "中", "😀"]) {
  console.log(ch, hex(ch.codePointAt(0)), "->", utf8(ch));
}
 
console.log("\n== UTF-16 code units");
const emoji = "😀";
console.log("length:", emoji.length, "units:", emoji.charCodeAt(0).toString(16), emoji.charCodeAt(1).toString(16));
 
console.log("\n== characters vs bytes");
const word = "Hëllö";
console.log("length:", word.length, "UTF-8 bytes:", new TextEncoder().encode(word).length);
 
console.log("\n== normalization");
const composed = "café".normalize("NFC");
const decomposed = "café".normalize("NFD");
console.log("lengths:", composed.length, decomposed.length);
console.log("equal as stored:", composed === decomposed);
console.log("equal after NFC:", composed === decomposed.normalize("NFC"));
const index = new Map([[composed, "found"]]);
console.log("lookup with decomposed key:", index.get(decomposed));
 
console.log("\n== grapheme clusters");
const seg = new Intl.Segmenter("en", { granularity: "grapheme" });
for (const s of ["👨‍💻", "🇺🇸", "é"]) {
  console.log(s, "code points:", [...s].length, "units:", s.length, "graphemes:", [...seg.segment(s)].length);
}
 
console.log("\n== BOM");
const withBom = "" + '{"a":1}';
console.log("BOM bytes:", utf8(""));
try {
  JSON.parse(withBom);
  console.log("JSON.parse: ok");
} catch (err) {
  console.log("JSON.parse:", err.name);
}
console.log("TextDecoder default:", JSON.stringify(new TextDecoder().decode(new Uint8Array([0xef, 0xbb, 0xbf, 0x7b, 0x7d]))));
 
console.log("\n== lone surrogate");
console.log("bytes:", utf8("\uD83D"));
 
console.log("\n== case mapping");
console.log('"straße".toUpperCase():', "straße".toUpperCase());

Output:

== code points and UTF-8 bytes
A U+0041 -> 41
€ U+20AC -> E2 82 AC
中 U+4E2D -> E4 B8 AD
😀 U+1F600 -> F0 9F 98 80
 
== UTF-16 code units
length: 2 units: d83d de00
 
== characters vs bytes
length: 5 UTF-8 bytes: 7
 
== normalization
lengths: 4 5
equal as stored: false
equal after NFC: true
lookup with decomposed key: undefined
 
== grapheme clusters
👨‍💻 code points: 3 units: 5 graphemes: 1
🇺🇸 code points: 2 units: 4 graphemes: 1
é code points: 1 units: 1 graphemes: 1
 
== BOM
BOM bytes: EF BB BF
JSON.parse: SyntaxError
TextDecoder default: "{}"
 
== lone surrogate
bytes: EF BF BD
 
== case mapping
"straße".toUpperCase(): STRASSE

Each line matches the Unicode tables: A is U+0041 and one byte, € is U+20AC and three bytes, 中 is U+4E2D and three bytes, and the grinning face is U+1F600 and four bytes.

UTF-16 and surrogate pairs

JavaScript strings are UTF-16 code units. Characters above U+FFFF take two units, called a surrogate pair. The grinning face is U+1F600, so its units are D83D and DE00. That is why the grinning face has a length of 2, not 1. The surrogate range U+D800 to U+DFFF has no characters of its own, so a lone surrogate is not a valid character.

Characters are not bytes

The byte count of a string depends on its encoding and on how many code points need more than one byte. In the output, Hëllö has 5 characters and 7 UTF-8 bytes. Never size a database column by string.length.

Normalization

The same visible text can be stored as different code points. é is one code point (U+00E9) in NFC, or e followed by the combining accent U+0301 in NFD. The output shows the two forms compare unequal until both are normalized to NFC.

Grapheme clusters

A user sees one "character" where Unicode uses several code points. A family or profession emoji joins people with the zero width joiner U+200D. A flag is two regional indicator symbols. Intl.Segmenter counts what a user sees.

BOM

The byte order mark is U+FEFF. In UTF-8 it is the three bytes EF BB BF. Some Windows editors add it, and some parsers reject it. TextDecoder removes it by default, while JSON.parse on a string that starts with it throws.

Mistakes and before/after

1. Using string length as a byte count

Before:

const name = "Hëllö";
const bytes = name.length; // 5

After:

const bytes = new TextEncoder().encode(name).length; // 7

2. Comparing strings without normalizing

Before: a lookup built from NFC text misses the same word typed in NFD. The output shows lookup with decomposed key: undefined.

After: normalize every string to NFC on the way in, and again before comparing:

const key = input.normalize("NFC");

3. Counting emoji as one JavaScript character

Before: the family emoji (man, zero width joiner, laptop) has a length of 5, and slicing it at 4 cuts the emoji in half, leaving a lone surrogate at the end.

After: count or cut by grapheme, using Intl.Segmenter, as the grapheme section above does. The segmenter reports 1 grapheme for the same string.

4. Parsing JSON with a BOM

Before: JSON.parse("{\"a\":1}") throws SyntaxError. The file was saved by an editor that wrote a BOM.

After: decode the bytes with TextDecoder (the default strips the BOM), or remove the first character before parsing.

5. Replacing a lone surrogate silently

Before: new TextEncoder().encode("\uD83D") does not fail. It produces EF BF BD, the replacement character, so the original value is lost without an error.

After: check for a lone surrogate before encoding, if the data must round-trip.

6. Case-changing a string and expecting the same length

Before: "straße".toUpperCase() gives STRASSE, which is one character longer, so a length check on the uppercased text fails.

After: compare with a locale-aware collator that ignores case and accents: "straße".localeCompare("STRASSE", "en", { sensitivity: "base" }) === 0 is true.

LangStop encoding tools