Sub topic 5
Decoding Bytes with TextDecoder
This chapter assumes you know how UTF-8 maps code points to bytes, how a Uint8Array holds bytes, and how TextEncoder.encode produces them. TextDecoder does the reverse job. It reads bytes and gives you back a JavaScript string.
The basic call
You create a decoder once and call decode with any ArrayBuffer, typed array, or DataView.
const bytes = new Uint8Array([0x68, 0xc3, 0xa9, 0x20, 0xe2, 0x82, 0xac]);
const decoder = new TextDecoder();
console.log(decoder.decode(bytes)); // "hé €"
console.log(decoder.encoding); // "utf-8"
console.log(decoder.decode(bytes.buffer)); // same result from the ArrayBufferIf you pass a view such as bytes.subarray(1, 3), the decoder reads only the bytes inside that view and ignores the rest of the underlying buffer.
Encoding labels
TextEncoder only produces UTF-8. TextDecoder can read many legacy encodings, and you select one with a label string. Several labels can name the same encoding, and the encoding property reports the canonical name.
const win = new TextDecoder("latin1");
console.log(win.encoding); // "windows-1252"
console.log(win.decode(new Uint8Array([0x80]))); // "€"
console.log(new TextDecoder("utf8").encoding); // "utf-8"
try {
new TextDecoder("not-a-real-encoding");
} catch (err) {
console.log(err.name); // "RangeError"
}| Label you pass | Canonical `encoding` |
|---|---|
| `"utf-8"`, `"utf8"`, none | `"utf-8"` |
| `"latin1"`, `"ascii"`, `"iso-8859-1"` | `"windows-1252"` |
| `"utf-16le"`, `"utf-16"` | `"utf-16le"` |
Lenient versus fatal decoding
UTF-8 has rules, and some byte sequences break them. 0xff can never appear in UTF-8, and 0xc3 must be followed by a continuation byte. By default, TextDecoder swaps each malformed sequence for the replacement character U+FFFD (�) and keeps going. With { fatal: true }, it throws a TypeError instead.
const bad = new Uint8Array([0x68, 0xff, 0x69]);
console.log(new TextDecoder().decode(bad)); // "h\uFFFDi"
const strict = new TextDecoder("utf-8", { fatal: true });
try {
strict.decode(bad);
} catch (err) {
console.log(err.name); // "TypeError"
}Pick the mode based on what a wrong answer would cost:
- Use lenient mode for display, logs, and user-facing text, where showing a � is better than failing.
- Use fatal mode when you validate input, parse protocols, or check file formats. Silent replacement there hides corrupt data, and the damage shows up later and is harder to trace.
The byte order mark
Some files begin with a byte order mark (BOM). In UTF-8 the BOM is the three bytes EF BB BF. The decoder strips it by default. Set ignoreBOM: true if you need to keep it as U+FEFF in the output.
const withBom = new Uint8Array([0xef, 0xbb, 0xbf, 0x68, 0x69]);
console.log(new TextDecoder().decode(withBom).length); // 2
console.log(new TextDecoder("utf-8", { ignoreBOM: true }).decode(withBom)); // "\uFEFFhi"Common errors
- Decoding a chunk that ends mid-character.
new TextDecoder().decode(new Uint8Array([0xe2, 0x82]))returns"\uFFFD", because the third byte of € never arrived. Network chunks split characters like this all the time. The chapter on chunked decoding covers thestreamoption, which fixes it. - Decoding with the wrong label. Reading UTF-8 bytes as windows-1252 never throws. It produces mojibake (garbled text) such as
"hé"for"hé". - Expecting replacement to be reversible. After a byte becomes U+FFFD, the original byte is lost. Re-encoding the string does not give you the same bytes back.
Exercise
What does new TextDecoder().decode(new Uint8Array([0xc3, 0xa9, 0xc3])) return, and what happens if the decoder is created with { fatal: true }?
Show answer
The lenient decoder returns "é\uFFFD". The bytes 0xc3 0xa9 decode to é, and the trailing 0xc3 is an incomplete sequence, so it becomes one U+FFFD. With { fatal: true }, decode throws a TypeError.
Exercise
You receive bytes from a legacy system documented as "ASCII", and byte 0x93 shows up as a curly quote after decoding with new TextDecoder("ascii"). Why?
Show answer
The label "ascii" maps to windows-1252 in the Encoding Standard, and in windows-1252 byte 0x93 is the left double quotation mark (U+201C).