JavaScript String Indexing and UTF-16 Code Units
Quick answer
String indices select UTF-16 code units. A visible character can occupy several units, so the length property is not a count of displayed characters.
How it works
Use text[i] for an indexed unit, charAt(i) for a unit or an empty string, and at(i) for a unit with negative indexing. charCodeAt(i) returns the numeric unit or NaN outside the string; codePointAt(i) returns a code point beginning at a valid index or undefined outside. A trailing surrogate alone is returned as its unit value. Strings are immutable.
const text = "plan";console.log(text.at(-1), text.charAt(8) === "");Expected output in Node.js:
n trueThe relative index selects the last unit; charAt returns an empty string outside the range.
const text = "A😀";console.log(text.length, text.codePointAt(1));Expected output in Node.js:
3 128512A occupies one unit and the emoji occupies two; index 1 starts its code point.
Common mistakes
Do not use text[-1] for the last unit. It looks up a property named -1, rather than using relative indexing.
Practice
Compare the length and first code point of a single supplementary-plane character.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript String Indexing and UTF-16 Code Units — Knowledge Check
Apply the taught concept and predict the output.
Which String member reads a unit at a negative relative index?
What does charCodeAt return for an out-of-range index?
What does codePointAt return outside the string?
What is the exact console output in JavaScript String Indexing and UTF-16 Code Units example 1?
const text = "plan";console.log(text.at(-1), text.charAt(8) === "");What is the exact console output in JavaScript String Indexing and UTF-16 Code Units example 2?
const text = "A😀";console.log(text.length, text.codePointAt(1));