`ArrayBuffer` in JavaScript

`ArrayBuffer` in JavaScript

This article explains ArrayBuffer in JavaScript.

We will explain everything about ArrayBuffer, from the basics to its usage, related types, and practical applications.

YouTube Video

ArrayBuffer in JavaScript

JavaScript's ArrayBuffer is an object for handling low-level binary data and is particularly useful for manipulating binary data in WebAPIs, file operations, and network communications.

What is ArrayBuffer

ArrayBuffer is a data structure for handling fixed-length binary data. It allows handling raw binary data that cannot be handled by regular JavaScript arrays or objects.

ArrayBuffer itself cannot directly manipulate data. Instead, data is read and written using TypedArray or DataView based on an ArrayBuffer.

ArrayBuffer is especially useful in the following situations.

  • When processing binary data received from the network
  • When efficient data sharing in Web Worker is required.
  • When performing image processing or 3D rendering with Canvas or WebGL.
  • When manipulating files (especially binary files).

Creating an ArrayBuffer

First, let's start with how to create an instance of ArrayBuffer. ArrayBuffer allocates memory in byte units, so you specify its size at creation.

1const buffer = new ArrayBuffer(16); // Create a 16-byte buffer
2console.log(buffer.byteLength); // 16
  • In this example, a buffer of 16 bytes is allocated. This buffer does not contain any data yet.

Manipulating data with TypedArray

You cannot directly access an ArrayBuffer, so you use a TypedArray to read and write data. TypedArray provides different types of views such as Int8Array and Float32Array, enabling efficient access to binary data.

Example using Int8Array

1const buffer = new ArrayBuffer(8); // Create an 8-byte buffer
2const int8View = new Int8Array(buffer); // Create an Int8Array
3
4int8View[0] = 42; // Write data to the first byte
5console.log(int8View[0]); // 42
  • Int8Array can store data in each byte, allowing the buffer to hold 8 elements. In this way, by using different types of views, you can manipulate data efficiently.

Other TypedArray examples

JavaScript has various types of TypedArray. For example, if you want to handle 32-bit unsigned integers, you use Uint32Array.

1const buffer = new ArrayBuffer(16);
2const uint32View = new Uint32Array(buffer);
3
4uint32View[0] = 123456;
5console.log(uint32View[0]); // 123456
  • Uint32Array can store data in 4-byte units, so the buffer can hold four elements. It is important to choose the appropriate TypedArray based on the type of data you are handling.

Flexible data manipulation using DataView

TypedArray can only handle data of a fixed type, but by using DataView, you can write data of any type to any location. This is particularly useful when dealing with buffers that contain mixed data types.

 1const buffer = new ArrayBuffer(16);
 2const dataView = new DataView(buffer);
 3
 4// Write a 32-bit signed integer to byte 0
 5dataView.setInt32(0, 2147483647);
 6console.log(dataView.getInt32(0)); // 2147483647
 7
 8// Write a 16-bit unsigned integer to byte 4
 9dataView.setUint16(4, 65535);
10console.log(dataView.getUint16(4)); // 65535

Using DataView, you can specify a byte offset and read or write data of various types. This is very useful when handling complex binary structures like network protocols or file formats.

Consideration of Endianness

When using DataView, you also need to pay attention to endianness (byte order). Depending on the computer architecture, the order in which data is stored in memory can differ. DataView methods have options to specify the endianness.

1const buffer = new ArrayBuffer(4);
2const view = new DataView(buffer);
3
4// Write a 32-bit integer in little-endian format
5view.setInt32(0, 42, true); // true indicates little-endian
6console.log(view.getInt32(0, true)); // 42

If you do not specify the correct endianness, data may not be correctly interpreted in different environments, so it's especially important to be cautious in network communication or file operations.

Applications of ArrayBuffer

ArrayBuffer is a powerful tool often used in web development and browser APIs. Let's look at some examples of applications.

Receiving and Processing Binary Data

For example, you can retrieve binary data from a server using XMLHttpRequest or the fetch API and handle it as an ArrayBuffer.

1fetch('https://codesparklab.com/image.jpg')
2    .then(response => response.arrayBuffer())
3    .then(buffer => {
4        const view = new Uint8Array(buffer);
5        console.log(view);
6    });
  • In this example, image data is fetched from the server and handled as a Uint8Array. In this way, you can process data received from the server using ArrayBuffer.

Usage in WebGL

In WebGL, ArrayBuffer is used to efficiently handle binary data such as vertex data and color data.

 1const vertices = new Float32Array([
 2    -1.0, -1.0,
 3    1.0, -1.0,
 4    1.0,  1.0,
 5    -1.0,  1.0
 6]);
 7
 8// Send data to the WebGL buffer
 9const buffer = gl.createBuffer();
10gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
11gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  • In this example, Float32Array is used to define the vertex coordinates of a rectangle and send them to a WebGL buffer.

Memory Management and ArrayBuffer

ArrayBuffer manages memory at the byte level, making it very efficient, but you also need to be careful with memory management. When dealing with large binary data, it is important to properly release unused ArrayBuffers. Although JavaScript automatically performs garbage collection, if an ArrayBuffer continues to be referenced, it can cause memory leaks.

Summary

ArrayBuffer provides the foundation for binary data processing in JavaScript. By combining TypedArray and DataView, it is possible to handle binary data efficiently and flexibly. They are indispensable tools in web development, especially in many situations that involve handling binary data such as network communication and WebGL. By understanding them correctly and using them appropriately, you can improve performance and efficiency.

You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.

YouTube Video