Sub topic 1
What a JavaScript String Really Contains
Prerequisites
This chapter assumes you know modern JavaScript syntax (let/const, arrow functions, destructuring), understand bits and bytes, and can run code in a browser console or Node.js.
Strings Are UTF-16 Code Units
A JavaScript string is a sequence of 16-bit UTF-16 code units. It is not a sequence of characters or bytes. Most common characters fit in one code unit. Characters outside the Basic Multilingual Plane, such as many emoji, need two code units, called a surrogate pair. length counts code units:
console.log("é".length); // 1
console.log("😀".length); // 2 (surrogate pair)UTF-8: Turning Code Points into Bytes
Files, HTTP bodies, and most APIs use UTF-8. UTF-8 encodes each Unicode code point as 1 to 4 bytes:
| Code point range | Example | UTF-8 bytes |
|---|---|---|
| U+0000 to U+007F | `h` | 1 |
| U+0080 to U+07FF | `é` | 2 |
| U+0800 to U+FFFF | `€` | 3 |
| U+10000 to U+10FFFF | `😀` | 4 |
String length and byte length therefore rarely match once text contains anything other than ASCII.
Holding Bytes with ArrayBuffer and Uint8Array
An ArrayBuffer is a fixed-size block of raw memory. A Uint8Array is a view onto that memory in which each element is one byte, a value from 0 to 255. Encoding APIs return and accept Uint8Array.
Encoding Strings with TextEncoder
TextEncoder always produces UTF-8:
const encoder = new TextEncoder();
const text = "héllo €";
const bytes = encoder.encode(text);
console.log(text.length); // 7 (UTF-16 code units)
console.log(bytes.length); // 10 (UTF-8 bytes: é is 2 bytes, € is 3)
console.log(bytes instanceof Uint8Array); // trueencodeInto writes into a buffer you already have, so no new array is allocated. It returns how many code units it read and how many bytes it wrote:
const target = new Uint8Array(16);
const { read, written } = new TextEncoder().encodeInto("€uro", target);
console.log(read); // 4 (UTF-16 code units consumed)
console.log(written); // 6 (bytes written into target)Exercise
What do "😀".length and new TextEncoder().encode("😀").length return, and why do they differ?
Show answer
They return 2 and 4. The emoji is one code point stored as a surrogate pair of two UTF-16 code units, and UTF-8 encodes code points above U+FFFF as 4 bytes.