charAt vs codePointAt in JavaScript

JavaScript provides different methods to inspect individual characters in a string, with String.prototype.charAt() and String.prototype.codePointAt() being two primary options. While charAt() returns a single 16-bit string character at a given index, codePointAt() returns the numeric Unicode code point value of the character at that position. Understanding the difference is crucial when handling modern text, especially non-ASCII characters, symbols, and emojis that span across surrogate pairs in UTF-16 encoding.


What is String.prototype.charAt()?

The charAt() method takes an index and returns the character located at that specific UTF-16 code unit as a new string.

const text = "Hello";
console.log(text.charAt(1)); // "e"

const emoji = "🦊";
console.log(emoji.charAt(0)); // "\uD83E" (High surrogate, rendered as an unreadable character)

What is String.prototype.codePointAt()?

Introduced in ECMAScript 2015 (ES6), codePointAt() resolves the surrogate pair limitation. Instead of returning a string character unit, it returns the complete decimal Unicode code point integer for the character.

const text = "Hello";
console.log(text.codePointAt(1)); // 101 (Unicode for "e")

const emoji = "🦊";
console.log(emoji.codePointAt(0)); // 129418 (Complete Unicode code point for the fox emoji)

Key Differences

Feature charAt() codePointAt()
Return Type String Number (Integer)
Return Value The character at the 16-bit unit The Unicode code point number
Surrogate Pair Support No (splits 4-byte characters) Yes (reads full multi-byte code points)
Out-of-Bounds Result "" (Empty string) undefined
JavaScript Version ECMAScript 1 (Legacy) ECMAScript 2015 (ES6)

When to Use Which