Sub topic 4
Encoding Strings with TextEncoder
This chapter shows how to turn JavaScript strings into UTF-8 bytes with the standard TextEncoder API. It covers the two methods, encode and encodeInto, how to size buffers for each, and the mistakes that tend to turn up in production code.
You should already know that a JavaScript string is a sequence of UTF-16 code units, that UTF-8 uses 1 to 4 bytes per code point, and that a Uint8Array is a view over an ArrayBuffer. Earlier chapters cover all three. The examples run unchanged in any modern browser console, Deno, Bun, or Node.js 11 and later, where TextEncoder is a global.
What TextEncoder Does
TextEncoder is an object that converts a string into UTF-8 bytes. It supports exactly one output encoding, UTF-8, and it holds no state between calls. One instance can be created at module load and reused everywhere.
const encoder = new TextEncoder();
console.log(encoder.encoding); // "utf-8"
// Arguments to the constructor are ignored. This is still UTF-8.
const notUtf16 = new TextEncoder("utf-16le");
console.log(notUtf16.encoding); // "utf-8"The read-only encoding property always returns "utf-8". Older drafts of the Encoding Standard accepted a label argument, and some old code still passes one. Modern engines silently ignore it. If you need UTF-16 or a legacy code page as output, TextEncoder cannot help. You would have to write the bytes yourself, or in Node.js use Buffer.from(str, "utf16le").
encode: Allocate and Return
encode(string) returns a new Uint8Array whose length is exactly the number of UTF-8 bytes needed.
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); // true
console.log(Array.from(bytes));
// [104, 195, 169, 108, 108, 111, 32, 226, 130, 172]The ASCII letters each map to one byte with the same value. é (U+00E9) becomes 0xC3 0xA9, and € (U+20AC) becomes 0xE2 0x82 0xAC. The array is backed by a fresh ArrayBuffer, so you can transfer it to a worker, send it with fetch, or change it without affecting anything else.
Argument conversion gotchas
The parameter is declared as a string that defaults to "". Anything else passes through ordinary string conversion first, and that can hide bugs:
const encoder = new TextEncoder();
console.log(encoder.encode().length); // 0 (no argument means "")
console.log(encoder.encode(undefined).length); // 0 (undefined also means "")
console.log(Array.from(encoder.encode(null))); // [110, 117, 108, 108] which is "null"
console.log(Array.from(encoder.encode(42))); // [52, 50] which is "42"
console.log(Array.from(encoder.encode({}))); // bytes of "[object Object]"A null that reaches the encoder by mistake produces four valid bytes instead of an error. If the input crosses a trust boundary, check typeof value === "string" before you encode it.
encodeInto: Write into a Buffer You Own
encodeInto(string, destination) writes UTF-8 bytes into an existing Uint8Array and returns an object with two counts:
readis the number of UTF-16 code units consumed from the source string.writtenis the number of bytes written into the destination.
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)
console.log(Array.from(target.subarray(0, written)));
// [226, 130, 172, 117, 114, 111]The two counts measure different units. read counts code units in the string. written counts bytes in the array. Mixing them up is the most common encodeInto bug.
What happens when the buffer is too small
encodeInto never throws because space ran out, and it never writes part of a character. It stops before the first code point that does not fit.
const encoder = new TextEncoder();
const small = new Uint8Array(3);
console.log(encoder.encodeInto("a€", small));
// { read: 1, written: 1 }: "a" fits, but € needs 3 bytes and only 2 remain
const tiny = new Uint8Array(3);
console.log(encoder.encodeInto("😀", tiny));
// { read: 0, written: 0 }: the emoji needs 4 bytesThe emoji is a surrogate pair, which is two code units and one code point. The encoder takes both units or neither, so read advances by 2 when the emoji fits and by 0 when it does not. Because the result is never a partial sequence, the bytes already written are always valid UTF-8. The catch is that a short buffer truncates the string silently. You must compare read with string.length to find out whether the whole string was encoded.
Sizing the destination
str.length * 3 bytes always holds the full encoding. A single UTF-16 code unit produces at most 3 bytes, and a surrogate pair (2 units) produces 4 bytes, which is fewer than 6. That bound wastes memory on ASCII-heavy text, though. If you need the exact size without allocating, compute it from code points:
function utf8ByteLength(str) {
let bytes = 0;
for (const ch of str) {
const cp = ch.codePointAt(0);
bytes += cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4;
}
return bytes;
}
console.log(utf8ByteLength("héllo €")); // 10
console.log(utf8ByteLength("😀")); // 4
console.log(utf8ByteLength("héllo €") === new TextEncoder().encode("héllo €").length); // trueA lone surrogate iterates as one character with a code point between U+D800 and U+DFFF and counts as 3 bytes. That matches what the encoder writes for it, as the next section shows. In Node.js, Buffer.byteLength(str, "utf8") gives the same number.
Writing several strings into one buffer
encodeInto writes from the start of the view it receives. To append at an offset, pass a subarray, which is a view onto the same memory and costs no copy:
const encoder = new TextEncoder();
function packStrings(strings, capacity) {
const buffer = new Uint8Array(capacity);
let offset = 0;
for (const s of strings) {
const { read, written } = encoder.encodeInto(s, buffer.subarray(offset));
if (read < s.length) {
throw new RangeError(`Buffer full: "${s}" did not fit at byte ${offset}`);
}
offset += written;
}
return buffer.subarray(0, offset);
}
const packed = packStrings(["id=", "42", ";name=", "Zoë"], 64);
console.log(packed.length); // 15The returned subarray shares memory with buffer. Copy it with packed.slice() if the caller should not see later writes to the larger buffer.
Lone Surrogates Become U+FFFD
UTF-8 cannot represent an unpaired surrogate. TextEncoder replaces each lone surrogate with the 3-byte encoding of U+FFFD, the replacement character, and gives no warning:
console.log(Array.from(new TextEncoder().encode("\uD800"))); // [239, 191, 189]The data loss is silent. The string goes in with one value and comes back from decoding with another. A later chapter covers detecting and repairing these strings with isWellFormed and toWellFormed.
encode or encodeInto?
| Concern | `encode` | `encodeInto` |
|---|---|---|
| Allocation | New `Uint8Array` on every call | None; writes into your buffer |
| Output size | Always exact | You choose it; risk of truncation |
| Error signal for lack of space | Not applicable | None; check `read < str.length` |
| Typical use | One-off conversions, `fetch` bodies, hashing | Hot loops, WebAssembly memory, binary protocols, pooled buffers |
| Code complexity | One line | Offset and overflow handling |
Use encode by default. It is simpler, and the engine already sizes the result exactly. Reach for encodeInto when allocation shows up in profiles, or when the bytes must land in memory you do not own. Writing a string straight into a WebAssembly module's linear memory is a typical case:
// Assumes `memory` is a WebAssembly.Memory and `ptr` is an offset you allocated.
function writeToWasm(memory, ptr, maxBytes, str) {
const view = new Uint8Array(memory.buffer, ptr, maxBytes);
const { read, written } = new TextEncoder().encodeInto(str, view);
if (read < str.length) throw new RangeError("String too long for wasm buffer");
return written;
}Create the Uint8Array view on every call. If the memory grows, its old ArrayBuffer is detached and any view you cached becomes unusable.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Using `str.length` as the byte count | Buffers or `Content-Length` too small for non-ASCII text | Use `encode(str).length` or an exact byte-length function |
| Ignoring `read` from `encodeInto` | Strings silently cut off at the end | Compare `read` with `str.length` |
| Confusing `read` with `written` | Offsets drift when text contains non-ASCII characters | Advance byte offsets by `written` only |
| Passing an encoding label | Expecting UTF-16 output and getting UTF-8 | Use Buffer or manual encoding for other encodings |
| Encoding non-strings | `"null"` or `"[object Object]"` in the payload | Validate the type before encoding |
| `unescape(encodeURIComponent(s))` | Deprecated legacy trick that produces a binary string, not bytes | Use `TextEncoder` |
Exercise
You call new TextEncoder().encodeInto("ab😀c", new Uint8Array(5)). What are read and written, and why?
Show answer
read is 2 and written is 2. "a" and "b" take 1 byte each, which leaves 3 bytes free. The emoji needs 4 bytes, so the encoder stops before it and writes nothing for it. "c" is never reached, even though it would have fit, because encoding stops at the first code point that does not fit.
Exercise
A logging function allocates new Uint8Array(message.length) and fills it with encodeInto. It works in tests but loses the end of some messages in production. Explain the bug and give two fixes.
Show answer
message.length counts UTF-16 code units, but any non-ASCII character takes 2 to 4 bytes in UTF-8, so the buffer is too small and encodeInto stops early without throwing. One fix is to size the buffer at message.length * 3, which always fits, and return buffer.subarray(0, written). The other is to use encoder.encode(message), which allocates exactly the right size. Either way, check read === message.length if you keep using encodeInto.
Exercise
Why is it safe to share one TextEncoder instance across an entire application, when the same is not always true of TextDecoder?
Show answer
TextEncoder holds no state between calls. Each call to encode or encodeInto stands alone, and UTF-8 output never depends on earlier input. A TextDecoder used with stream: true keeps incomplete byte sequences from one call to the next, so sharing one decoder across unrelated streams can mix their bytes together.