ArrayBuffer
By Flavio Copes
Learn how JavaScript ArrayBuffer stores raw binary data, how to read it through typed arrays or DataView, slice it, resize it, and fetch binary data.
An ArrayBuffer represents a region of memory containing raw bytes.
You cannot read or write those bytes directly through the buffer. Create a typed array or DataView that views the same memory.
See the MDN ArrayBuffer reference for every property and method.
Create a fixed-length buffer by passing its size in bytes:
const buffer = new ArrayBuffer(64)
New bytes are initialized to zero. byteLength reports the current size:
buffer.byteLength //64
Read and write the bytes
Use a typed array when all values have the same numeric type:
const buffer = new ArrayBuffer(4)
const bytes = new Uint8Array(buffer)
bytes[0] = 255
bytes[0] //255
Use DataView when you need to read and write different numeric types or control byte order:
const buffer = new ArrayBuffer(4)
const view = new DataView(buffer)
view.setUint16(0, 500, true)
view.getUint16(0, true) //500
The buffer and its views share the same memory.
Copy part of a buffer
slice() copies bytes from a start index up to, but not including, an end index:
const buffer = new ArrayBuffer(64)
const newBuffer = buffer.slice(8, 32)
newBuffer.byteLength //24
The second argument is an end position, not a length. The MDN slice() reference documents negative indexes and omitted arguments.
Resizable and transferable buffers
You can opt into a resizable buffer by setting a maximum length:
const buffer = new ArrayBuffer(8, {
maxByteLength: 16
})
buffer.resize(12)
buffer.byteLength //12
transfer() moves the bytes to a new buffer and detaches the old one:
const moved = buffer.transfer()
moved.byteLength //12
buffer.byteLength //0
Resizable and transferable ArrayBuffers were added in ES2024. Check compatibility when supporting older browsers.
Downloading data from the internet as an ArrayBuffer
Use fetch() and Response.arrayBuffer() to download binary data:
const downloadBuffer = async url => {
const response = await fetch(url)
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`)
}
return response.arrayBuffer()
}
The returned promise fulfills with an ArrayBuffer. See the MDN arrayBuffer() reference for response and size errors.
Related posts about platform: