JavaScript Unicode Code Points and Grapheme Clusters
Quick answer
A code point is a Unicode number; a grapheme cluster is a text segmentation unit approximating a user-perceived character. UTF-16 code units are different from both.
How it works
String iteration ([...text]) follows code points, combining valid surrogate pairs but leaving combining marks separate. Intl.Segmenter with granularity grapheme can segment clusters; the exact rules depend on the implementation Unicode data. String.fromCodePoint builds strings from valid code point numbers; fromCharCode builds from 16-bit units.
const text = "é😀";console.log(text.length, [...text].length);Expected output in Node.js:
4 3The combining mark is one unit and code point; emoji uses two units but one code point.
const text = "é😀";const parts = [...new Intl.Segmenter("en", {granularity:"grapheme"}).segment(text)];console.log(parts.length, String.fromCodePoint(0x1F600));Expected output in Node.js:
2 😀The base-plus-mark and emoji are two grapheme clusters in this runtime.
Common mistakes
Counting with spread is not a grapheme count. Do not truncate user-facing text by arbitrary code-unit boundaries.
Practice
Count units, code points and graphemes in Persian text containing combining marks and in emoji; record the runtime.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Unicode Code Points and Grapheme Clusters — Knowledge Check
Apply the taught concept and predict the output.
Which representation is used by JavaScript string length?
Which operation can produce grapheme segments?
What does String.fromCodePoint require from each numeric argument?
What is the exact console output in JavaScript Unicode Code Points and Grapheme Clusters example 1?
const text = "é😀";console.log(text.length, [...text].length);What is the exact console output in JavaScript Unicode Code Points and Grapheme Clusters example 2?
const text = "é😀";const parts = [...new Intl.Segmenter("en", {granularity:"grapheme"}).segment(text)];console.log(parts.length, String.fromCodePoint(0x1F600));