Code Points vs Code Units
In this lesson, you'll learn the crucial difference between Unicode code points (the characters you see) and UTF-16 code units (how JavaScript stores them internally).
What's the Difference?
Think of code points as the actual characters in Unicode's master list. Each character—whether it's "A", "😀", or "中"—has a unique code point number.
Think of code units as the storage boxes JavaScript uses to hold these characters. JavaScript uses UTF-16 encoding, which means it uses 16-bit boxes (code units) to store characters.
The Simple Case
For most common characters (like letters, numbers, basic punctuation), one code point fits perfectly into one code unit:
- "A" = 1 code point = 1 code unit
- "5" = 1 code point = 1 code unit
The Tricky Case
Here's where it gets interesting: some characters (like emojis and rare symbols) have code points that are too big for a single 16-bit box. JavaScript needs two code units (called a "surrogate pair") to store one code point.
- "😀" = 1 code point (one character you see)
- "😀" = 2 code units (two 16-bit boxes in memory)
This is why the .length property can be confusing—it counts code units, not the characters you actually see!
Why This Matters
Many string methods count code units, not code points. Understanding this distinction helps you avoid bugs when working with emojis, rare characters, or international text.
Key Takeaway: Code points are the Unicode characters themselves; code units are JavaScript's 16-bit storage slots. One character (code point) may require two code units.