TypedArray in JavaScript

TypedArray in JavaScript

This article explains TypedArray in JavaScript.

We will explain in detail the basic concept of TypedArray, each type, how to use them, and specific use cases.

YouTube Video

TypedArray in JavaScript

TypedArray in JavaScript is an object for efficiently handling buffered binary data. TypedArray allocates and manipulates memory based on specific data types. Unlike regular arrays, TypedArray can hold only fixed-size binary data, not arbitrary data types.

The Basic Structure of TypedArray

The main components of a TypedArray are the ArrayBuffer and the TypedArray itself.

  • ArrayBuffer: A fixed-size buffer that allocates binary data in memory. This buffer is merely a data area and cannot be read from or written to directly.
  • TypedArray: A wrapper object that applies a specific data type to the buffer, enabling data access and manipulation.

Basic Usage Example

The following is an example of creating an ArrayBuffer and then creating a TypedArray based on it.

 1// Create a 16-byte buffer
 2const buffer = new ArrayBuffer(16);
 3
 4// Create a TypedArray (Uint8Array) to handle 8-bit unsigned integers
 5const uint8Array = new Uint8Array(buffer);
 6
 7// Set data
 8uint8Array[0] = 255;
 9uint8Array[1] = 128;
10
11// Retrieve data
12console.log(uint8Array[0]); // 255
13console.log(uint8Array[1]); // 128
  • In this example, an ArrayBuffer is created, and then a Uint8Array is made based on that buffer. Each element is treated as an 8-bit unsigned integer, storing values only within the specified range.

Types of TypedArray

There are different types of TypedArray for each data type. The main ones are as follows.

Type Name Size of Element Description
Int8Array 1 byte 8-bit signed integer
Uint8Array 1 byte 8-bit unsigned integer
Uint8ClampedArray 1 byte 8-bit unsigned integer (holds clamped values)
Int16Array 2 bytes 16-bit signed integer
Uint16Array 2 bytes 16-bit unsigned integer
Int32Array 4 bytes 32-bit signed integer
Uint32Array 4 bytes 32-bit unsigned integer
Float32Array 4 bytes 32-bit floating-point number
Float64Array 8 bytes 64-bit floating-point number

These TypedArrays are all memory efficient and are effective for handling large amounts of data.

Manipulating TypedArrays

You can access data in a TypedArray using indices, just like a regular array, but several special methods are also provided.

Setting values

In a TypedArray, you can assign multiple values at once using the set method.

1const buffer = new ArrayBuffer(8);
2const int16Array = new Int16Array(buffer);
3
4// Set values
5int16Array.set([10, 20, 30]);
6
7console.log(int16Array[0]); // 10
8console.log(int16Array[1]); // 20
9console.log(int16Array[2]); // 30
  • This code uses the set method to assign multiple values at once to an Int16Array, and displays each element in the console.

Getting a subarray

To obtain a part of a TypedArray as a subarray, use the subarray method. This references the same buffer as the original TypedArray.

1const int16Array = new Int16Array([1, 2, 3, 4, 5]);
2
3// Get a subarray containing elements from the 2nd to the 4th
4const subArray = int16Array.subarray(1, 4);
5
6console.log(subArray); // Int16Array [2, 3, 4]
  • This code retrieves a specified range of elements from an Int16Array using the subarray method and displays the subarray in the console.

Copying buffers

The buffer of a TypedArray can also be copied to another TypedArray. Using the set method, you can copy from a specified position.

1const srcArray = new Uint8Array([10, 20, 30, 40]);
2const destArray = new Uint8Array(4);
3
4// Copy
5destArray.set(srcArray);
6
7console.log(destArray); // Uint8Array [10, 20, 30, 40]
  • This code copies the contents of a Uint8Array to another array using the set method, and displays the copied array in the console.

Using DataView

While a TypedArray handles buffers with a fixed data type, DataView is an interface that allows flexible manipulation of binary data with arbitrary offsets and data types. This allows different types to be mixed within the same buffer.

 1const buffer = new ArrayBuffer(8);
 2const dataView = new DataView(buffer);
 3
 4// Write a 32-bit signed integer at offset 0
 5dataView.setInt32(0, 12345);
 6
 7// Write a 32-bit floating-point number at offset 4
 8dataView.setFloat32(4, 12.34);
 9
10console.log(dataView.getInt32(0)); // 12345
11console.log(dataView.getFloat32(4)); // 12.34000015258789
  • This code uses a DataView to write different types of data—32-bit integers and 32-bit floating-point numbers—onto the same buffer and checks the results.

  • DataView offers greater data access flexibility than TypedArray and is especially useful when working with binary format files or network protocols.

Use cases of TypedArray

TypedArray is mainly used for efficiently handling large amounts of binary data. Specific use cases include the following.

Image processing

TypedArray is used when manipulating pixel information of image data. Using Uint8Array, you hold the RGBA values of each pixel and perform image editing and processing.

 1const width = 100;
 2const height = 100;
 3const imageData = new Uint8Array(width * height * 4); // RGBA
 4
 5// Set pixel data
 6for (let i = 0; i < imageData.length; i += 4) {
 7    imageData[i] = 255;     // Red
 8    imageData[i + 1] = 0;   // Green
 9    imageData[i + 2] = 0;   // Blue
10    imageData[i + 3] = 255; // Alpha
11}
  • This code creates image data with a width of 100 and height of 100 in RGBA format using a Uint8Array, and sets all pixels to red.

Interfacing with WebAssembly

TypedArray is used for exchanging binary data between JavaScript and WebAssembly. By sharing the memory space of JavaScript and WebAssembly through ArrayBuffer, fast data exchange is possible.

Processing audio and video data

TypedArray plays an important role in processing audio and video. You can store audio data waveforms in Float32Array to perform playback and processing.

Conclusion

TypedArray is a powerful tool for efficiently handling large amounts of binary data. It is especially useful in performance-critical applications such as image processing, WebAssembly, and audio/video data processing. TypedArray has an API similar to regular arrays, but there are constraints regarding memory usage and data types, so proper differentiation in usage is required.

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