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

Accessing Characters with charAt vs Bracket Notation

Learn how charAt and bracket notation can return incomplete surrogate pairs instead of full characters.

Accessing Characters with charAt vs Bracket Notation

You'll learn why both charAt() and bracket notation can give you incomplete data when working with characters outside the Basic Multilingual Plane.

The Problem with Surrogate Pairs

Remember that some characters (like emoji or rare symbols) require two code units to represent one visual character. Both charAt() and bracket notation access strings by code unit position, not by full character.

When you use either method on a surrogate pair, you get just one half of the pair—an incomplete, invalid Unicode character that displays as a replacement symbol (�) or garbage.

Why Both Methods Fail the Same Way

const emoji = "😀";
console.log(emoji.length);       // 2 (two code units)

// Both methods access by code unit:
console.log(emoji.charAt(0));    // � (first half of pair)
console.log(emoji[0]);           // � (first half of pair)

console.log(emoji.charAt(1));    // � (second half of pair)
console.log(emoji[1]);           // � (second half of pair)

Think of it like this: A surrogate pair is like a two-piece puzzle. Both charAt() and bracket notation hand you just one piece at a time, which makes no sense on its own.

The Key Difference

The only practical difference: charAt() returns an empty string for out-of-bounds indices, while bracket notation returns undefined. For surrogate pairs, they fail identically.

Key Takeaway: Both charAt() and bracket notation operate at the code unit level, meaning they can split surrogate pairs and return incomplete characters. Neither is "safe" for Unicode characters outside the BMP.