Sub topic 2
ArrayBuffer: A Block of Raw Bytes
This chapter assumes you know core JavaScript syntax and regular arrays. It also assumes you understand that a byte holds 8 bits (values 0 to 255) and can read hexadecimal numbers such as 0xff. You will see Uint8Array used briefly to look inside a buffer. The next chapter covers typed arrays properly, so here you only need to know that new Uint8Array(buffer) shows a buffer's bytes as numbers from 0 to 255.
What an ArrayBuffer Is
An ArrayBuffer is an object that owns a fixed-length block of raw memory, measured in bytes. It does not know what those bytes mean. It has no idea whether they hold integers, floats, pixels, or UTF-8 text. It just stores them.
That separation is the core design choice. JavaScript splits binary data into two layers:
- Storage: the
ArrayBuffer, which allocates and owns the bytes. - Interpretation: views such as typed arrays and
DataView, which read and write those bytes as particular number types.
You never read or write an ArrayBuffer directly. You always go through a view.
Creating a Buffer
The constructor takes a length in bytes. The memory starts out filled with zeros.
const buf = new ArrayBuffer(8);
console.log(buf.byteLength); // 8
// Look inside through a byte view
console.log(new Uint8Array(buf)); // Uint8Array(8) [0, 0, 0, 0, 0, 0, 0, 0]The zero fill is guaranteed by the specification. You never get leftover memory from another part of the program, which matters for security as well as predictability.
The length argument goes through the spec's ToIndex conversion. That conversion has a few edge cases worth knowing:
console.log(new ArrayBuffer().byteLength); // 0 (missing length means 0)
console.log(new ArrayBuffer(1.9).byteLength); // 1 (fraction truncated)
console.log(new ArrayBuffer('4').byteLength); // 4 (string converted to number)
for (const bad of [-1, 2 ** 53]) {
try {
new ArrayBuffer(bad);
} catch (e) {
console.log(bad, e instanceof RangeError); // true for both
}
}Negative lengths and lengths above 2 ** 53 - 1 throw a RangeError. Engines also have practical limits that are far smaller than that. If an allocation is legal but too big for the engine, for example several gigabytes on a constrained device, the engine also throws a RangeError. Code that allocates buffers from untrusted sizes, such as a length field read from a file header, should check the size before calling the constructor.
You must call it with new. Calling ArrayBuffer(8) without it throws a TypeError.
An ArrayBuffer Is Not an Array
The name suggests a kind of array, but an ArrayBuffer behaves very differently from [].
| Feature | Regular `Array` | `ArrayBuffer` |
|---|---|---|
| Contents | Any JavaScript values, mixed freely | Raw bytes only |
| Index access (`x[0]`) | Reads or writes an element | No element access; `buf[0]` is `undefined` |
| Length | Grows and shrinks (`push`, `length = n`) | Fixed at creation (unless created resizable, covered later) |
| Memory layout | Engine-defined, may have holes | One contiguous block of bytes |
| Size property | `length` (element count) | `byteLength` (byte count) |
| Iterable with `for...of` | Yes | No, throws `TypeError` |
| `Array.isArray` | `true` | `false` |
| `JSON.stringify` | Serializes elements | Produces `"{}"` |
The index-access row causes the most confusion. An ArrayBuffer is an ordinary object, so writing buf[0] = 5 does not fail. It quietly creates a normal property named "0" and leaves the bytes untouched.
const buf = new ArrayBuffer(4);
console.log(buf[0]); // undefined
buf[0] = 5; // creates an ordinary property, not a byte
console.log(buf[0]); // 5
console.log(new Uint8Array(buf)[0]); // 0, the memory did not change
console.log(Array.isArray(buf)); // false
console.log(JSON.stringify(buf)); // "{}"
try {
for (const b of buf) {}
} catch (e) {
console.log(e instanceof TypeError); // true, ArrayBuffer is not iterable
}Properties and Methods
An ArrayBuffer has only a few members. Here are the ones for ordinary fixed-length buffers:
| Member | What it does |
|---|---|
| `byteLength` | Number of bytes, read-only |
| `slice(begin, end)` | Returns a **new** ArrayBuffer containing a copy of the selected bytes |
| `ArrayBuffer.isView(x)` | Static method; `true` if `x` is a typed array or `DataView` |
| `resizable`, `maxByteLength` | `false` and equal to `byteLength` for fixed buffers |
| `resize()`, `transfer()`, `detached` | ES2024 additions, covered in a later chapter |
byteLength is read-only. Assigning to it has no effect, and in strict mode it throws a TypeError, because it is a getter with no setter.
slice copies
ArrayBuffer.prototype.slice works like Array.prototype.slice. It accepts negative indices and clamps out-of-range values. The result is an independent copy with its own memory.
const original = new ArrayBuffer(6);
new Uint8Array(original).set([10, 20, 30, 40, 50, 60]);
const part = original.slice(2, 5); // bytes at index 2, 3, 4
const tail = original.slice(-2); // last two bytes
console.log(part.byteLength); // 3
console.log(new Uint8Array(part)); // Uint8Array(3) [30, 40, 50]
console.log(new Uint8Array(tail)); // Uint8Array(2) [50, 60]
new Uint8Array(part)[0] = 99;
console.log(new Uint8Array(original)[2]); // 30, the original is unchangedCopying costs time and memory in proportion to the slice size. If you only need a window onto existing bytes, create a view with an offset instead. A later chapter covers views that share memory.
Telling buffers from views
APIs that accept binary data often take either a raw buffer or a view. ArrayBuffer.isView lets you tell them apart:
const buf = new ArrayBuffer(4);
console.log(ArrayBuffer.isView(buf)); // false
console.log(ArrayBuffer.isView(new Uint8Array(buf))); // true
console.log(ArrayBuffer.isView(new DataView(buf))); // true
console.log(ArrayBuffer.isView([1, 2, 3])); // false
// Normalize either input to a Uint8Array over the right bytes
function toBytes(input) {
if (input instanceof ArrayBuffer) return new Uint8Array(input);
if (ArrayBuffer.isView(input)) {
return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
}
throw new TypeError('Expected an ArrayBuffer or a view');
}
console.log(toBytes(buf).length); // 4Note the use of byteOffset and byteLength in toBytes. A view may cover only part of its buffer. Using input.buffer alone would include bytes outside the view, which is a common bug.
Inspecting a Buffer
A hex dump helper is useful while debugging any binary code. It goes through a Uint8Array because that is the only way to see the bytes.
function hexDump(buffer) {
return Array.from(new Uint8Array(buffer), (b) =>
b.toString(16).padStart(2, '0')
).join(' ');
}
const buf = new ArrayBuffer(4);
new Uint8Array(buf).set([0xde, 0xad, 0xbe, 0xef]);
console.log(hexDump(buf)); // "de ad be ef"Node.js's console.log(buf) also prints a buffer's contents. Browser devtools show them when you expand the object. Do not depend on either format in program output.
Copying Buffers Whole
To duplicate a whole buffer, use buf.slice(0) or structuredClone(buf). Both give you an independent copy.
const a = new ArrayBuffer(2);
new Uint8Array(a)[0] = 7;
const b = structuredClone(a);
new Uint8Array(b)[0] = 8;
console.log(new Uint8Array(a)[0]); // 7
console.log(new Uint8Array(b)[0]); // 8structuredClone is the same algorithm postMessage uses. Later chapters show how a transfer list makes it move a buffer instead of copying it. After a move, the original buffer is detached: its byteLength becomes 0 and views over it become empty.
Common Errors
- Treating the length as an element count.
new ArrayBuffer(4)holds 4 bytes, so it fits only one 32-bit integer. Allocatecount * elementSizebytes, or let a typed array constructor allocate the buffer for you. - Indexing the buffer directly.
buf[0]reads an ordinary property, never a byte. - Expecting
sliceto share memory.ArrayBuffer.prototype.slicealways copies. - Passing
view.bufferwhere the view is meant. The buffer can be larger than the view. - Trusting external sizes. Validate lengths from files or network messages before allocating.
Exercise
After running const buf = new ArrayBuffer(3); buf[1] = 200; const v = new Uint8Array(buf);, what are buf.byteLength, buf[1], and v[1], and why?
Show answer
buf.byteLength is 3, buf[1] is 200, and v[1] is 0. Assigning buf[1] creates an ordinary object property on the ArrayBuffer and does not touch its memory. The memory is still zero-filled, so the view reads 0.
Exercise
You have const view = new Uint8Array(new ArrayBuffer(16), 4, 8); and call const copy = view.buffer.slice(0);. How many bytes does copy contain, and how would you copy only the bytes the view covers?
Show answer
copy has 16 bytes, because view.buffer is the entire underlying buffer. To copy only the view's bytes, use view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength), which returns an 8-byte ArrayBuffer.
Exercise
Which of these throw, and with what error type: new ArrayBuffer(-4), new ArrayBuffer(2.7), ArrayBuffer(8), and for (const b of new ArrayBuffer(2)) {}?
Show answer
new ArrayBuffer(-4) throws a RangeError. new ArrayBuffer(2.7) does not throw and creates a 2-byte buffer. ArrayBuffer(8) without new throws a TypeError. The for...of loop throws a TypeError because an ArrayBuffer is not iterable.