Strings and Unicode
The string methods you reach for daily, why strings are immutable, and the UTF-16 gotcha behind why `"😀".length` is `2`.
Strings and Unicode
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Strings are immutable — every method that looks like it's changing a string (`slice`, `toUpperCase`, `replace`, `trim`) actually returns a brand-new string and leaves the original untouched; there is no in-place string mutation in JavaScript.
- A JavaScript string's `.length` doesn't count characters the way a person would — it counts UTF-16 *code units*. Most text each character fits in one code unit, but emoji and other characters outside the Basic Multilingual Plane need two units (a surrogate pair), so `"😀".length` is `2`, not `1`.
- That mismatch is why naive index-by-index iteration (`for (let i = 0; i < str.length; i++)`) can split a surrogate pair in half and produce garbage, while `for...of` and the spread operator (`[...str]`) iterate by *code point* instead, handling multi-unit characters correctly without any extra work.
- `.normalize()` matters because Unicode can represent the same visible character more than one way — an accented letter as one combined code point, or as a plain letter plus a separate combining accent mark — and those two representations don't compare equal with `===` until you normalize both to the same form.
- A small set of core methods — `slice`, `split`, `includes`, `padStart`/`padEnd`, `trim`, `replace` — covers the overwhelming majority of real string work; reach for `Intl.Segmenter` instead of hand-rolled logic the moment you need to count what a human would actually call "one character".
Strings don’t change — they get replaced
Before the Unicode gotchas, one property of strings is worth nailing down
because it quietly affects everything else in this lesson: strings are
immutable. slice, trim, toUpperCase, replace, split — none of
them modify the string they’re called on. Each one computes and returns a
new string, and the original is untouched.
const greeting = "hello";
greeting.toUpperCase(); // "HELLO" — but this value is thrown away
console.log(greeting); // still "hello"
const shouted = greeting.toUpperCase(); // now you've kept it
This is the same immutability numbers and booleans have, just easier to
forget with strings because method-call syntax (str.toUpperCase()) looks
exactly like the mutating methods arrays have (arr.push()). There’s no
str.toUpperCaseInPlace() lurking anywhere — if a string method’s return
value isn’t captured, the call did nothing useful.
The methods you’ll actually reach for
A handful of string methods cover nearly everything you do with text day to day, and it’s worth knowing them as a set rather than discovering each one the first time you need it:
slice(start, end)— pull out a substring by position, negative indices count from the end.split(separator)— break a string into an array on a delimiter.includes,startsWith,endsWith— substring checks that read better thanindexOf(...) !== -1.padStart/padEnd— pad a string to a target length, handy for aligning output or zero-filling ("7".padStart(2, "0")→"07").trim— strip leading/trailing whitespace.replace/replaceAll— substitute a match (string or regex) with something else.
This is a survey, not the full API — the goal is recognizing the shape of
the problem each one solves, so you reach for the right tool instead of
reinventing padStart with a loop.
Where .length stops matching intuition
Here’s where strings get genuinely tricky. JavaScript strings are
sequences of UTF-16 code units, and .length counts code units — not
“characters” the way you’d count them by eye. For almost all the text
you’ll ever type, one character is one code unit, and the distinction never
surfaces. It surfaces hard the moment you touch emoji, or any character
outside Unicode’s Basic Multilingual Plane (BMP):
"a".length; // 1 — fits in one code unit, no surprise
"😀".length; // 2 — needs a surrogate pair: two code units for one emoji
😀’s real Unicode code point is too large to fit in 16 bits, so UTF-16
encodes it as a surrogate pair — two 16-bit code units that are only
meaningful read together. .length doesn’t know or care about that
pairing; it just counts units, so one visible emoji reports as 2.
This is exactly the trap the embedded talk walks through — it opens with
the real example of '👩🏿🎤'.length being 7, not 1, and works through
why, covering how JavaScript actually stores text internally and where
UTF-8 and UTF-16 diverge. Seeing the explanation built from that one
startling number is more convincing than being told the rule abstractly.
Why naive iteration breaks, and for...of doesn’t
The practical danger isn’t .length by itself — it’s code that walks a
string one index at a time, assuming each step lands on one character:
const emoji = "😀";
for (let i = 0; i < emoji.length; i++) {
console.log(emoji[i]); // two lines of mangled, unpaired surrogate halves
}
for (const char of emoji) {
console.log(char); // one line: 😀
}
Indexed access (str[i]) and the classic for loop both step one UTF-16
code unit at a time — Unicode-blind. Hit a surrogate pair mid-stride and
you’ll split it, producing two meaningless lone surrogates instead of one
emoji. for...of, and the spread operator ([...str]), iterate by code
point instead — they’re Unicode-aware, and they treat a surrogate pair as
the single character it actually represents. That’s the whole fix, and
it’s free: prefer for...of or spreading over index-based loops whenever
you’re walking text that might contain anything outside plain ASCII.
Code points aren’t even the final word, though — some single visible
emoji (a family, a flag, certain skin-tone variants) are several code
points stitched together with zero-width joiners, so code-point iteration
can still overcount what a person would call “one character.” When that
distinction actually matters — a character counter, a text-truncation
feature — Intl.Segmenter operates on grapheme clusters, the real
human-perceived unit, and is the tool built for exactly that job.
.normalize(): the same text, two different byte sequences
One more Unicode wrinkle worth knowing: Unicode sometimes offers more than
one way to encode the same visible text. An accented character like é can
be a single precomposed code point, or a plain e followed by a separate
combining accent mark layered on top. Both render identically on screen,
but they’re different sequences underneath, so === sees them as
different strings:
const precomposed = "café"; // é as one code point
const decomposed = "café"; // e + combining accent
precomposed === decomposed; // false — looks identical, isn't
precomposed.normalize() === decomposed.normalize(); // true
.normalize() converts a string to a consistent representation, so two
strings that look the same but were built differently — say, one typed
on a keyboard and one pasted from somewhere that encoded it differently —
actually compare equal. Any time you’re comparing or deduplicating
user-entered text, normalizing first is cheap insurance against this.
Where this fits
This lesson builds directly on values, types, and coercion —
a string is one of the primitive types introduced there, and everything
here is what that primitive actually looks like under load. It also sets
up regular expressions next,
where the same code-unit-versus-code-point distinction resurfaces as the
u flag — a regex without it matches code units, the same trap as index-
based string iteration, just wearing a different syntax.
Check yourself
If `str.toUpperCase()` doesn't change `str` in place, what is it actually doing, and how do you "keep" the result?
It builds and returns a brand-new string in uppercase form, leaving the original `str` exactly as it was. Strings are immutable in JavaScript, so every string method that appears to transform a string is really just computing a new one — to keep the result you have to capture it, usually by reassigning: `str = str.toUpperCase();`.
Why does `"😀".length` return `2` instead of `1`?
JavaScript strings are sequences of UTF-16 code units, and `.length` counts those units, not human-perceived characters. Most characters fit in a single 16-bit code unit, but 😀 sits outside the Basic Multilingual Plane, so it's encoded as a *surrogate pair* — two 16-bit code units that only make sense together. `.length` counts both units, giving `2` for one visible emoji.
Why does looping over a string with `for (let i = 0; i < str.length; i++) { console.log(str[i]); }` produce broken output on a string containing an emoji, while `for (const char of str) { console.log(char); }` doesn't?
Index-based access and the classic `for` loop step one UTF-16 code unit at a time, so on an emoji's surrogate pair it can print each half separately — two meaningless, unpaired code units instead of one emoji. `for...of` (and the spread operator) iterate the string by *code point*, which is Unicode-aware: it treats a surrogate pair as the single character it represents, so each loop iteration gives you one real, complete character.
Two strings both display as "café" on screen but `str1 === str2` is `false`. What's the most likely cause, and how do you fix it?
Unicode can represent the accented é two different ways: as a single precomposed code point, or as a plain `e` followed by a separate combining-accent code point. Both render identically but are different sequences of code units underneath, so a strict comparison sees them as different strings. Calling `.normalize()` on both (to the same normalization form) converts them to a consistent representation before comparing.
You need to count how many "characters" a user sees in a string that might contain multi-codepoint emoji (like a flag or a family emoji built from several combined codepoints). Why might even `[...str].length` give a count a person would disagree with, and what handles it correctly?
`[...str]` iterates by code point, which fixes the surrogate-pair problem but not the next layer: some visibly single emoji are actually *several* code points joined by zero-width joiners (a family emoji, a flag), so code-point iteration still overcounts them as multiple characters. `Intl.Segmenter` operates on grapheme clusters — the actual unit a person perceives as "one character" — and is the correct tool when that distinction matters.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.