charCodeAt vs codePointAt in JavaScript
Beginner ยท 4 min read
Computers don't store letters. They store numbers, and every character you see on screen has a number behind it. 'A' is 65, 'a' is 97, and a thumbs-up emoji has a number too. Reading those numbers is how you sort, encrypt or check characters at a low level, for example in a Caesar cipher or a "is this a digit?" test.
JavaScript has two methods for reading a character's number: charCodeAt and codePointAt. For ordinary letters they give the same answer. For emoji they don't, and only one of them tells the truth. In this tutorial you will use both, build strings back from numbers, and see exactly where they part ways. You only need to know what a string and its index are.
Characters as numbers
The list that matches every character to a number is called Unicode. The number for a character is called its code point. Here are a few:
'A' 65 'a' 97 '0' 48 '๐' 128077
Notice that the digit '0' is 48, not 0. The character and the number it looks like are different things.
Code units: how JavaScript stores the numbers
JavaScript stores a string as a list of small pieces called code units. Each code unit holds a number from 0 to 65535. That is enough for almost every letter in every alphabet, so most characters take one code unit.
But 128077 is bigger than 65535. A character like that doesn't fit, so JavaScript stores it as two code units, a pair that together mean one character. This is why '๐'.length is 2.
charCodeAt(i)reads one code unit.codePointAt(i)reads the whole character starting at positioni, even if it takes two code units.
Here is the exercise. Try it on your own first if you like, or read on and we will build it step by step.
4 Character codes, and the two ways to read them
easyFind the numeric code of a character and build a string back from codes. Then try it on an emoji and see which method tells the truth.
Stuck? Three hints, smallest first
- 1.
charCodeAtreturns one UTF-16 code unit;String.fromCharCodereverses it. - 2.
codePointAtreturns the whole character, even above 65535. - 3. An emoji is stored as two code units, so
charCodeAt(0)only sees the first half.
Step 1: read a letter's code
Write a small helper that gives the code of a character.
const codeOf = (c) => c.charCodeAt(0);
console.log(codeOf('A')); // 65
console.log(codeOf('a')); // 97
console.log(codeOf('a') - codeOf('A')); // 32
console.log(codeOf('0')); // 48
charCodeAt(0) reads the code at position 0, the first character. Lower case and upper case English letters are always 32 apart. That is a real fact, but it only holds for the 26 plain letters A to Z, so don't build upper-casing on it. toUpperCase exists for that.
Step 2: go back from numbers to text
String.fromCharCode does the reverse: give it numbers, it gives you a string.
console.log(String.fromCharCode(78, 71)); // 'NG'
78 is N and 71 is G. You can pass as many numbers as you like and they are joined into one string.
Step 3: ask past the end
What if there is no character at that position?
console.log('A'.charCodeAt(9)); // NaN
console.log('A'.charCodeAt(9) === NaN); // false
console.log(Number.isNaN('A'.charCodeAt(9))); // true
You get NaN, short for "Not a Number". It has an odd rule: NaN is never equal to anything, not even itself, so === NaN is always false. Use Number.isNaN to test for it.
Step 4: try an emoji
Now the interesting part. Ask both methods about the thumbs-up.
console.log('๐'.charCodeAt(0)); // 55357
console.log('๐'.codePointAt(0)); // 128077
charCodeAt(0) reads only the first of the two code units, so it gives 55357, which is half of the emoji. codePointAt(0) sees that this code unit is the start of a pair, reads both halves, and gives the real number, 128077.
Step 5: build the emoji back
The reverse methods follow the same split. String.fromCodePoint understands big numbers. String.fromCharCode doesn't.
console.log(String.fromCodePoint(128077) === '๐'); // true
console.log(String.fromCharCode(128077) === '๐'); // false
console.log(String.fromCharCode(55357, 56397) === '๐'); // true
fromCharCode only handles numbers up to 65535, so 128077 gets cut down and comes out as a different character. Give it the two halves separately, 55357 and 56397, and it puts the emoji back together.
Step 6: read the second half
Where does 56397 come from? It is the second code unit, at position 1.
console.log('๐'.codePointAt(1)); // 56397
console.log('๐'.charCodeAt(1)); // 56397
Starting at position 1, there is no pair to join, so both methods read the lone second half. codePointAt only gives the whole character when you point it at the start.
The full solution
Here is the complete answer: letter codes, building a string from codes, and both methods side by side on the emoji. Press Run, then read the checks for the emoji lines.
const codeOf = (c) => c.charCodeAt(0);
console.log("'A' is", codeOf('A'), " 'a' is", codeOf('a'), " gap:", codeOf('a') - codeOf('A'));
console.log('fromCharCode(78, 71) :', String.fromCharCode(78, 71));
console.log('--- an emoji is two code units ---');
console.log('charCodeAt(0) :', '๐'.charCodeAt(0), '<- the high half only');
console.log('codePointAt(0):', '๐'.codePointAt(0), '<- the whole character');
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.
test('A is 65', codeOf('A'), 65);
test('the gap between the cases is 32', codeOf('a') - codeOf('A'), 32);
test("the digit '0' is 48, not 0", codeOf('0'), 48);
test('fromCharCode builds a string from codes', String.fromCharCode(78, 71), 'NG');
test('charCodeAt past the end is NaN, so compare with Number.isNaN', Number.isNaN('A'.charCodeAt(9)), true);
test('for an emoji, charCodeAt sees only the first half', '๐'.charCodeAt(0), 55357);
test('codePointAt sees the whole thing', '๐'.codePointAt(0), 128077);
test('and fromCodePoint puts it back', String.fromCodePoint(128077), '๐');
test('fromCharCode cannot, because the number does not fit in 16 bits', String.fromCharCode(128077) === '๐', false);
test('though it can from both halves', String.fromCharCode(55357, 56397), '๐');
test('codePointAt(1) reads the SECOND half on its own', '๐'.codePointAt(1), 56397);
charCodeAt and codePointAt agree for every character below U+10000, which is all of Latin, Greek, Cyrillic and CJK. They part company on emoji and other astral characters, where charCodeAt(0) hands back a lone surrogate โ a number that is a valid code unit but not a valid character.
The 32 gap between 'A' and 'a' is a genuine ASCII fact, but do not build case conversion on it. It holds for the 26 unaccented Latin letters and nothing else.
Common mistakes
- Using
charCodeAton text that may contain emoji. It hands you half a character. UsecodePointAtandString.fromCodePoint. - Testing
code === NaN. That is alwaysfalse. UseNumber.isNaN(code). - Using the 32 gap to change case. It only works for A to Z.
'รฉ'and'ร'needtoUpperCase.
Try it yourself
- Write
isDigit(c)that returnstruewhenc.charCodeAt(0)is between 48 and 57. - Print the codes of every letter in
'Hi!'with a loop. - Use
String.fromCharCodeand a loop to build the string'ABCDE'from the numbers 65 to 69.