CodePointAt and CharCodeAt
You'll learn: How to extract numeric Unicode values from strings using codePointAt() and charCodeAt(), and why the difference matters for characters beyond the Basic Multilingual Plane.
The Core Difference
Both methods give you numeric codes for characters in a string, but they work at different levels:
charCodeAt(index)returns a code unit (a 16-bit value between 0 and 65535). For characters outside the BMP, it only returns half the surrogate pair.codePointAt(index)returns the full code point (a value that can exceed 65535), correctly handling surrogate pairs.
Think of it like measuring height: charCodeAt() measures in feet only, while codePointAt() measures in feet and inches—giving you the complete picture.
How They Work
const text = 'A😀B';
// 'A' is in the BMP (U+0041)
text.charCodeAt(0); // 65
text.codePointAt(0); // 65 (same result)
// '😀' requires a surrogate pair
text.charCodeAt(1); // 55357 (only the high surrogate!)
text.codePointAt(1); // 128512 (the full emoji code point)
// 'B' follows the emoji
text.charCodeAt(3); // 66
text.codePointAt(3); // 66
For BMP characters like 'A', both methods return identical values. For non-BMP characters like emojis, charCodeAt() breaks down and returns only part of the surrogate pair, while codePointAt() correctly returns the complete Unicode code point.
When to Use Which
Use codePointAt() when working with modern text that might contain emojis, rare symbols, or characters from supplementary Unicode planes. Use charCodeAt() only if you specifically need code unit values or you're certain your text is BMP-only.
Key Takeaway: codePointAt() returns full Unicode code points and handles all characters correctly, while charCodeAt() returns 16-bit code units and fails for characters beyond the BMP—always prefer codePointAt() for reliable Unicode handling.