Example 1 — Move the Bytes and Detach the Original
Hand a finished buffer to a new owner, such as a Web Worker or a library. After the transfer the old reference can no longer read or change the bytes.
const original = new Uint8Array([1, 2, 3, 4]).buffer;
const moved = original.transfer();
console.log(moved.byteLength); // 4
console.log(JSON.stringify(Array.from(new Uint8Array(moved)))); // [1,2,3,4]
console.log(original.byteLength); // 0
console.log(original.detached); // true How It Works
- Move instead of copy.
transfer()createsmovedwith the same 4 bytes; the engine may reuse the memory rather than copy it. - The old handle is emptied.
originalnow reportsbyteLength0 anddetachedastrue. - One owner at a time. Only
movedcan reach the data, which stops two parts of a program from editing the same bytes by accident.

