Sub topic 14
Resizable Buffers and ArrayBuffer.prototype.transfer
This chapter assumes you know how to create an ArrayBuffer, wrap it in typed arrays and a DataView, and set a view's byteOffset and length. Everything here comes from ES2024. Current browsers and Node.js 22 support it. Older runtimes may support resizing but not transfer, so check before you ship.
For years an ArrayBuffer had a fixed size. If you needed more room, you allocated a bigger buffer, copied the bytes into it, and rebuilt every view. ES2024 adds two tools for this:
- Resizable buffers can grow or shrink in place, up to a limit you set when you create them.
transfer()moves a buffer's contents into a new buffer and detaches the old one, leaving it empty and unusable.
Creating a Resizable Buffer
Pass an options object with maxByteLength as the second argument to the constructor:
const buf = new ArrayBuffer(4, { maxByteLength: 16 });
console.log(buf.byteLength); // 4
console.log(buf.maxByteLength); // 16
console.log(buf.resizable); // true
buf.resize(12);
console.log(buf.byteLength); // 12
buf.resize(2);
console.log(buf.byteLength); // 2
try {
buf.resize(17);
} catch (e) {
console.log(e instanceof RangeError); // true, beyond maxByteLength
}
const fixed = new ArrayBuffer(4);
console.log(fixed.resizable, fixed.maxByteLength); // false 4
try {
fixed.resize(8);
} catch (e) {
console.log(e instanceof TypeError); // true, not resizable
}The rules are:
resize(n)accepts anynfrom 0 tomaxByteLength.- Bytes added by growing are always zero.
- Shrinking throws away the bytes past the new end. If you grow the buffer again later, those positions come back as zeros, not as the old data.
- On a fixed buffer,
maxByteLengthequalsbyteLength, andresizethrows aTypeError.
Length-Tracking Views
A typed array or DataView created on a resizable buffer without a length argument is length-tracking. Its length follows the buffer every time the buffer is resized. A view created with an explicit length keeps that fixed length. When the buffer shrinks below the end of a fixed-length view, the view goes out of bounds.
const buf = new ArrayBuffer(8, { maxByteLength: 16 });
const fixed = new Uint8Array(buf, 0, 8); // explicit length
const tracking = new Uint8Array(buf, 4); // no length: tracks the buffer
const dv = new DataView(buf); // no length: tracks the buffer
console.log(fixed.length, tracking.length, dv.byteLength); // 8 4 8
buf.resize(6);
console.log(fixed.length, tracking.length, dv.byteLength); // 0 2 6
console.log(fixed[0]); // undefined
buf.resize(10);
console.log(fixed.length, tracking.length, dv.byteLength); // 8 6 10An out-of-bounds view reports length, byteLength, and byteOffset as 0. Reading an index returns undefined, and writing to an index does nothing. Methods that need the view's contents, such as fill or slice, throw a TypeError. The view is not permanently broken: once the buffer grows back far enough, it comes back in bounds. A length-tracking view with a non-zero offset can also go out of bounds, if the buffer shrinks below its byteOffset.
Detaching with transfer()
buffer.transfer(newLength) returns a new ArrayBuffer that holds the original contents. The original becomes detached. If you leave out newLength, the new buffer has the same length. A shorter length truncates the contents, and a longer one pads them with zeros.
const original = new ArrayBuffer(4);
const view = new Uint8Array(original);
view.set([1, 2, 3, 4]);
const moved = original.transfer(6);
console.log(original.detached, original.byteLength); // true 0
console.log(view.length, view[0]); // 0 undefined
console.log(new Uint8Array(moved)); // Uint8Array(6) [1, 2, 3, 4, 0, 0]
try {
original.slice(0);
} catch (e) {
console.log(e instanceof TypeError); // true
}
try {
new Uint8Array(original);
} catch (e) {
console.log(e instanceof TypeError); // true
}Detaching cannot be undone. Unlike an out-of-bounds view, a view over a detached buffer never recovers. You have to build a new view on the returned buffer.
Calling transfer costs about the same as a copy in the worst case. When the length stays the same, engines can often hand the memory over without copying it. Even when bytes are copied, transfer gives you a clear guarantee about ownership: after the call, no other code holding the old buffer or its views can read or change the data. This guarantee is useful when you hand a buffer to a library or freeze a result.
transfer versus transferToFixedLength
| Method | Result's resizability | Length limit |
|---|---|---|
| `transfer(n)` | Same as the original. A resizable buffer keeps its `maxByteLength` | `n` must not exceed `maxByteLength`, or it throws `RangeError` |
| `transferToFixedLength(n)` | Always fixed-length | Any `n` the engine can allocate |
const growable = new ArrayBuffer(4, { maxByteLength: 64 });
const stillGrowable = growable.transfer();
console.log(stillGrowable.resizable, stillGrowable.maxByteLength); // true 64
const frozen = stillGrowable.transferToFixedLength(2);
console.log(frozen.resizable, frozen.byteLength); // false 2A Worked Example: A Growable Byte Writer
A common pattern is to write binary output of unknown size into a growable buffer, then return a fixed buffer trimmed to the exact length. The writer below uses length-tracking views, so it never has to rebuild them after a resize.
class ByteWriter {
constructor(initial = 16, max = 1 << 20) {
this.buffer = new ArrayBuffer(initial, { maxByteLength: max });
this.bytes = new Uint8Array(this.buffer); // length-tracking
this.view = new DataView(this.buffer); // length-tracking
this.length = 0;
}
ensure(extra) {
const needed = this.length + extra;
if (needed <= this.buffer.byteLength) return;
if (needed > this.buffer.maxByteLength) {
throw new RangeError(`ByteWriter limit of ${this.buffer.maxByteLength} bytes exceeded`);
}
let size = Math.max(this.buffer.byteLength, 1);
while (size < needed) size *= 2;
this.buffer.resize(Math.min(size, this.buffer.maxByteLength));
}
writeUint8(value) {
this.ensure(1);
this.view.setUint8(this.length, value);
this.length += 1;
}
writeUint32(value) {
this.ensure(4);
this.view.setUint32(this.length, value); // big-endian
this.length += 4;
}
writeBytes(source) {
this.ensure(source.length);
this.bytes.set(source, this.length);
this.length += source.length;
}
finish() {
// Exact-size fixed buffer; the writer's buffer is detached afterwards.
return this.buffer.transferToFixedLength(this.length);
}
}
const w = new ByteWriter(4);
w.writeUint8(1);
w.writeUint32(0xcafebabe);
w.writeBytes(new TextEncoder().encode('hi'));
const out = w.finish();
console.log(out.byteLength, out.resizable); // 7 false
console.log(new Uint8Array(out)); // Uint8Array(7) [1, 202, 254, 186, 190, 104, 105]
console.log(w.buffer.detached); // trueBecause finish detaches the writer's buffer, any later write fails loudly. ensure reads byteLength, which is 0 on a detached buffer, so it calls resize, and resize throws a TypeError on a detached buffer. Without the detach, a stale writer could quietly overwrite output that someone else already holds.
Common Errors
| Symptom | Cause |
|---|---|
| `TypeError` from `resize` | The buffer was created without `maxByteLength`, or it is detached |
| `RangeError` from `resize` or `transfer(n)` | The new length is greater than `maxByteLength` |
| View suddenly has `length` 0 | Either the buffer shrank below the view's end (out of bounds) or the buffer was detached. Check `buffer.detached` to tell which |
| View did not grow after `resize` | The view was created with an explicit length, so it does not track the buffer |
| Old data missing after shrink then grow | Shrinking discards bytes, and growing adds zeros |
| `TypeError` from `slice`, `fill`, or a constructor | The buffer is detached |
When to Use Which
- Use a resizable buffer when output grows step by step (encoders, serializers, network frame assemblers) and you can name a sensible upper bound. You avoid repeated allocate-and-copy cycles and stale views.
- Use the allocate-and-copy pattern when you have no reasonable maximum or must support older runtimes.
- Use
transferToFixedLengthto hand off a finished result. The receiver gets a buffer with a plain, fixed size, and the producer loses access to it. - Use
transferwhen you want to keep resizability but end aliasing, for example to revoke views you gave to other code.
SharedArrayBuffer has a growable form too: new SharedArrayBuffer(n, { maxByteLength }) with a grow() method. It can only get bigger, because other threads may be reading it at the same time. Shared memory is covered in the last chapter. The postMessage transfer list, covered in the next chapter, detaches buffers the same way transfer() does.
Exercise
A buffer is created with new ArrayBuffer(10, { maxByteLength: 20 }). You create a = new Uint16Array(buf, 2, 3) and b = new Uint16Array(buf, 4), then call buf.resize(7). What are a.length and b.length?
Show answer
a covers bytes 2 to 7, which is past the new length of 7, so it is out of bounds and a.length is 0. b tracks the buffer from offset 4. Three bytes remain after offset 4, which holds one whole Uint16 element, so b.length is 1 (the leftover byte is ignored).
Exercise
After const m = r.transfer(), where r was resizable with maxByteLength 32, what do r.detached, m.resizable, and m.maxByteLength return, and what happens if you call m.transfer(40)?
Show answer
r.detached is true. transfer keeps resizability, so m.resizable is true and m.maxByteLength is 32. m.transfer(40) throws a RangeError because 40 is greater than the maximum. Use m.transferToFixedLength(40) if you need 40 bytes.
Exercise
Why does the ByteWriter keep its own length field instead of using this.buffer.byteLength as the write position?
Show answer
The buffer grows by doubling, so its byteLength is usually larger than the number of bytes actually written. The separate length records where the real data ends, and finish uses it to trim the result with transferToFixedLength(this.length).