Example 1 — Grow and Shrink in Place
Make a 4-byte resizable buffer, fill it, then grow and shrink it while a Uint8Array watches.
const buffer = new ArrayBuffer(4, { maxByteLength: 16 });
const bytes = new Uint8Array(buffer);
bytes.set([1, 2, 3, 4]);
buffer.resize(8);
console.log(buffer.byteLength); // 8
console.log(JSON.stringify(Array.from(bytes))); // [1,2,3,4,0,0,0,0]
buffer.resize(2);
console.log(buffer.byteLength); // 2
console.log(JSON.stringify(Array.from(bytes))); // [1,2]
console.log(buffer.maxByteLength); // 16 How It Works
- Opt in at creation. The
maxByteLength: 16option makes the 4-byte buffer resizable, up to 16 bytes. - Grow with zeros. After
resize(8)the old bytes stay and four zero bytes appear. Thebytesview was created without a length, so it now shows all 8. - Shrink from the end.
resize(2)keeps only the first two bytes.maxByteLengthstays16, so the buffer can grow again later.

