JavaScript Strings: Literals, Escape Sequences and UTF-16 Code Units
Everything about writing and reading strings: single, double and backtick quotes, multi-line strings, every escape sequence, why length counts UTF-16 code units, indexing with [] and at(), surrogate pairs and emoji, well-formed strings, and how string comparison really works.
kvi5hnuCode Sprout team member7 min readOn this page
Strings hold text: names, messages, JSON, HTML, file contents. A JavaScript string is an immutable, ordered sequence of 16-bit values called UTF-16 code units. That one sentence explains most string behavior, including the confusing parts: why an emoji has length 2, why s[0] can return half a character, and why "Z" < "a".
This article covers writing strings and their internal model. Article 15 covers the string methods, and article 16 covers template literals.
Three kinds of quotes
const single = 'Hello';
const double = "Hello";
const backtick = `Hello`;
console.log(single === double && double === backtick); // all the same string
console.log("It's easy"); // apostrophe inside double quotes
console.log('She said "yes"'); // double quotes inside single quotes
console.log(`Both 'kinds' and "kinds"`); // anything inside backticks
console.log(""); // the empty string has length 0
console.log("".length);
true
It's easy
She said "yes"
Both 'kinds' and "kinds"
0
Single and double quotes are completely equivalent. Pick one style for a project (Prettier defaults to double quotes; many style guides prefer single) and let the formatter enforce it. Backticks create template literals, which add ${expression} interpolation, real multi-line text and tagging; article 16 covers them.
There's no separate character type. A "character" is just a string of length 1.
Multi-line strings
Ordinary quotes can't contain a raw line break. You have three options:
const escaped = "first line\nsecond line"; // \n is a newline character
console.log(escaped);
const continued = "one long \
sentence"; // backslash-newline is removed entirely
console.log(continued);
const template = `first line
second line`; // the line break is part of the string
console.log(template === escaped);
first line
second line
one long sentence
true
The backslash-at-end-of-line form is legal but fragile: a single space after the backslash breaks it, and the indentation of the next line becomes part of the string. Prefer template literals, or join pieces with +.
Escape sequences
A backslash starts an escape sequence, a way to write characters that are hard or impossible to type directly:
| Escape | Character | Code point |
|---|---|---|
\n | newline (line feed) | U+000A |
\r | carriage return | U+000D |
\t | tab | U+0009 |
\b, \f, \v | backspace, form feed, vertical tab | U+0008, U+000C, U+000B |
\0 | the NUL character (not followed by a digit) | U+0000 |
\', \", \` | a quote character | |
\\ | a backslash | U+005C |
\xHH | the character with 2-digit hex code HH | U+0000 to U+00FF |
\uHHHH | the UTF-16 code unit with 4-digit hex code | U+0000 to U+FFFF |
\u{H...} | the code point with 1 to 6 hex digits (ES2015) | U+0000 to U+10FFFF |
console.log("col1\tcol2");
console.log("C:\\Users\\ana"); // a literal backslash must be doubled
console.log("\x41\u0042\u{43}"); // three ways to write letters
console.log("\u{1F680}", "\uD83D\uDE80"); // the same rocket, two spellings
console.log("\#" === "#"); // an unknown escape just drops the backslash
col1 col2
C:\Users\ana
ABC
🚀 🚀
true
Things to know:
- Windows paths and regex strings need doubled backslashes:
"C:\new"contains a newline, not\n.String.raw(article 16) avoids the doubling. - An escape the language doesn't define, like
\#or\q, simply means the character itself. That's harmless but often a typo. - Legacy octal escapes like
"\101"(meaning"A") are aSyntaxErrorin strict mode and in modules. Use\x41or\u0041. - Article 7 explains Unicode escapes, code points and normalization in depth.
length counts code units, not characters
JavaScript strings use the UTF-16 encoding. Every code point up to U+FFFF (the Basic Multilingual Plane, which covers nearly all living languages) takes one 16-bit code unit. Code points above U+FFFF, including most emoji and some rare CJK characters, take two code units, called a surrogate pair:

const s = "go 🚀!";
console.log(s.length); // 6 code units
console.log([...s].length); // 5 code points
console.log(s[3] === "\uD83D"); // [] returns one code unit: half the rocket
console.log(s.charCodeAt(3).toString(16), s.charCodeAt(4).toString(16));
console.log(s.codePointAt(3).toString(16)); // the whole code point
console.log(s.at(-1), s.at(0)); // at() accepts negative indexes (ES2022)
console.log(s[99], s.at(99)); // out of range: undefined, not an error
6
5
true
d83d de80
1f680
! g
undefined undefined
Most string operations (length, [], slice, charAt, substring) work on code units. These work on code points instead: for...of, the spread ..., Array.from(s), codePointAt and String.fromCodePoint. So to count or iterate over characters correctly, use the iterator:
const word = "naïve🙂";
for (const ch of word) {
console.log(ch, ch.codePointAt(0).toString(16));
}
console.log(Array.from(word).reverse().join("")); // a code-point-safe reverse
console.log(word.split("").reverse().join("") === Array.from(word).reverse().join(""));
n 6e
a 61
ï ef
v 76
e 65
🙂 1f642
🙂evïan
false
The classic split("").reverse().join("") breaks the emoji into two lone surrogates and puts them in the wrong order, producing garbage.
Well-formed strings
Because strings are just sequences of 16-bit values, nothing stops a string from containing a lone surrogate, half of a pair, for example after slicing an emoji in two. Such a string isn't valid Unicode, and APIs that need real text (encodeURIComponent, TextEncoder, network and file APIs) either throw or replace the bad unit with the replacement character U+FFFD.
ES2024 added two methods to detect and fix this:
const broken = "go 🚀!".slice(0, 4); // cuts the rocket in half
console.log(broken.length, broken.isWellFormed());
console.log(broken.toWellFormed().codePointAt(3).toString(16)); // replaced with U+FFFD
try {
encodeURIComponent(broken);
} catch (err) {
console.log(err.name);
}
console.log(encodeURIComponent(broken.toWellFormed()));
4 false
fffd
URIError
go%20%EF%BF%BD
Comparing strings
=== compares strings code unit by code unit: two strings are equal when they have the same length and the same unit at every index. (Visually identical text in different normalization forms is not equal; see article 7.)
<, >, <= and >= also compare code unit by code unit, by numeric value. That's not alphabetical order:
console.log("apple" < "banana"); // true, as expected
console.log("Zebra" < "apple"); // true: uppercase letters come before lowercase
console.log("10" < "9"); // true: compared as text, "1" < "9"
console.log("é" > "z"); // true: é is U+00E9, after z (U+007A)
const names = ["émile", "Zoe", "adam", "Eve"];
console.log([...names].sort());
console.log([...names].sort((a, b) => a.localeCompare(b)));
console.log([...names].sort(new Intl.Collator("en", { sensitivity: "base" }).compare));
true
true
true
true
[ 'Eve', 'Zoe', 'adam', 'émile' ]
[ 'adam', 'émile', 'Eve', 'Zoe' ]
[ 'adam', 'émile', 'Eve', 'Zoe' ]
The default sort() and the < operator use code unit order, which puts all uppercase letters before all lowercase ones and accented letters after z. For anything a human will read, sort with localeCompare or an Intl.Collator (faster when sorting many items). Collators also handle numbers in text: new Intl.Collator("en", { numeric: true }) sorts "file10" after "file9".
Strings are immutable
No operation changes a string in place. Index assignment is ignored (or a TypeError in strict mode), and every method returns a new string:
"use strict";
const greeting = "hello";
try {
greeting[0] = "J";
} catch (err) {
console.log(err.name);
}
const fixed = "J" + greeting.slice(1);
console.log(greeting, fixed);
TypeError
hello Jello
Building a long string with += in a loop is fine in modern engines, which use ropes and other tricks to avoid copying. For assembling many pieces, collecting them in an array and calling join is equally good and often clearer.
Common questions
Should I use single or double quotes?
It doesn't matter technically. Choose one, configure Prettier, and never think about it again. Use backticks when you need interpolation or multiple lines.
What's the maximum length of a string?
The specification allows up to 2^53 - 1 code units, but engines set much smaller limits. V8 (Chrome, Node.js) allows about 2^29 code units on 64-bit systems, roughly 536 million. Building a bigger string throws RangeError: Invalid string length.
Does length count bytes?
No, UTF-16 code units. A string's size in UTF-8 bytes (what you'd send over the network or store in a file) is different: new TextEncoder().encode(s).length, or Buffer.byteLength(s) in Node.js. For example, "é" has length 1 but takes 2 bytes in UTF-8.
What's the difference between s[i], s.charAt(i) and s.at(i)?
All return the code unit at index i as a string. Out of range, s[i] and s.at(i) give undefined while charAt gives "". Only at accepts negative indexes, counting from the end: s.at(-1) is the last code unit.
Summary
- Strings are immutable sequences of UTF-16 code units. Single and double quotes are identical; backticks make template literals.
- Escapes:
\n \t \\ \' \",\xHH,\uHHHH,\u{H...}. Unknown escapes drop the backslash; octal escapes are banned in strict code. length,[],sliceand friends count code units, so characters above U+FFFF (most emoji) count as 2.for...of, spread andcodePointAtwork with code points;Intl.Segmenterwith user-perceived characters.- Lone surrogates make strings ill-formed; check with
isWellFormedand repair withtoWellFormed(ES2024). <and defaultsort()use code unit order; uselocaleCompareorIntl.Collatorfor human ordering.
Practice Questions
What is "🙂".length, and what is [..."🙂"].length?
Answer
2 and 1. The emoji is one code point above U+FFFF, stored as a surrogate pair of two code units.
What does "a\\nb".length evaluate to? And "a\nb".length?
Answer
4 and 3. In the first string, \\ is one backslash followed by the letter n. In the second, \n is a single newline character.
Why does ["b", "C", "a"].sort() give ["C", "a", "b"]?
Answer
The default sort compares UTF-16 code units, and uppercase C (U+0043) has a smaller code than lowercase a (U+0061). Use .sort((x, y) => x.localeCompare(y)) for alphabetical order.
Write a function that returns the last character of a string, correctly handling emoji.
Answer
const lastChar = s => [...s].at(-1);. Spreading splits by code point, so a final emoji stays whole. (s.at(-1) would return only its low surrogate.) For multi-code-point emoji such as flags, use Intl.Segmenter.
What does this code return?
"\u{1F680}" === "\uD83D\uDE80"
Answer
true. Both escapes produce the same two code units; \u{...} is just a more convenient way to write a code point above U+FFFF.
Previous: JavaScript BigInt: Arbitrary-Precision Integers, Operators and Pitfalls
Next: JavaScript String Methods: Searching, Slicing, Replacing, Padding and More

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.