Basics
Code Units vs Code Points
Understanding the difference between storage units and character identities.
Time Complexity
O(1)
Space Complexity
O(1)
Interactive Visualization
Technical Guide
A Code Point is the 'numerical identity' of a character in Unicode (e.g., U+1F680). A Code Unit is the 'storage chunk' used by an encoding (e.g., two 16-bit units in UTF-16). Most beginners use '.length', which measures code units. To correctly count characters, you must count code points.
Logical Phases
- 1Understanding that one visual character = one Code Point.
- 2Realizing that one Code Point can require multiple Code Units.
- 3Using iterators like 'for...of' which correctly yield code points.
- 4Differentiating between byte-size, unit-size, and character-count.
Implementation
const s = '𐐷';
[...s].length; // 1 (Code Points)
s.length; // 2 (Code Units)Expert Pitfalls
Looping through a string with a standard 'for(i)' loop and breaking surrogate pairs.