Strings
A JavaScript string is an immutable sequence of UTF-16 code units. Every method that looks like it edits a string actually returns a new one, and length counts code units rather than characters.
Detailed Explanation
Treat a string as a read-only array of 16-bit numbers and most of its behaviour follows. You cannot change a character in place. "hello"[0] = "H" does nothing in sloppy mode and throws a TypeError in strict mode, which includes all ES modules and class bodies. Methods such as toUpperCase, slice, replace, and trim all return fresh strings and leave the original alone.
Immutability is a deliberate trade. It makes strings safe to share, cheap to compare by identity when the engine interns them, and safe as object keys. The cost is that heavy editing allocates. In Java you reach for StringBuilder for this reason. In JavaScript you usually do not need to: V8 represents a + b as a rope (a small node pointing at both halves) and only flattens it into contiguous memory when something reads the characters. So result += chunk in a loop is O(1) per append, with one O(n) flatten later. Building an array of pieces and calling join("") is still marginally more predictable for very large outputs.
The part that causes real bugs is Unicode. JavaScript strings are UTF-16, and there are three different things you might mean by "character".
- A code unit is one 16-bit slot.
length,charCodeAt, and bracket indexing work in code units. - A code point is one Unicode scalar value. Anything above U+FFFF is stored as a surrogate pair: two code units.
for...of, spread, andcodePointAtwork in code points. - A grapheme cluster is what a reader calls a character. An emoji with a skin-tone modifier, a flag, or
eplus a combining accent is one grapheme built from several code points.
So "👍".length is 2, [..."👍"].length is 1, and both are correct answers to different questions. "👨👩👧".length is 8, because it is three emoji joined by two zero-width joiners. Slicing at a code-unit boundary can split a surrogate pair and produce an unpaired half that renders as a replacement box.
Two standard tools handle the rest. normalize() fixes the case where the same visible text has two encodings: "é" can be one code point (NFC) or e plus a combining acute (NFD). They are not === equal, so normalise both sides before comparing user input. Intl.Segmenter with granularity: "grapheme" gives correct per-character iteration, and is the right way to truncate text or count characters for a UI limit.
Cost of the main operations
| Operation | Cost |
|---|---|
s[i], charCodeAt(i) | O(1) once flattened |
s1 + s2 | O(1) amortised (rope), O(n) on first read |
slice, substring | O(n) worst case, O(1) when the engine shares a slice |
indexOf, includes, replace | O(n) typical, O(n × m) worst |
=== comparison | O(n), O(1) if both are interned |
[...s], for...of | O(n) |
For sorting human-readable text, === and < compare code units, so "Z" < "a" is true and accented letters sort after z. Use localeCompare or Intl.Collator instead.
Code Examples
Three different notions of "length" for the same visible text.
// Three different notions of "length" for the same visible text.
const thumb = "👍"; // U+1F44D, stored as the surrogate pair D83D DC4D
console.log(thumb.length); // => 2 code units
console.log([...thumb].length); // => 1 code points (for...of / spread)
console.log(thumb.charCodeAt(0)); // => 55357 just the high surrogate
console.log(thumb.codePointAt(0)); // => 128077 the whole code point
const family = "👨👩👧"; // three emoji joined by zero-width joiners
console.log(family.length, [...family].length); // => 8 5
// Grapheme clusters: what a reader counts as one character.
const seg = new Intl.Segmenter("en", { granularity: "grapheme" });
console.log([...seg.segment(family)].length); // => 1
// Slicing by code unit can cut a surrogate pair in half.
console.log(thumb.slice(0, 1) === "\uD83D"); // => true an unpaired surrogate"use strict"; // ES modules and class bodies are strict already
// The same text, two encodings. Normalise before comparing user input.
const composed = "café"; // "é" is one code point, U+00E9
const decomposed = "cafe\u0301"; // "e" plus a combining acute accent
console.log(composed.length, decomposed.length); // => 4 5
console.log(composed === decomposed); // => false
console.log(composed.normalize("NFC") === decomposed.normalize("NFC")); // => true
// Strings are immutable: index assignment throws under strict mode.
const label = "hello";
try {
label[0] = "H";
} catch (err) {
console.log(err.constructor.name); // => TypeError
}
console.log(label.toUpperCase(), label); // => HELLO hello original unchanged
// Code-unit order is not alphabetical order.
console.log(["apple", "Banana", "Äpfel"].sort()); // => [ 'Banana', 'apple', 'Äpfel' ]
console.log(["apple", "Banana", "Äpfel"].sort((a, b) => a.localeCompare(b, "de")));
// => [ 'Äpfel', 'apple', 'Banana' ] "Ä" collates as "A" in GermanCommon Gotchas
`length` is not character count
it counts UTF-16 code units, so any emoji or non-BMP character inflates it. Validating a 20-character limit with `length` rejects valid input. Count with `Intl.Segmenter`.
Index assignment throws in strict mode
`s[0] = "H"` raises `TypeError: Cannot assign to read only property '0'`. Build a new string with `slice` and concatenation.
Visually identical strings can be unequal
NFC and NFD encodings of the same accented text are not `===`. Call `normalize()` on both sides, especially for names and passwords.
`new String("x")` is an object
the wrapper has `typeof "object"` and is never `===` to the primitive. Never use it; the primitive already has all the methods.