UNB/ CS/ David Bremner/ teaching/ cs2613/ books/ mdn/ Reference/ Global Objects/ ArrayBuffer

The ArrayBuffer object is used to represent a generic raw binary data buffer.

It is an array of bytes, often referred to in other languages as a "byte array". You cannot directly manipulate the contents of an ArrayBuffer; instead, you create one of the typed array objects or a DataView object which represents the buffer in a specific format, and use that to read and write the contents of the buffer.

The ArrayBuffer() constructor creates a new ArrayBuffer of the given length in bytes. You can also get an array buffer from existing data, for example, from a Base64 string or from a local file.

ArrayBuffer is a transferable object.

Description

Resizing ArrayBuffers

ArrayBuffer objects can be made resizable by including the maxByteLength option when calling the ArrayBuffer() constructor. You can query whether an ArrayBuffer is resizable and what its maximum size is by accessing its resizable and maxByteLength properties, respectively. You can assign a new size to a resizable ArrayBuffer with a resize() call. New bytes are initialized to 0.

These features make resizing ArrayBuffers more efficient — otherwise, you have to make a copy of the buffer with a new size. It also gives JavaScript parity with WebAssembly in this regard (Wasm linear memory can be resized with WebAssembly.Memory.prototype.grow()).

Transferring ArrayBuffers

ArrayBuffer objects can be transferred between different execution contexts, like Web Workers or Service Workers, using the structured clone algorithm. This is done by passing the ArrayBuffer as a transferable object in a call to or . In pure JavaScript, you can also transfer the ownership of memory from one ArrayBuffer to another using its transfer() or transferToFixedLength() method.

When an ArrayBuffer is transferred, its original copy becomes detached — this means it is no longer usable. At any moment, there will only be one copy of the ArrayBuffer that actually has access to the underlying memory. Detached buffers have the following behaviors:

You can check whether an ArrayBuffer is detached by its detached property.

Constructor

Static properties

Static methods

Instance properties

These properties are defined on ArrayBuffer.prototype and shared by all ArrayBuffer instances.

Instance methods

Examples

Creating an ArrayBuffer

In this example, we create a 8-byte buffer with a Int32Array view referring to the buffer:

const buffer = new ArrayBuffer(8);
const view = new Int32Array(buffer);

Specifications

Browser compatibility

See also