Javascript - Collection Typed Arrays

Introduction

Typed arrays in ES6 provide an efficient way for accessing and manipulating binary data.

The typed array has a buffer and a view.

  • A buffer is an object that represents a chunk of data. We can't directly manipulate the contents of a buffer.
  • View is used to access the memory contained in the buffer. A view enables us to read and write the data content of the buffer.

The typed arrays have two separate classes: ArrayBuffer and DataView.

The ArrayBuffer contains the data and the DataView provides a view for the data.

The following code creates an ArrayBuffer and a specific DataView to handle its data:

const buffer = new ArrayBuffer(16); 
const int32View = new Int32Array(buffer); 

for (let i = 0; i < int32View.length; i++) { 
    int32View[i] = i * 2; 
} 
console.log(int32View); // [0, 2, 4, 6] 

Typed array views provide views for all the usual numeric types like Int8, Uint32, Float64, etc.

The following table lists all the types and their respective size.

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

The Uint8ClampedArray typed array represents an array of 8-bit unsigned integers clamped to 0-255.

If you specify a value that is out of the range of [0,255], 0 or 255 will be set instead.

If you specify a non-integer, the nearest integer will be set.

Related Topics