Sub topic 3
Holding Bytes with ArrayBuffer and Uint8Array
The previous chapters showed that a JavaScript string is a sequence of UTF-16 code units, and that UTF-8 turns code points into a variable number of bytes. Before you can call TextEncoder or build a base64 string, you need a place to keep those bytes. In JavaScript that place is an ArrayBuffer, and you usually read and write it through a Uint8Array.
This chapter assumes you know modern JavaScript syntax, ordinary arrays and loops, and the idea that a byte is 8 bits holding a value from 0 to 255. Every example runs in a browser console or in Node.js 17 or later.
The Working Model: Memory Plus Views
The design has two layers:
- An
ArrayBufferis a fixed-length block of raw memory. It has a size (byteLength) and nothing else. You cannot index into it directly. - A typed array view, such as
Uint8Array, interprets that memory as a sequence of numbers of one type. AUint8Arrayreads it as unsigned 8-bit integers, one element per byte.
Several views can point at the same buffer at once. A write through one view is visible through all the others, because only one copy of the memory exists.
const buffer = new ArrayBuffer(4);
console.log(buffer.byteLength); // 4
const view = new Uint8Array(buffer);
view[0] = 72;
view[1] = 105;
console.log(view); // Uint8Array(4) [72, 105, 0, 0]
const second = new Uint8Array(buffer);
console.log(second[1]); // 105 (same memory)A new ArrayBuffer is always zero-filled. You never see leftover data from earlier allocations.
Creating a Uint8Array
Most of the time you skip the explicit ArrayBuffer, because a Uint8Array creates one for you. The constructor accepts several argument shapes:
// 1. A length: allocates a new zero-filled buffer
const a = new Uint8Array(3); // [0, 0, 0]
// 2. An array or iterable: copies the values
const b = new Uint8Array([1, 2, 3]); // [1, 2, 3]
// 3. An existing buffer, with optional byte offset and length: no copy
const buf = new ArrayBuffer(8);
const c = new Uint8Array(buf, 2, 4); // view of bytes 2..5
console.log(c.length, c.byteOffset); // 4 2
// 4. Static helpers
const d = Uint8Array.of(0x48, 0x69); // [72, 105]
const e = Uint8Array.from("123", Number); // [1, 2, 3]
console.log(a, b, d, e);Shapes 1 and 2 allocate new memory. Shape 3 does not allocate. It describes a window onto memory that already exists. This difference matters a lot for the gotchas later in the chapter.
What Happens When You Store a Value
A Uint8Array element can only hold an integer from 0 to 255. When you assign anything else, JavaScript converts it instead of throwing an error. The conversion is ToUint8: the value is converted to a number, truncated toward zero, and reduced modulo 256.
const bytes = new Uint8Array(5);
bytes[0] = 256; // 256 mod 256
bytes[1] = -1; // wraps to 255
bytes[2] = 3.7; // truncated to 3
bytes[3] = "65"; // string converted to number 65
bytes[4] = "hi"; // NaN becomes 0
console.log(bytes); // Uint8Array(5) [0, 255, 3, 65, 0]Uint8ClampedArray exists for canvas pixel data. Instead of wrapping, it clamps to the range and rounds to the nearest integer (ties go to the even number):
const clamped = new Uint8ClampedArray(3);
clamped[0] = 256; // 255
clamped[1] = -1; // 0
clamped[2] = 3.7; // 4
console.log(clamped); // Uint8ClampedArray(3) [255, 0, 4]For text encoding and base64 work, use Uint8Array. Every API in this tutorial produces or expects one.
Fixed Length and Out-of-Range Indexes
A typed array cannot grow or shrink. There is no push, pop, or splice. Writing past the end is ignored, and reading past the end returns undefined:
const fixed = new Uint8Array(3);
fixed[10] = 5;
console.log(fixed.length); // 3
console.log(fixed[10]); // undefined
console.log(typeof fixed.push); // "undefined"When you don't know the final size in advance, collect chunks in a regular array and concatenate them once at the end:
function concatBytes(chunks) {
const total = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
const result = new Uint8Array(total);
let offset = 0;
for (const chunk of chunks) {
result.set(chunk, offset);
offset += chunk.length;
}
return result;
}
console.log(concatBytes([Uint8Array.of(1, 2), Uint8Array.of(3)]));
// Uint8Array(3) [1, 2, 3]set(source, offset) copies a whole array into place in one call. It is much faster than a loop that assigns one element at a time.
subarray Versus slice
The two methods look alike, but they behave differently:
| Method | Allocates new memory | Changes to the original are visible | Typical use |
|---|---|---|---|
| `subarray(start, end)` | No | Yes | Cheap window for reading or for passing to an API |
| `slice(start, end)` | Yes | No | Independent copy you can keep or modify |
const original = Uint8Array.of(1, 2, 3, 4, 5);
const shared = original.subarray(1, 3);
const copy = original.slice(1, 3);
original[1] = 99;
console.log(shared[0]); // 99
console.log(copy[0]); // 2Use subarray in hot paths such as chunked processing, where copying would waste memory. Use slice when the data must outlive changes to the source buffer.
The byteOffset Gotcha
Every view exposes .buffer, but .buffer is the whole underlying ArrayBuffer, not just the part the view covers. Code that passes view.buffer to another API can accidentally send bytes that belong to someone else.
const whole = Uint8Array.of(10, 20, 30, 40, 50);
const part = whole.subarray(1, 3);
console.log(part.length); // 2
console.log(part.byteOffset); // 1
console.log(part.buffer.byteLength); // 5, not 2
// Wrong: reinterprets the entire buffer
console.log(new Uint8Array(part.buffer)); // [10, 20, 30, 40, 50]
// Right: respect offset and length
console.log(new Uint8Array(part.buffer, part.byteOffset, part.byteLength)); // [20, 30]This happens in real code. Node.js allocates small Buffer objects from a shared memory pool, so buf.buffer often holds many unrelated buffers. Whenever you reach for .buffer, carry byteOffset and byteLength with it, or call slice() to get a tightly sized copy.
Multi-Byte Views and Endianness
Other typed arrays read the same memory in larger units. A Uint16Array treats every 2 bytes as one number, using the platform's byte order. Almost every current machine is little-endian, so the lowest byte comes first. DataView lets you pick the byte order explicitly. That is what file formats and network protocols need.
const buf = new ArrayBuffer(2);
const u8 = new Uint8Array(buf);
u8[0] = 0x01;
u8[1] = 0x02;
const dv = new DataView(buf);
console.log(dv.getUint16(0)); // 258 (0x0102, big-endian is the default)
console.log(dv.getUint16(0, true)); // 513 (0x0201, little-endian)
try {
new Uint16Array(new ArrayBuffer(4), 1);
} catch (err) {
console.log(err.name); // "RangeError": offset must be a multiple of 2
}UTF-8 is a byte-oriented encoding and has no byte-order issue, which is one reason TextEncoder returns a Uint8Array and nothing wider.
Inspecting and Comparing Bytes
map on a Uint8Array returns another Uint8Array, so every result is forced back through ToUint8. Converting bytes to hex with map therefore fails silently:
const sample = Uint8Array.of(255, 16);
// Wrong: "ff" becomes NaN becomes 0, "10" becomes 10
console.log(sample.map((b) => b.toString(16))); // Uint8Array(2) [0, 10]
// Right: Array.from with a mapping function produces a plain array
function toHex(bytes) {
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(" ");
}
console.log(toHex(sample)); // "ff 10"Typed arrays are objects, so === compares identity, not contents. Write a small comparison function:
function bytesEqual(a, b) {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
console.log(Uint8Array.of(1, 2) === Uint8Array.of(1, 2)); // false
console.log(bytesEqual(Uint8Array.of(1, 2), Uint8Array.of(1, 2))); // trueWhy Bytes Need a Text Form
Typed arrays do not serialize well as text:
console.log(JSON.stringify(Uint8Array.of(1, 2)));
// '{"0":1,"1":2}'
console.log(String(Uint8Array.of(72, 105)));
// "72,105"Neither result is compact, and the JSON version does not even turn back into a Uint8Array when parsed. This is the gap base64 fills later in the tutorial: it turns any Uint8Array into a short ASCII string that survives JSON, URLs, and HTTP headers.
Transferring and Detaching Buffers
You can move an ArrayBuffer to a worker or into a new owner without copying it. After the move, the original buffer is detached: its length becomes 0 and every view on it is empty.
const source = Uint8Array.of(1, 2, 3);
const moved = structuredClone(source.buffer, { transfer: [source.buffer] });
console.log(source.length); // 0 (detached)
console.log(new Uint8Array(moved)); // Uint8Array(3) [1, 2, 3]When a view suddenly reports length 0, check whether its buffer was passed to postMessage or structuredClone with a transfer list.
Common Errors at a Glance
| Symptom | Cause | Fix |
|---|---|---|
| Values like 300 come out as 44 | ToUint8 wraps modulo 256 | Validate or mask with `& 0xff` |
| Extra bytes appear after using `.buffer` | The view had a nonzero `byteOffset` or shorter length | Pass offset and length, or `slice()` |
| Edits show up in a "copy" | `subarray` shares memory | Use `slice` |
| Hex output is all zeros | `map` coerced strings back to bytes | Use `Array.from(bytes, fn)` |
| `RangeError` creating `Uint16Array` | Misaligned byte offset | Use `DataView` or an aligned offset |
| View length is suddenly 0 | Buffer was transferred | Copy before transferring |
Exercise
You run const a = Uint8Array.of(5, 6, 7, 8); const b = a.subarray(2); const c = new Uint8Array(b.buffer); b[0] = 0;. What are c.length and the contents of a, and why?
Show answer
c.length is 4 and a is [5, 6, 0, 8]. b is a window starting at byte offset 2 on the same buffer, so writing b[0] changes a[2]. c was built from b.buffer without the offset and length, so it covers the whole 4-byte buffer rather than the 2 bytes of b.
Exercise
Write a function fromHex(hex) that turns a string like "48 69 ff" (space-separated hex pairs) into a Uint8Array, and throw an error if any pair is not valid hex.
Show answer
function fromHex(hex) { const parts = hex.trim().split(/\s+/); const out = new Uint8Array(parts.length); parts.forEach((p, i) => { if (!/^[0-9a-fA-F]{2}$/.test(p)) throw new Error("Invalid hex: " + p); out[i] = parseInt(p, 16); }); return out; } Calling fromHex("48 69 ff") returns Uint8Array [72, 105, 255]. The regex check matters because assigning NaN to an element would silently store 0.
Exercise
Why does Uint8Array.of(200).map((b) => b * 2) give [144], and how would you get 400?
Show answer
map on a typed array returns a typed array of the same type, so 400 goes through ToUint8 and becomes 400 mod 256 = 144. Use Array.from(Uint8Array.of(200), (b) => b * 2) to get a plain array [400], or store the results in a wider type such as Uint16Array.