Skip to content
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

Visual Character
𐐷
→
One Code Point
U+10437
UTF-16 Units
["\uD801", "\uDC37"]
Length: 2
Code Points
[0x10437]
Array.from(str).length: 1

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

  • 1
    Understanding that one visual character = one Code Point.
  • 2
    Realizing that one Code Point can require multiple Code Units.
  • 3
    Using iterators like 'for...of' which correctly yield code points.
  • 4
    Differentiating 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.