Emmanuel Akinfulubi

JavaScriptString

Code units vs code points in JavaScript strings

Intermediate Β· 4 min read

Type 'πŸ‘'.length into a JavaScript console and you get 2, not 1. It looks like a bug. It isn't: it is how JavaScript stores text, and once you see why, a whole family of string surprises makes sense, from broken emoji to character limits that reject a message that is clearly short enough.

In this tutorial you will measure the same text two ways, find which string tools count one way and which count the other, and learn the safe way to count and cut text people actually type. You only need to know what length, slice and square-bracket indexing do on a string.

Code units: the pieces a string is made of

Every character has a number in Unicode, the big list of all the world's characters. That number is called a code point. A is 65, Γ© is 233, and the thumbs-up πŸ‘ is 128077.

JavaScript doesn't store code points directly. It stores text as a list of 16-bit pieces called code units. One code unit can hold a number up to 65535. That covers ordinary letters, most accented letters and most of the world's alphabets, so for them one character is one code unit.

128077 is too big for one piece. So πŸ‘ is stored as two code units, a pair that only makes sense together. That pair is called a surrogate pair. Most emoji, and some rare letters, work this way.

Two ways to count

  • length, slice, charAt, charCodeAt, split('') and text[0] all work in code units.
  • Spread ([...text]), Array.from, for...of and codePointAt work in code points, so a surrogate pair stays together.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

43 Code units against code points

fair

Show that 'πŸ‘'.length is 2, and work out which operations on a string are counting the wrong thing because of it.

Stuck? Three hints, smallest first
  1. 1. A JavaScript string is a sequence of UTF-16 code units, and length counts those.
  2. 2. Anything above U+FFFF needs two units, called a surrogate pair.
  3. 3. Spread, Array.from and for...of all iterate code points instead.

Step 1: count the thumbs-up both ways

Step 1

const thumbsUp = 'πŸ‘';
console.log(thumbsUp.length);      // 2
console.log([...thumbsUp].length); // 1

length counts the two code units. Spreading the string into an array walks it by code point, so the array holds one item: the whole emoji.

Step 2: look at the number behind it

Step 2

const thumbsUp = 'πŸ‘';
console.log(thumbsUp.codePointAt(0)); // 128077
console.log(thumbsUp.charCodeAt(0));  // 55357

codePointAt(0) reads the full code point, 128077. charCodeAt(0) reads only the first code unit, 55357, which is the first half of the pair. On its own that number isn't a character at all.

Step 3: indexing gives you half a character

Step 3

const thumbsUp = 'πŸ‘';
console.log(thumbsUp[0] === thumbsUp);          // false
console.log(thumbsUp[0].length);                // 1
console.log(thumbsUp.slice(0, 1) === thumbsUp); // false

thumbsUp[0] and slice(0, 1) both take one code unit, half the emoji. If that half ends up on screen, it shows as a broken box or a question mark. Once it is saved somewhere it usually can't be repaired.

Step 4: the safe way to take characters

Step 4

const thumbsUp = 'πŸ‘';
console.log([...thumbsUp].join('') === thumbsUp); // true

Spread the string, work on the array, then join('') it back. Because the array holds whole code points, nothing is ever cut in half.

Step 5: a mixed string

Real text mixes ordinary letters and emoji:

Step 5

const mixed = 'Lagos πŸ‘';
console.log(mixed.length);      // 8
console.log([...mixed].length); // 7

A reader sees seven characters: five letters, a space and the emoji. length says 8, because the emoji counts twice.

This is where it costs you. Imagine a 7-character limit checked with length. The user sees seven characters and the check says eight, so the message is rejected. A limit should be measured in the unit you meant:

JavaScript

const mixed = 'Lagos πŸ‘';
console.log([...mixed].slice(0, 7).join('') === mixed); // true
console.log(mixed.slice(0, 7) === mixed);               // false

Slicing the array keeps the whole emoji. Slicing the string at 7 code units stops in the middle of it.

Step 6: code points are still not the end

Spreading fixes emoji like πŸ‘, but some things a reader sees as one character are several code points. An e followed by a separate accent mark is two code points that display as Γ©. Exercise 44 deals with that, using normalize.

The full solution

The panel prints the thumbs-up's length, its code-point count, its first half and the two counts for 'Lagos πŸ‘'. Press Run and compare the numbers, then read the checks underneath.

The answer

const thumbsUp = 'πŸ‘';
const mixed = 'Lagos πŸ‘';

console.log('thumbsUp.length     :', thumbsUp.length, '<- code units');
console.log('[...thumbsUp].length:', [...thumbsUp].length, '<- code points');
console.log('thumbsUp[0]         :', JSON.stringify(thumbsUp[0]), '<- half a character');
console.log('mixed.length        :', mixed.length, ' by code point:', [...mixed].length);

Output


      
11 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 11 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

11 checks

test('a thumbs-up is one character but length 2', thumbsUp.length, 2);
test('because length counts UTF-16 code units', [...thumbsUp].length, 1);
test('its code point is above the 16-bit range', thumbsUp.codePointAt(0), 128077);
test('so charCodeAt and codePointAt disagree', thumbsUp.charCodeAt(0) !== thumbsUp.codePointAt(0), true);
test('indexing gives you half a character', thumbsUp[0] === thumbsUp, false);
test('and that half is one code unit long', thumbsUp[0].length, 1);
test('slice(0, 1) cuts it in half too', thumbsUp.slice(0, 1) === thumbsUp, false);
test('while spreading and re-joining is safe', [...thumbsUp].join(''), thumbsUp);
test('a mixed string over-counts with length', mixed.length, 8);
test('and counts correctly by code point', [...mixed].length, 7);
test('so a length limit has to be measured in the unit you meant', [...mixed].slice(0, 7).join(''), 'Lagos πŸ‘');

This one fact explains most of the surprises in this section. length, charAt, charCodeAt, slice, substring, split('') and array index access all work in code units. for...of, spread, Array.from, codePointAt and matchAll work in code points.

Where it actually costs money: a 140-character limit enforced with length rejects text a user can see is short enough, and a slice at a fixed offset can end a string with half a surrogate pair, which serialises to a replacement character and cannot be recovered.

Code points are still not characters. 'e' + U+0301 is two code points and one letter, which is exercise 44.

Common mistakes

  • Using length for a character limit. Emoji count twice. Count [...text].length when the limit is about what people see.
  • Cutting with slice at a fixed position. It can split an emoji in half. Spread first, slice the array, then join.
  • Reading charCodeAt as the character's number. For emoji it gives only half. Use codePointAt.

Try it yourself

  1. Write visibleLength(text) that returns [...text].length, and try it on 'hi πŸ‘‹πŸ½'. Is the answer what you see?
  2. Write firstChars(text, n) that returns the first n code points, and check it never breaks 'πŸ‘πŸ‘πŸ‘'.
  3. Loop over 'aπŸ‘b' with for...of and print codePointAt(0) for each character.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.