Course contentsShow
← JavaScript
Lesson 186 of 2,7235. StringsFree lesson

String Length and Surrogate Pairs

Understand why string.length counts code units, not characters, and how this affects emoji and special characters.

String Length and Surrogate Pairs

What you'll learn: Why JavaScript's string.length can give unexpected results with emoji and special characters.

The Problem with .length

JavaScript's string.length property counts code units, not actual visible characters. Since JavaScript uses UTF-16 encoding internally, each position in a string holds one 16-bit code unit.

For most everyday characters (letters, digits, punctuation), one character equals exactly one code unit, so .length works exactly as expected:

"hello".length; // 5 (five characters, five code units)

However, many emoji and special characters are stored using more than one code unit, leading to lengths that don't match what you see on the screen.

Surrogate Pairs

For Unicode code points beyond U+FFFF (like many modern emojis), JavaScript uses a surrogate pair. A surrogate pair is a high surrogate (a code unit from U+D800 to U+DBFF) followed by a low surrogate (from U+DC00 to U+DFFF). Together, these two code units represent a single character outside the Basic Multilingual Plane (BMP). Because there are two code units, .length counts them as 2:

"😀".length; // 2 (one emoji, but a surrogate pair of two code units!)

Multi-Code Unit Graphemes (The Heart Exception)

Not all 2-unit emojis are surrogate pairs. A classic example is the red heart (❤️). As commonly typed, ❤️ is formed by the code point U+2764 (Heavy Black Heart) followed by U+FE0F (VARIATION SELECTOR-16, which tells the system to render it as a colorful emoji).

These are two separate code units in the BMP forming a single visual character (a grapheme). This is not a surrogate pair. Still, because it consists of two distinct code units, its length is also 2:

"❤️".length; // 2 (U+2764 and U+FE0F, two BMP code units)
"I ❤️ JS".length; // 7 (I + space + ❤️ + space + J + S)

Why This Matters

This mismatch between what you see (one visual character) and what JavaScript counts (multiple code units) can cause bugs. If you try to slice strings or count characters for validation, you might accidentally split a surrogate pair or a variation selector sequence, resulting in broken or corrupted text.

Key Takeaway: string.length counts UTF-16 code units, not visible characters. Emojis beyond U+FFFF use surrogate pairs (a high surrogate U+D800–U+DBFF and low surrogate U+DC00–U+DFFF), while others like ❤️ use multiple BMP code units (U+2764 plus U+FE0F VARIATION SELECTOR-16). Both scenarios cause .length to return higher values than the number of visible characters.