/

Understanding the ArrayBuffer: What it is and how to use it

Understanding the ArrayBuffer: What it is and how to use it

In JavaScript, an ArrayBuffer is a data structure that represents a collection of bytes in memory. Similar to a Blob, which represents data available on disk, an ArrayBuffer serves as an opaque representation of bytes available in memory.

To create an ArrayBuffer, you need to provide its length in bytes as a parameter in the constructor. Here’s an example:

1
const buffer = new ArrayBuffer(64);

Once you have an ArrayBuffer, you can access its length in bytes using the byteLength property, which is read-only.

Additionally, the ArrayBuffer provides an instance method called slice(), which allows you to create a new ArrayBuffer from an existing one. This method takes a starting position and an optional length parameter. Here’s an example:

1
2
const buffer = new ArrayBuffer(64);
const newBuffer = buffer.slice(32, 8);

Downloading data from the internet and storing it as an ArrayBuffer can be done using the XHR (XMLHttpRequest) object. Here’s an example of a function that downloads a blob from the internet and stores it as an ArrayBuffer:

1
2
3
4
5
6
7
8
9
10
11
const downloadBlob = (url, callback) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'arraybuffer';

xhr.onload = () => {
callback(xhr.response);
};

xhr.send(null);
};

In summary, the ArrayBuffer is a powerful data structure in JavaScript that allows you to work with collections of bytes in memory. It’s particularly useful when dealing with binary data or when performing complex operations on data.

tags: [“ArrayBuffer”, “JavaScript”, “XHR”, “data structure”, “Blob”]