Resizable ArrayBuffer Grows In Place
Allocate an ArrayBuffer with maxByteLength and call resize() to expand or shrink backing bytes in place while length-tracking typed views update automatically.
Code
// Reserve up to 16 bytes of address space while starting at 4 bytes
const buffer = new ArrayBuffer(4, { maxByteLength: 16 });
const view = new Uint8Array(buffer);
view.set([10, 20, 30, 40]);
console.log('initial:', buffer.resizable, 'len:', view.length, 'max:', buffer.maxByteLength);
// Growing the buffer updates length-tracking views automatically without reallocating
buffer.resize(8);
view.set([50, 60], 4);
console.log('grown :', view.length, JSON.stringify([...view]));
// Exceeding maxByteLength throws RangeError rather than silently truncating
try {
buffer.resize(32);
} catch (err) {
console.log('over max:', err.name);
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
initial: true len: 4 max: 16
grown : 8 [10,20,30,40,50,60,0,0]
over max: RangeErrorCode mechanics — Resizable ArrayBuffer Grows In Place
Top-level bindings buffer, view hold the demo state — nothing sits inside a function scope.
Caveats
- Everything it calls is documented as part of the language core.
Using it
Output messages include stage tags — initial:, grown :, over max: — when the file runs.
Key statements
const buffer = new ArrayBuffer(4, { maxByteLength: 16 });
const view = new Uint8Array(buffer);
view.set([10, 20, 30, 40]);
FAQ
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `buffer`, `view`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.