ArrayBuffer.transfer Moves Buffer Memory

Move an ArrayBuffer into a larger buffer with transfer, confirm the source detaches, and inspect the zero-filled tail.

JavascriptData Integrity

Code

javascriptsnippet
15 lines
const original = new ArrayBuffer(8);
const bytes = new Uint8Array(original);
bytes.set([1, 2, 3, 4], 0);

const moved = original.transfer(16);
const movedBytes = new Uint8Array(moved);

console.log('original length:', original.byteLength);
console.log('original detached:', original.detached);
console.log('moved length:', moved.byteLength);
console.log('first four:', Array.from(movedBytes.slice(0, 4)).join(','));
console.log('zero filled:', Array.from(movedBytes.slice(8)).every((value) => value === 0));

const empty = moved.transfer(0);
console.log('empty length:', empty.byteLength);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

original length: 0
original detached: true
moved length: 16
first four: 1,2,3,4
zero filled: true
empty length: 0

Inside the snippet

The file’s state is a handful of top-level bindings: original, bytes, moved, movedBytes.

Putting it to use

The run emits 6 labeled sections — original length:, original detached:, moved length:, first four:, zero filled:, empty length: — one per step.

Core lines

const movedBytes = new Uint8Array(moved);
const bytes = new Uint8Array(original);
const original = new ArrayBuffer(8);

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. Its state lives in module-level bindings: `original`, `bytes`, `moved`.