JavaScript ArrayBuffer.prototype.transfer() Method

The transfer() method of ArrayBuffer create a new ArrayBuffer that has the same byte content as the current buffer, then detach this current buffer, this means that merely the fresh buffer is able to get at the buried data and not any else.

Such an option as transfer() comes in handy when there is a need to shift ArrayBuffers ownership between diverse contexts like from the main thread into Web Workers, additionally, it may make possible for better use of memory through reallocating more or less space within a new buffer without having an impact on old one.

Syntax

transfer()
transfer(newByteLength)

Parameters:

  • newByteLength: (Optional) Specifies the byte length of the new ArrayBuffer, if not provided it defaults to the byte length of the original ArrayBuffer.

Return Type:

A new ArrayBuffer object with the content of the original buffer and potentially resized based on the newByteLength parameter.

Example 1: In the given below example we are transferring an ArrayBuffer.

JavaScript
const buffer = new ArrayBuffer(8);
const view = new Uint8Array(buffer);
view[1] = 2;
view[7] = 4;

const newBuffer = buffer.transfer();
console.log(newBuffer.byteLength); 

Output:

8

Example 2: In the given below example we are transferring to a Smaller ArrayBuffer.

JavaScript
const buffer = new ArrayBuffer(8);
const view = new Uint8Array(buffer);
view[1] = 2;
view[7] = 4;

const smallerBuffer = buffer.transfer(4);
console.log(smallerBuffer.byteLength); 

Output:

4

Contact Us