ArrayBuffer

'To achieve maximum flexibility and efficiency, JavaScript typed arrays split the implementation into buffers and views. A buffer (implemented by the ArrayBuffer object) is an object representing a chunk of data; it has no format to speak of and offers no mechanism for accessing its contents. To access the memory contained in a buffer, you need to use a view. A view provides a context — that is, a data type, starting offset, and number of elements — that turns the data into an actual typed array.' – MDNThe ArrayBuffer has the following properties and methods:

.length

.isView(arg)

.prototype.transfer([newByteLength]), .prototype.transferToFixedLength([newByteLength])

.prototype.byteLength

.prototype.slice()

.slice()


ArrayBuffer.isView();
ArrayBuffer.isView([]);
ArrayBuffer.isView({});
ArrayBuffer.isView(null);
ArrayBuffer.isView(undefined);
ArrayBuffer.isView(new ArrayBuffer(10));
ArrayBuffer.isView(new Uint8Array());
ArrayBuffer.isView(new Float32Array());
ArrayBuffer.isView(new Int8Array(10).subarray(0, 3));

var buffer = new ArrayBuffer(2);
var dv = new DataView(buffer);
ArrayBuffer.isView(dv);

false false false false false false true true true true

Added in ECMAScript 2024, .transfer([newByteLength]) detaches this buffer (so it becomes zero-length and unusable) and returns a new, independent ArrayBuffer holding the same bytes — optionally zero-padded or truncated to newByteLength — without copying the underlying memory. .transferToFixedLength() behaves the same, except the result is guaranteed to be a fixed-length buffer even if the source was resizable (see below).


var buf1 = new ArrayBuffer(8);
new Uint8Array(buf1)[0] = 42;

var buf2 = buf1.transfer(16);
console.log(buf1.detached);
console.log(buf1.byteLength);
console.log(buf2.byteLength);
console.log(new Uint8Array(buf2)[0]);   // the original byte survived the transfer

true 0 16 42

Also added in ECMAScript 2024, an ArrayBuffer can be created resizable by passing a maxByteLength option, letting its .byteLength grow or shrink in place (up to that cap) via .resize(newByteLength), without ever reallocating or copying — useful for streaming/growing buffers that previously required allocating a new, larger buffer and copying every time.


var buf = new ArrayBuffer(8, {maxByteLength: 16});
console.log(buf.resizable);
console.log(buf.maxByteLength);

buf.resize(16);
console.log(buf.byteLength);   // grown in place, same underlying allocation

true 16 16

var buf1 = new ArrayBuffer(8);
var buf2 = buf1.slice(0);
var buf3 = buf1.slice(2, 4);
console.log(buf3.byteLength);

2