JavaScript TypedArray

JavaScript TypedArray with Examples

In this article, I am going to discuss JavaScript TypedArray with Examples. Please read our previous article where we discussed JavaScript Symbols with Examples. TypedArray is the new feature introduced in JavaScript ES6 for handling binary data. When working on web-development we meet binary data mostly while dealing with files (create, upload, download, and delete). Another use is in image processing.

Nowadays web application has become more interactive by adding features such as video streaming, high graphics images, and web socket messenger all that has been handled by JavaScript easily with the help of TypedArray this is where the typed array comes in and play a vital role. That’s all possible in JavaScript, as it contains many classes. Such as

  1. ArrayBuffer,
  2. Uint8Array,
  3. DataView,
  4. Blob,
  5. File, etc.

The ArrayBuffer is a basic binary object – contains a fixed-length contiguous memory area. This assigns a memory area of 16 bytes and fills it with zeroes in advance.

Note: Please note that ArrayBuffer and array are different and they don’t have anything in common.

Different ways to show binary data in the browser:

JavaScript has two ways to show binary data in the browser.

ArrayBuffers/TypedArrays contain mutable i.e.: can be changed (though still fixed-length) binary data which we can directly modify. Whereas Blobs contain immutable (i.e.: cannot be changed) binary data which can only be accessed through the asynchronous File interface.

Two types of objects work together in the Typed Array API:

  1. Buffers: it is an Instances of ArrayBuffer that holds the binary data.
  2. Views: It provides the methods for accessing the binary data.
There are two types of views:
  1. An instance of a Typed Array constructor (Uint8Array, Float64Array, etc.) works the same as a normal Array, but only allows a single type for its elements
  2. An instance of DataView allows us to access data at the specified location i.e.: at any byte offset in the buffer, and interprets that data as one of several types (Uint8, Float64, etc.).

Below is the diagram that depicts the structure of typedArray where all typedArray contains the superclass ArrayBuffer.

JavaScript ArrayBuffer with Examples

Typed arrays are array-like objects that provide a technique for reading and writing raw binary data in memory buffers. But before we dive into typed arrays, we have to get into ArrayBuffers.

Array Buffer in JavaScript

An ArrayBuffer is an object representing a piece of fixed-length binary data; it offers no technique for accessing its contents, it’s just an array of bytes.

  • Arraybuffer is actual storage for the bytes which is used for binary data transfers between server and client.
  • To work on binary data or start with, ArrayBuffer is the core root object of everything.
  • It’s just an array of bytes.
  • It has got a fixed length; it can’t be modified.
  • It doesn’t take extra space rather it takes exactly that much space in the memory.
  • The contents of an ArrayBuffer cannot be directly modified and can only be accessed through a DataView Object or one of the typed array objects.
  • A single ArrayBuffer can have more than one DataView or typed array objects attached to it and any changes to one object can be easily seen by the other object’s view.
  • The following are the typed arrays:

Float32Array, Float64Array, Int8Array, Int16Array, Int32Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array.

  • To access/read the content of Arraybuffer and to perform any operation (write or iterate) on ArrayBuffer, we need to use a View (TypedArray and DataViews).
  • Reading and writing values into ArrayBuffer can be done using DataView.
  • To access the ArrayBuffer data, two kinds of View are used.
    • Typed Arrays (Uint8Array, Int16Array, Float32Array, etc.) explain the ArrayBuffer as an indexed sequence of elements of a single type. These are mappings of whether the bits should be viewed as an array of 8-bit signed integers, 16-bit signed integers which are already given in the below table for types of the typedArray.
    • Instances of DataView allow us to access data as elements of several types (Uint8, Int16, Float32, etc.), at the specified location i.e.: at any byte offset inside an ArrayBuffer.
  • The view object is nothing but the mirror reflection that represents the bytes stored in the Arraybuffer.
  • Create an ArrayBuffer bypassing its number of bytes to it.
  • In order to create a DataView, we need to provide its constructor with an ArrayBuffer.
  • Typed Array constructors can optionally create an ArrayBuffer for us.

Before understanding about View and how it stored bytes let’s gather some basic info about bytes and bits and how does it get stored in a memory.

What is Bit?

A Bit is the basic unit in computer language and has only two different values, generally defined as a 0 or 1. These values can be translated as on or off, yes or no, true or false, etc. It just depends on the binary code.

What is a Byte?

A Byte is just 8 Bits and is the smallest unit of memory that can be addressed in many computer systems. The following list shows the relationship between all of the different units of data

How view stored byte?

Array Buffer in JavaScript

As we know to manipulate ArrayBuffer we need to use View. A view is an eyeglass that provides information about that is, a data type, and the number of elements or the bytes stored in the Arraybuffer.

For example
  1. Uint8Array – treats every byte in ArrayBuffer as a separate number, with possible values from 0 to 255 (one byte is equal to 8 bites, so it can hold only that much). A value like this is known as an “8-bit unsigned integer”.
  2. Uint16Array – treats every 2 bytes like an integer, with possible values from 0 to 65535. This is known as a “16-bit unsigned integer”.
  3. Uint32Array – treats every 4 bytes like an integer, with possible values from 0 to 4294967295. This is known as a “32-bit unsigned integer”.
  4. Float64Array – treats every 8 bytes like a floating-point number with possible values from 5.0×10-324 to 1.8×10308.

So, the binary data in an ArrayBuffer of 16 bytes can be translated as 16 “tiny numbers”, or 8 bigger numbers (2 bytes each), or 4 even bigger (4 bytes each), or 2 floating-point values with high precision (8 bytes each).

Which depicts in the below diagram:

JavaScript ArrayBuffer with Examples

ArrayBuffer Constructor in JavaScript

Syntax: new ArrayBuffer(length : number)

Calling this constructor using a new operator creates an instance of ArrayBuffer with specified length bytes. Where each byte starts as 0. When calling an ArrayBuffer constructor as a function without new will throw a TypeError. ArrayBuffer can be generated in the following way.

Example: JavaScript ArrayBuffer Creation
<html>
<head>
    <title>JavaScript ArrayBuffer Creation example</title>
</head>
<body>
    <script>
        var buffer = new ArrayBuffer(16);
        console.log('The length of ArrayBuffer is  :', buffer.byteLength);// 16
    </script>
</body>
</html>

Output: The length of ArrayBuffer is : 16

Example: JavaScript ArrayBuffer object example
<html>
<head>
    <title>JavaScript ArrayBuffer object example</title>
</head>
<body>
    <script>
        // create an ArrayBuffer with a size in bytes/length 8
        var buffer = new ArrayBuffer(12);

        //Create a DataView referring to the buffer
        var dataView = new DataView(buffer);

        //Create a Int8Array view referring to the buffer
        var int8View = new Int8Array(buffer);

        //Put value of 32bits
        dataView.setInt32(0, 0x1234ABCD);

        //prints the 32bit value
        console.log('DataView 32 bit value: ', dataView.getInt32(0).toString(16));

        //prints only 8bit value
        console.log('DataView 8 bit value :', dataView.getInt8(0).toString(16));
        console.log('Int8Array 8 bit value :', int8View[0].toString(16));
    </script>
</body>
</html>

Output:

JavaScript ArrayBuffer object example

ArrayBuffer methods in JavaScript

ArrayBuffer IsView:

This method is used to check whether the given argument/passed values for the method is an instance of a TypedArray or of DataView. Returns true if given argument(arg) is a typedArray and a view of ArrayBuffer otherwise false.

Syntax: ArrayBuffer.isView(arg)

Example: JavaScript working of ArrayBuffer.isView() function
<html>
<head>
    <title>JavaScript working of ArrayBuffer.isView() function example</title>
</head>
<body>
    <script>
        // Creation of ArrayBuffer having a size in bytes
        var buffer = new ArrayBuffer(12);

        // Use of ArrayBuffer.isView function
        isView1 = ArrayBuffer.isView(new Int32Array())
        console.log('Is isView1 a typed array :', isView1)

        // Creation of ArrayBuffer having a size in bytes
        var buffer1 = new ArrayBuffer(10);
        const dv = new DataView(buffer1);
        isView2 = ArrayBuffer.isView(dv); // true

        isView3 = ArrayBuffer.isView();                    // false
        isView4 = ArrayBuffer.isView([]);                  // false
        isView5 = ArrayBuffer.isView({});                  // false
        isView6 = ArrayBuffer.isView(null);                // false
        isView7 = ArrayBuffer.isView(undefined);           // false
        isView8 = ArrayBuffer.isView(new ArrayBuffer(18)); // false

        isView9 = ArrayBuffer.isView(new Uint16Array());    // true
        isView10 = ArrayBuffer.isView(new Float64Array());  // true

        console.log('Is isView2 a typed array :', isView2)
        console.log('Is isView3 a typed array :', isView3)
        console.log('Is isView4 a typed array :', isView4)
        console.log('Is isView5 a typed array :', isView5)
        console.log('Is isView6 a typed array :', isView6)
        console.log('Is isView7 a typed array :', isView7)
        console.log('Is isView8 a typed array :', isView8)
        console.log('Is isView9 a typed array :', isView9)
        console.log('Is isView10 a typed array :', isView10)
    </script>
</body>
</html>

Output:

JavaScript working of ArrayBuffer.isView() function

In the above code sample as we can see some isView output as true because they are typed array whereas other arguments are not typed array hence output as false.

ArrayBuffer Slice

Syntax: ArrayBuffer.prototype.slice(begin,end)

Returns a new ArrayBuffer with a copy of this ArrayBuffer based on the start and end index provided. Begin starts slicing (means making small pieces) at zero-base index byte. And the slicing finished at the end index. If the end is not provided then the new ArrayBuffer will contain all the contents from the beginning to the end of this ArrayBuffer. If the end provided is negative it will begin the slicing from the last index.

Example: JavaScript working of ArrayBuffer.slice method example
<html>
<head>
    <title>JavaScript working of ArrayBuffer.slice method example</title>
</head>
<body>
    <script>
        // create an ArrayBuffer with a size in bytes
        const buffer = new ArrayBuffer(8);

        const int32View = new Int32Array(buffer);
        // produces Int32Array [0, 0, 0, 0]

        int32View[1] = 22;
        const sliced = new Int32Array(buffer.slice(4, 8));
        // produces Int32Array [22, 0]

        console.log('The new Sliced ArrayBuffer is :',sliced[0]);//22
    </script>
</body>
</html>

Output: The new Sliced ArrayBuffer is : 22

ArrayBuffer properties

ArrayBuffer byte Length

Syntax: ArrayBuffer.prototype.byteLength

An ArrayBuffer length can be checked with the.byteLength property. which gives the length of ArrayBuffer in bytes. If the ArrayBuffer length given infraction then it will return the whole number, also it will return zero length if the Arraybuffer length given in string form. It is used for checking the size of an ArrayBuffer.

Example: JavaScript working of ArrayBuffer.byteLength property
<html>
<head>
    <title>JavaScript working of ArrayBuffer.byteLength property example</title>
</head>
<body>
    <script>
        // create an ArrayBuffer with a size in bytes
        const buffer = new ArrayBuffer(14);

        // use byteLength to check the size
        const bytes = buffer.byteLength;
        console.log('The length of an ArrayBuffer in bytes :', bytes);//14

        const bufferFraction = new ArrayBuffer(8.5);

        const bytesFraction = bufferFraction.byteLength;
        console.log('The fraction length of an ArrayBuffer in bytes :', bytesFraction);//8

        const bufferString = new ArrayBuffer('abc');

        const bytesString = bufferString.byteLength;
        console.log('The string form length of an ArrayBuffer in bytes :', bytesString);//0
    </script>
</body>
</html>

Output:

JavaScript working of ArrayBuffer.byteLength property

Typed Arrays in JavaScript

TypedArray is the new feature introduced in JavaScript ES6 for handling binary data.

    • Typed arrays are array-like objects that provide a technique for reading and writing raw binary data in memory buffers.
    • Typed arrays have self-descriptive names. Typed Array is like mirror reflection View and not actual Arrays.
    • A TypedArray illustrates an array-like view of the binary data buffer.
    • They are like buckets to showcase a view of different types of the array such as ArrayBuffer, Int8Array, Uint8Array, and so on.
    • Typed arrays function the same as regular arrays: they have indexed and are iterable.
    • All the typed arrays are constructors that require the use of the new operator
    • When we create an instance of a Typed array which in turn creates a corresponding ArrayBuffer inside the memory automatically, this is the place where the elements get stored.
    • The various kinds of Typed Array are only different with respect to the type of their elements:
      • Typed Arrays whose elements are integers: Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array
      • Typed Arrays whose elements are floats: Float32Array, Float64Array

There are different types of TypedArray shown below with their range, size, web IDL Type, Equivalent C Type:

Typed Arrays in JavaScript

Typed Array Constructor in JavaScript

All the typed arrays are constructors that need the use of the new operator. Each Typed Array constructor has a name that follows the pattern «ElementType»Array, where «ElementType» is one of the element types explained in the table at the beginning. That means that there are 9 constructors for Typed Arrays: Int8Array, Uint8Array, Uint8ClampedArray (element type Uint8C), Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array.

Each constructor has five overloaded versions – it behaves differently depending on how many arguments it receives and what their types are:

Syntax of 5 overloaded versions of Each Constructor:

new TypedArray(buffer, [byteOffset], [length]); //or new «ElementType»Array(buffer, byteOffset = 0, length ?): Creates a new Typed Array whose Arraybuffer is buffer. It starts accessing the buffer at the provided byteOffset to start from (0 by default) and will have the given length (till the end of the buffer by default). Note that length counts the number of elements of the Typed Array

new TypedArray(length); //or new «ElementType»Array(length): Creates a Typed Array with the given length and the appropriate buffer whose size/length in bytes is length * «ElementType»Array.BYTES_PER_ELEMENT. That is length multiplied by the numbers of bytes in a single item.

new TypedArray(); //or new «ElementType»Array(): Without arguments, creates a Typed Array whose length is 0. It also creates a linked empty ArrayBuffer.

new TypedArray(typedArray); //or new «ElementType»Array(typedArray): If another TypedArray is passing as an argument, create a new Typed Array that has the same length and elements as a typed array. If needed, values are converted appropriately to the new type in the process.

new TypedArray(object); //or new «ElementType»Array(arrayLikeObject): If an array or any array-Like Object provided as an argument treats arrayLikeObject like an Array and creates a new TypedArray that has the same length and elements. If needed, values are converted appropriately to the new type in the process.

Example: 5 Overloaded versions of each constructor.
<html>
<head>
    <title>JavaScript TypedArray 5 overloaded version of Each Constructor for creating the same Typed Array example</title>
</head>
<body>
    <script>
        // create an ArrayBuffer with a size in bytes
        //1-new TypedArray(buffer, [byteOffset], [length]);
        const buffer = new ArrayBuffer(12);

        var typedArray1 = new Uint8Array(buffer, 0);
        // Make view of 5th to 7th bytes of the buffer
        var x1 = new Uint8Array(buffer, 4, 2);

        typedArray1[4] = 40;
        console.log('Creating TypeArray using buffer :', x1[0]); // x1 is a live view on the buffer

        //2- create a TypedArray with a size in byte- new TypedArray(length);
        const typedArray2 = new Int8Array(8);
        typedArray2[0] = 33;

        //3-new TypedArray(typedArray);
        const typedArray3 = new Int8Array(typedArray2);
        typedArray3[1] = 44;

        //4-new TypedArray(object);
        const typedArray4 = new Int8Array([1, 2, 3, 4, 5, 6]);

        //5-new TypedArray();
        const typedArray5 = new Int8Array();

        console.log('Creating TypeArray using length :', typedArray2);//[33, 0, 0, 0, 0, 0, 0, 0]
        console.log('Creating TypeArray using typedArray :', typedArray3);//[33, 44, 0, 0, 0, 0, 0, 0]
        console.log('Creating TypeArray using array-like object :', typedArray4);//[1, 2, 3, 4, 5, 6]
        console.log('Creating TypeArray using without argument :', typedArray5);//[0, 0, 0, 0, 0, 0, 0, 0]
    </script>
</body>
</html>

Output:

JavaScript TypedArray with Examples

Typed Array Methods in JavaScript

TypedArray methods in JavaScript are the same as the normal arrays. There are also methods that are specific to typed arrays. Such as .slice(), .subarray() and .set()

copyWithin()

Syntax: TypedArray.prototype.copyWithin(target : number, start : number, end = this.length)

This Copies the elements whose indices are between start (including) and end (excluding) to the index or position starting at target. This method copies a portion of an array to another location in the same array at the position defined at the target and returns the size without modification.

Example: JavaScript TypedArray.copyWithin() method example
<html>
<head>
    <title>JavaScript TypedArray.copyWithin() method example</title>
</head>
<body>
    <script>
        const uint8 = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);

        // (insert position, start position, end position)
        uint8.copyWithin(3, 1, 3);

        console.log('TypedArray using copyWithin() method :', uint8);//Uint8Array [1, 2, 3, 2, 3, 6, 7, 8]
    </script>
</body>
</html>

Output:

JavaScript TypedArray.copyWithin() method example

JavaScript TypedArray entries() Method:

Syntax: TypedArray<T>.prototype.entries() : Iterable<[number, T]>

This method returns a new Array Iterator object that contains [index, element] pairs this typed array

Example: JavaScript TypedArray.entries() method example
<html>
<head>
    <title>JavaScript TypedArray.entries() method example</title>
</head>
<body>
    <script>
        const uint8 = new Uint8Array([10, 20, 30, 40, 50]);
        const eArr = uint8.entries();
        
        console.log('TypedArray using entries() method 1:', eArr.next());//Array [1, 10]
        console.log('TypedArray using entries() method 2:', eArr.next().value);//Array [2, 20]
        console.log('TypedArray using entries() method 3:', eArr.next().value);//Array [3, 30]
    </script>
</body>
</html>

Output:

JavaScript TypedArray.entries() method example

JavaScript TypedArray slice() Method:

Syntax: TypedArray<T>.prototype.slice(start = 0, end = this.length) : TypedArray<T>

Create a new Typed Array that only has the elements of the original TypedArray whose indices are between start (including) and end (excluding). If the start is undefined, the slice begins from index 0. If the end is omitted, slice extracts till the end of the sequence but not include end i.e.: end-1. The slice method doesn’t modify it just returns the shallow copy of an item from its original TypedArray.

Example: JavaScript TypedArray.slice() method example
<html>
<head>
    <title>JavaScript TypedArray.slice() method example</title>
</head>
<body>
    <script>
        const uint8 = new Uint8Array([10, 20, 30, 40, 50, 60, 70, 80]);
        const array1 = uint8.slice(1, 4);
        const array2 = uint8.slice(3);
        const array3 = uint8.slice(2);
        console.log('The SliceArray item from index 1 to 4 :', array1);//Uint8Array [20, 30, 40]
        console.log('The SliceArray item from index 3 to end :', array2);//Uint8Array [40, 50, ...]
        console.log('The SliceAarray item from index 2 to end :', array3);//Uint8Array [30, 40, ...]
    </script>
</body>
</html>

Output:

JavaScript TypedArray.slice() method example

JavaScript TypedArray subarray() Method:

Syntax: TypedArray<T>.prototype.subarray(begin=0, end=this.length) : TypedArray<T>

The method returns a new TypedArray on this ArrayBuffer as a view and it doesn’t change the original TypedArray. The begin item is included and the end item is excluded. It will take the item from begin to end-1 and return in new TypedArray. If the end is not specified then the original TypedArray length is used.

Example: JavaScript TypedArray.subarray() method example
<html>
<head>
    <title>JavaScript TypedArray.subarray() method example</title>
</head>
<body>
    <script>
        var buffer = new ArrayBuffer(8);
        var uint8 = new Uint8Array(buffer);
        uint8.set([1, 2, 3, 4, 5, 6, 7, 8]);

        const array1 = uint8.subarray(1, 3);
        const array2 = uint8.subarray(3);
        console.log('The SubArray item from index 1 to 3 :', array1);//Uint8Array [2, 3]
        console.log('The SubArray item from index 3 to end :', array2);//Uint8Array [4, 5, 6, 7, 8]
    </script>
</body>
</html>

Output:

JavaScript TypedArray.subarray() method example

JavaScript TypedArray set() Method:

Syntax: TypedArray<T>.prototype.set(arrayOrTypedArray, offset = 0) : void

This method is used to store values into the TypedArray at a specified location i.e.: Offset and then reading the stored values from the specified array. If Offset is not provided then by default it will start at index 0. If arrayOrTypedArray is a normal Array, its elements are converted to numbers who are then converted to the element any type T of this Typed Array. If arrayOrTypedArray is a Typed Array then each of its elements is converted directly to the appropriate type for this Typed Array. If both Typed Arrays have the same element type then faster, byte-wise copying is used.

Example: JavaScript TypedArray.set() method example
<html>
<head>
    <title>JavaScript TypedArray.set() method example</title>
</head>
<body>
    <script>
        // create an ArrayBuffer with a size in bytes
        const buffer = new ArrayBuffer(10);
        const uint8 = new Uint8Array(buffer);

        // Copy the values into the array starting at index 3
        uint8.set([1, 2, 3], 3);

        console.log('The set value of Uint8Array at index 3 :', uint8);//Uint8Array [0, 0, 0, 1, 2, 3, 0, 0, 0, 0]
        console.log('The set value of Uint8Array at index 3, 4, and 5:', uint8[3], uint8[4], uint8[5]);//Uint8Array [1, 2, 3]

        // Copy the values into the array without specifying index at 0 by default
        uint8.set([10, 20, 30]);
        console.log('The set value of Uint8Array without index at 0 by default :', uint8);//Uint8Array [10, 20, 30, 1, 2, 3, 0, 0, 0, 0]
        console.log('The set value of Uint8Array at index 0, 1, and 2:', uint8[0], uint8[1], uint8[2]);//Uint8Array [10, 20, 30]
    </script>
</body>
</html>

Output:

JavaScript TypedArray.set() method example

As typedArray has regular Array method such as copyWithin(), entries(), every(), fill(), filter(), find(), findIndex(), forEach(), includes(), indexof(), join(), Keys(), lastIndexof(), map(), reduce(), reduceRight(), reverse(), set(), Slice(), some(), sort(), subarray(), values(), toLocalString(), and toString(). These are the methods that we will cover in the Array chapter.

JavaScript Typed Array Properties

The following properties are specific to Typed Arrays, normal Arrays don’t have them:

Typed Array buffer

Syntax: TypedArray.prototype.buffer

The buffer property represents the ArrayBuffer referenced by a TypedArray at the time of construction. Returns the underlying buffer for this Typed Array.

Example: JavaScript TypedArray.buffer property example
<html>
<head>
    <title>JavaScript TypedArray.buffer property example</title>
</head>
<body>
    <script>
        // create an ArrayBuffer with a size in bytes
        const buffer = new ArrayBuffer(8);
        const uint16 = new Uint16Array(buffer);

        console.log('TypeArray using TypedArray.buffer property :', uint16.buffer);// 8
    </script>
</body>
</html>

Output:

JavaScript TypedArray.buffer property example

Typed Array byte Length

Syntax: TypedArray.prototype.byteLength

Returns the length or size in bytes of this Typed Array’s buffer. If Typed Array doesn’t specify the length then the length of the referenced ArrayBuffer will be returned.

Example: JavaScript TypedArray.byteLength property example
<html>
<head>
    <title>JavaScript TypedArray.byteLength property example</title>
</head>
<body>
    <script>
        var buffer = new ArrayBuffer(8);

        var uint8 = new Uint8Array(buffer);
        console.log('The byteLength of the TypedArray buffer :', uint8.byteLength);// 8

        var uint8 = new Uint8Array(buffer, 1, 6);
        console.log('The byteLength of the TypedArray buffer as specified when constructing the Uint8Array :', uint8.byteLength);// 6

        var uint8 = new Uint8Array(buffer, 3);
        console.log('The byteLength of the TypedArray buffer due to the offset of the constructed Uint8Array :', uint8.byteLength);// 5
    </script>
</body>
</html>

Output:

JavaScript TypedArray.byteLength property example

Typed Array byte Offset

Syntax: TypedArray.prototype.byteOffset

Returns the offset i.e.: location from where this Typed Array “starts” reading inside its ArrayBuffer. If no offset is specified it will start from 0 by default.

Example: JavaScript TypedArray.byteOffset property example
<html>
<head>
    <title>JavaScript TypedArray.byteOffset property example</title>
</head>
<body>
    <script>
        var buffer = new ArrayBuffer(8);

        var uint8 = new Uint8Array(buffer);
        console.log('The byteOffset of this TypedArray buffer when no offset specified :', uint8.byteOffset);// 0

        var uint8 = new Uint8Array(buffer, 4);
        console.log('The byteOffset of this TypedArray buffer as specified when constructing Uint8Array :', uint8.byteOffset);// 4

        var uint8 = new Uint8Array(buffer, 5, 2);
        console.log('The byteOffset of this TypedArray buffer as specified when constructing Uint8Array with length :', uint8.byteOffset);// 5
    </script>
</body>
</html>

Output:

JavaScript TypedArray.byteOffset property example

Type Array BYTES_PER_ELEMENT

Syntax: ElementType»Array.BYTES_PER_ELEMENT

Counts how many bytes are needed to store a single element. In other words, it represents the size in bytes of each item in a typed array.

Example: JavaScript TypedArray.BYTES_PER_ELEMENT property example
<html>
<head>
    <title>JavaScript TypedArray.BYTES_PER_ELEMENT property example</title>
</head>
<body>
    <script>
        console.log('The size in bytes of each element in Int8Array :', Int8Array.BYTES_PER_ELEMENT);// 1
        console.log('The size in bytes of each element in Uint8Array :', Uint8Array.BYTES_PER_ELEMENT);// 1
        console.log('The size in bytes of each element in Uint8ClampedArray :', Uint8ClampedArray.BYTES_PER_ELEMENT);// 1
        console.log('The size in bytes of each element in Int16Array :', Int16Array.BYTES_PER_ELEMENT);// 2
        console.log('The size in bytes of each element in Uint16Array :', Uint16Array.BYTES_PER_ELEMENT);// 2
        console.log('The size in bytes of each element in Int32Array :', Int32Array.BYTES_PER_ELEMENT);// 4
        console.log('The size in bytes of each element in Uint32Array :', Uint32Array.BYTES_PER_ELEMENT);// 4
        console.log('The size in bytes of each element in Float32Array :', Float32Array.BYTES_PER_ELEMENT);// 4
        console.log('The size in bytes of each element in Float64Array :', Float64Array.BYTES_PER_ELEMENT);// 8
    </script>
</body>
</html>

Output:

JavaScript TypedArray.BYTES_PER_ELEMENT property example

Typed Array length

Syntax: TypedArray.length

It represents the number of elements of a typed array.

Example: JavaScript TypedArray.length property example
<html>
<head>
    <title>JavaScript TypedArray.length property example</title>
</head>
<body>
    <script>
        var buffer = new ArrayBuffer(8);

        var uint8 = new Uint8Array(buffer);
        console.log('The length of the buffer :', uint8.length);// 8

        var uint8 = new Uint8Array(buffer, 1, 6);
        console.log('The length of the buffer as specified when constructing the Uint8Array :', uint8.length);// 6

        var uint8 = new Uint8Array(buffer, 3);
        console.log('The length of the buffer due to the offset of the constructed Uint8Array :', uint8.length);// 5
    </script>
</body>
</html>

Output:

JavaScript TypedArray.length property example

Typed Array name

Syntax: TypedArray.name

It represents the typed array constructor name in a string value. The name property describes what data type the array consists of. The first section can be Int for “integer” or Uint for an “unsigned integer”, also Float for “floating point” is used. A second section is a number describing the bit-size of the array. Finally, the object type is Array, with ClampedArray as a special case

Example: JavaScript TypedArray.name property example
<html>
<head>
    <title>JavaScript TypedArray.name property example</title>
</head>
<body>
    <script>
        console.log('The data type of Int8Array :', Int8Array.name);// Int8Array
        console.log('The data type of Uint8Array :', Uint8Array.name);// Uint8Array
        console.log('The data type of Uint8ClampedArray :', Uint8ClampedArray.name);// Uint8ClampedArray
        console.log('The data type of Int16Array :', Int16Array.name);// Int16Array
        console.log('The data type of Uint16Array :', Uint16Array.name);// Uint16Array
        console.log('The data type of Int32Array :', Int32Array.name);// Int32Array
        console.log('The data type of Uint32Array :', Uint32Array.name);// Uint32Array
        console.log('The data type of Float32Array :', Float32Array.name);// Float32Array
        console.log('The data type of Float64Array :', Float64Array.name);// Float64Array
    </script>
</body>
</html>

Output:

JavaScript TypedArray.name property example

Typed Array V/s normal Arrays in JavaScript

Typed arrays are not Arrays though typed arrays are very similar to arrays there are some important differences.

Typed Arrays are the same as normal Arrays, they have a length, elements can be accessed through the bracket operator [ ] and they have all of the standard Array methods. They differ from Arrays in the following ways:

    • Just like regular arrays, typed arrays have a length, elements can be accessed via the bracket operator [ ].
    • All of their elements have the same type, setting the elements converts values to that type.
    • They are contiguous. Normal Arrays can have potholes (indices in the range (0, to arr.length) that have no mapped element), Typed Arrays can’t.
    • Initialized with zeros. This is a consequence of the previous item:
      • new Array(10) creates a normal Array without any elements (it only has holes).
      • new Uint8Array(10) creates a Typed Array whose 10 elements are all 0.
    • An associated buffer. The elements of a Typed Array (ta) are not stored in (ta), they are stored in a linked ArrayBuffer that can be accessed via ta.buffer.
    • Some differences are that typed arrays are of fixed length and the values are of the same type.
    • Typed arrays (well actually the ArrayBuffers) only store numbers. Adding anything that is not a number to TypedArray will return NaN (Not a Number)

Array.isArray(uint8)//false

Or check with typedarray instanceof Array

uint8 instanceof Array //🌶 false Remember: typed array is not an Array

uint8 instanceof Uint8Array // ✅true

Most of the usual Array methods work

As typed arrays are of fixed length, array mutating methods like splice(), .concat(), .push() and .unshift() are not methods of typed arrays.

Typed Arrays are iterable in JavaScript

Typed Arrays in JavaScript implement an inbuilt method whose key is Symbol.iterator and are therefore iterable. That means that you can use the for-of loop and similar mechanisms in ES6:

JavaScript ES6 provides for…of the loop that works with the iterable objects.

Note: ArrayBuffers and DataViews are not iterable.

Example: Typed array iterable using for…of the loop and [Symbol.iterator]
<html>
<head>
    <title>JavaScript Typed array iterating using for...of loop example</title>
</head>
<body>
    <script>
        //Typed array iterating using for...of loop
        var ui8Arr = new Uint8Array([1, 2, 3, 4, 5]);
        for (let n of ui8Arr) {
            console.log('The element of Uint8Array is using for..of loop :', n);
        }

        //Alternative typed array iteration using [Symbol.iterator]
        var arr = new Uint8Array([1, 2, 3, 4, 5]);
        var eArr = arr[Symbol.iterator]();
        console.log('The element of Uint8Array is using [Symbol.iterator] :', eArr.next().value); // 1
        console.log('The element of Uint8Array is using [Symbol.iterator] :', eArr.next().value); // 2
        console.log('The element of Uint8Array is using [Symbol.iterator] :', eArr.next().value); // 3
        console.log('The element of Uint8Array is using [Symbol.iterator] :', eArr.next().value); // 4
        console.log('The element of Uint8Array is using [Symbol.iterator] :', eArr.next().value); // 5
    </script>
</body>
</html>

Output:

Typed array iterable using for…of loop and [Symbol.iterator]

Converting Typed Arrays to and from normal Arrays in JavaScript

To convert a normal Array to a Typed Array, we make it the parameter of a Typed Array constructor. For example: const tarr = new Uint8Array([0, 1, 2]);

The classic way to convert a Typed Array to an Array is to invoke Array.prototype.slice on it. This trick works for all Array-like objects (such as arguments) and Typed Arrays are Array-like. Array.prototype.slice.call(tarr) //[ 0, 1, 2 ]

In ES6, we can use the spread operator (…), because Typed Arrays are iterable: […tarr] //[ 0, 1, 2 ]

Another ES6 alternative is Array.from(), which works with either iterables or Array-like objects: Array.from(tarr)//[ 0, 1, 2 ]

Typed Arrays are iterable Which means we can easily convert it to a regular Array using the spread operator […]. Array.from() also works for the same reason which creates an array from an iterable object.

Example: Convert TypedArray to a regular Array using the spread operator & Array.from() 
<html>
<head>
    <title>JavaScript Converting Typed Arrays to and from normal Arrays example</title>
</head>
<body>
    <script>
        // Create a typed array from a regular array
        const tarr = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
        console.log('Convert a Typed Array to an Array using classic Slice :', Array.prototype.slice.call(tarr))//[ 0, 1, 2, ...]
        console.log('Convert a Typed Array to an Array using spread operator :', [...tarr])//[ 0, 1, 2, ...]
        console.log('Convert a Typed Array to an Array using array.from() :', Array.from(tarr))//[ 0, 1, 2, ...]
    </script>
</body>
</html>

Output:

Convert TypedArray to a regular Array using the spread operator & Array.from() 

JavaScript DataView

The DataView object is nothing but the mirror reflection that represents the bytes stored in the Arraybuffer.

  1. Instances of DataView allow us to access data as elements of several types (Uint8, Int16, Float32, etc.), at any byte offset i.e.: at any location inside an ArrayBuffer.
  2. A view is an eyeglass that provides information about that is, a data type, and the number of elements — that turns the data into a typed array.
  3. We cannot modify the content of ArrayBuffer instead we use a view.
  4. To access/read the content of Arraybuffer and to perform any operation (write or iterate) on ArrayBuffer, we need to use a View
  5. It’s an interface that contains the getter and setter API method to read and write data to the buffer.
  6. A single array buffer can have multiple views attached to it
  7. While working with Data View we used the methods .getUint8(i) or .getUint16(i) to access the data.
Data View Constructor in JavaScript

Syntax: new DataView(buffer, [byteOffset :Number], [byteLength:Number])

The DataView constructor is used to creates a new DataView object whose data is stored in the ArrayBuffer buffer at the specified location. By default, the new DataView can access all of the buffers. If length is not specified, buffer.byteLength – byteOffset will be used.

Parameters:
  1. buffer – An existing ArrayBuffer used to store the new DataView Object.
  2. byteOffset (Optional) – The offset should be in bytes. The starting byte position of the view (by default 0).
  3. byteLength (Optional) – It is the number of elements in the array. The byte length of the view (by default till the end of buffer)
Example: JavaScript DataView object example
<html>
<head>
    <title>JavaScript DataView object example</title>
</head>
<body>
    <script>
        var buffer = new ArrayBuffer(12);
        var dv = new DataView(buffer, 0);
        dv.setInt8(0, 22);
        dv.setFloat32(1, Math.PI);
        console.log('DataView Int8 value at 0 position is : ', dv.getInt8(0));
        console.log('DataView Float32 value at 1 position is : ', dv.getFloat32(1));
    </script>
</body>
</html>

Output:

JavaScript DataView object example

Data View Methods in JavaScript

It’s an interface that contains the getter and setter API method to read and write data to the buffer.

Getter method

The getter getUint8 method gets/reads an Unsigned 8-bit integer at the specified location i.e.: at byte offset from the start of the DataView. It returns the Unsigned 8-bit integer.

Syntax: dataview.getUint8(byteOffset)

The data view is a new DataView object

Parameters:

byteOffset – It has the parameter byteOffset which is offset in a byte and which says from where to read the data from the beginning of the DataView.

Return Value – It returns the Unsigned 8-bit integer.

Example: JavaScript DataView.getInt8() method example
<html>
<head>
    <title>JavaScript DataView.getInt8() method example</title>
</head>
<body>
    <script>
        // create an ArrayBuffer with a size in bytes
        const buffer = new ArrayBuffer(16);

        const dview = new DataView(buffer);
        dview.setInt8(1, 127); // setting (max signed 8-bit integer)

        console.log('Reading the DataView Int8 value at 1 position is : ', dview.getInt8(1));//getting 127
    </script>
</body>
</html>

Output: Reading the DataView Int8 value at 1 position is : 127

The above example will be the same for other getter methods of unsigned and signed 8,16 32 & 64 integer floats etc except the typedArray of set<typedArray> and get<TypedArray> we be differing per the requirement.

Setter method

The setter setUint8 method stores/writes an Unsigned 8-bit integer value at the specified location i.e.: at byte offset from the start of the DataView.

Syntax: dataview.setUint8(byteOffset, value)

The data view is a new DataView object

Parameters:

byteOffset – It has the parameter byteOffset which is offset in a byte and which says from where to read the data from the beginning of the DataView.

Value – The value to set/store.

Example: JavaScript DataView.setUint8() method example
<html>
<head>
    <title>JavaScript DataView.setUint8() method example</title>
</head>
<body>
    <script>
        // create an ArrayBuffer with a size in bytes
        const buffer = new ArrayBuffer(16);

        const dview = new DataView(buffer);
        dview.setUint8(2, 255); // setting (max Unsigned 8-bit integer)

        console.log('Reading the DataView Unsigned Int8(UInt8) value at 2 position is : ', dview.getUint8(2));//getting 255
    </script>
</body>
</html>

Output: Reading the DataView Unsigned Int8(UInt8) value at 2 position is : 255

The above example will be the same for other setter methods of unsigned and signed 8,16 32 & 64 integer floats etc except the typedArray of set<typedArray> and get<TypedArray> we be differing per the requirement.

Below is the list of getter and setter methods for unsigned and signed 8,16 32 & 64 integer floats etc. the range of unsigned and signed integer, float, and BigInt is already explained under the typed array table.

getUint8()

About getUint8() method, we already have explained about this, at the above under getter method section.

getUint32()

The getUint32 method gets/reads an Unsigned 32-bit integer at the specified location i.e.: at byte offset from the start of the DataView. It returns an unsigned 32-bit integer number.

Syntax: dataview.getUint32(byteOffset)

getUint16()

The getUint16 method gets/reads an Unsigned 16-bit integer at the specified location i.e.: at byte offset from the start of the DataView. It returns an unsigned 16-bit integer number.

Syntax: dataview.getUint16(byteOffset)

getInt8()

The getInt8 method gets/reads a signed 8-bit integer(byte) at the specified location i.e.: at byte offset from the start of the DataView. It returns a signed 8-bit integer number.

Syntax: dataview.getInt8(byteOffset)

getInt32()

The getInt32 method gets/reads a signed 32-bit integer at the specified location i.e.: at byte offset from the start of the DataView. It returns a signed 32-bit integer number.

Syntax: dataview.getInt32(byteOffset)

getInt16()

The getInt16 method gets/reads a signed 16-bit integer at the specified location i.e.: at byte offset from the start of the DataView. It returns a signed 16-bit integer number.

Syntax: dataview.getInt16(byteOffset)

getFloat64()

The getFloat64 method gets/reads a signed 64-bit float at the specified location i.e.: at byte offset from the start of the DataView. It returns a signed 64-bit float number.

Syntax: dataview.getFloat64(byteOffset)

getFloat32()

The getFloat32 method gets/reads a signed 32-bit float at the specified location i.e.: at byte offset from the start of the DataView. It returns a signed 32-bit float number.

Syntax: dataview.getFloat32(byteOffset)

getBigUint64()

The getBigUint64 method gets/reads an unsigned 64-bit integer at the specified location i.e.: at byte offset from the start of the DataView. It returns a BigInt.

Syntax: dataview.getBigUint64(byteOffset)

getBigInt64()

The getBigInt64 method gets/reads a signed 64-bit integer at the specified location i.e.: at byte offset from the start of the DataView. It returns a BigInt.

Syntax: dataview.getBigInt64(byteOffset)

setUint8()

In the above under setter method section, we already have explained this method.

setUint32()

The setUint32 method stores/writes an Unsigned 32-bit integer value at the specified location i.e.: at byte offset from the start of the DataView.

Syntax: dataview.setUint32(byteOffset, value)

setUint16()

The setUint16 method stores/writes an Unsigned 16-bit integer value at the specified location i.e.: at byte offset from the start of the DataView.

Syntax: dataview.setUint16(byteOffset, value)

setInt8()

The setInt8() method stores/writes a signed 8-bit integer value at the specified location i.e.: at byte offset from the start of the DataView.

Syntax: dataview.setInt8(byteOffset, value)

setInt32()

The setInt32() method stores/writes a signed 32-bit integer value at the specified location i.e.: at byte offset from the start of the DataView.

Syntax: dataview.setInt32(byteOffset, value)

setInt16()

The setInt16() method stores/writes a signed 16-bit integer value at the specified location i.e.: at byte offset from the start of the DataView.

Syntax: dataview.setInt16(byteOffset, value)

setFloat64()

The setFloat64() method stores/writes a signed 64-bit float value at the specified location i.e.: at byte offset from the start of the DataView.

Syntax: dataview.setFloat64(byteOffset, value)

setFloat32()

The setFloat32() method stores/writes a signed 32-bit float value at the specified location i.e.: at byte offset from the start of the DataView.

Syntax: dataview.setFloat32(byteOffset, value)

setBigUint64()

The setBigUint64() method stores/writes an Unsigned 64-bit integer value at the specified location i.e.: at byte offset from the start of the DataView.

Syntax: dataview.setBigUint64(byteOffset, value)

setBigInt64()

The setBigInt64 () method stores/writes a signed 64-bit integer value at the specified location i.e.: at byte offset from the start of the DataView.

Syntax: dataview.setBigInt64(byteOffset, value)

Data View Properties in JavaScript

DataView buffer

Syntax: DataView.prototype.buffer

Returns the ArrayBuffer of this DataView.

Example: JavaScript DataView.buffer property example
<html>
<head>
    <title>JavaScript DataView.buffer property example</title>
</head>
<body>
    <script>
        //create an ArrayBuffer
        const buffer = new ArrayBuffer(12);

        // Create a view
        const view = new DataView(buffer);

        console.log('DataView using DataView.buffer property :', view.buffer);//12
        console.log('DataView using DataView.buffer property with byteLength :', view.buffer.byteLength);//12
    </script>
</body>
</html>

Output:

JavaScript DataView.buffer property example

DataView byte Length

Syntax: DataView.prototype.byteLength

Returns how many bytes can be accessed by this DataView. Returns the length or size in bytes of this DataView’s buffer. If DataView doesn’t specify the length then the length of the referenced ArrayBuffer will be returned.

Example: JavaScript DataView.byteLength property example
<html>
<head>
    <title>JavaScript DataView.byteLength property example</title>
</head>
<body>
    <script>
        var buffer = new ArrayBuffer(8);

        var dataView = new DataView(buffer);
        console.log('The byteLength of the DataView buffer :', dataView.byteLength);// 8

        var dataView = new DataView(buffer, 1, 6);
        console.log('The byteLength of the DataView buffer as specified when constructing the Uint8Array :', dataView.byteLength);// 6

        var dataView = new DataView(buffer, 3);
        console.log('The byteLength of the DataView buffer due to the offset of the constructed Uint8Array :', dataView.byteLength);// 5
    </script>
</body>
</html>

Output:

JavaScript DataView.byteLength property example

DataView byte Offset

Syntax: DataView.prototype.byteOffset

Returns at which offset i.e.: at which location this DataView starts accessing the bytes in its buffer. If no offset is specified it will start from 0 by default.

Example: JavaScript DataView.byteOffset property example
<html>
<head>
    <title>JavaScript DataView.byteOffset property example</title>
</head>
<body>
    <script>
        var buffer = new ArrayBuffer(16);

        var dataView = new DataView(buffer);
        console.log('The byteOffset of this DataView buffer when no offset specified :', dataView.byteOffset);// 0

        var dataView = new DataView(buffer, 4);
        console.log('The byteOffset of this DataView buffer as specified when constructing the DataView :', dataView.byteOffset);// 4

        var dataView = new DataView(buffer, 12, 4); //from byte 12 for the next 4 bytes
        console.log('The byteOffset of this DataView buffer as specified when constructing the DataView with length :', dataView.byteOffset);// 12
    </script>
</body>
</html>

Output:

JavaScript DataView.byteOffset property example

WebAPIs using TypedArray
  1. FileReader.prototype.readAsArrayBuffer() method is used to starts reading the contents of the specified Blob or File a FileReader as a typed array.
  2. XMLHttpRequest.prototype.send() method supports typed arrays and ArrayBuffer objects as argument.
  3. ImageData.data Is a Uint8ClampedArray depicting a one-dimensional array holding the data in the RGBA order, with integer values between 0 and 255 inclusive.
  4. WebAudio
Where to use TypedArray, ArrayBuffer, and DataView in JavaScript
  1. Typed arrays are fast and good to store specific numeric values. Bitmaps are a typical candidate for typed arrays (e.g., canvas 2D/WebGL).
  2. Heavy data processing of data inside web workers is another use and so on. like transfer between client and server or the file-system.
  3. DataView’s are perfect to parse or build binary files and file formats.
  4. Typed arrays are an excellent way to pack binary data for sending over the net, to the server, or via web sockets and things like data-channels for WebRTC.
  5. If we deal with audio, video, canvas, or media recording, there is often no way around using typed arrays.
  6. The keys for using typed arrays are performance and memory. They are most often used in special scenarios, but there is nothing wrong with using them in ordinary cases when we only need to store numeric values (or utf-8 strings, encryption vectors, etc.). They are fast and have a low memory footprint.
  7. ArrayBuffer is used in canvas and WebGL APIs.
  8. Blob APIs provide us an interface to retrieve its data as an ArrayBuffer.
  9. Binary files are composed of numbers and strings. So, we can read the data of a blob using TypedArray and DataView.
  10. Processing binary data: manipulating image data in HTML Canvas elements, parsing binary files, handling binary network protocols, etc.

Here, in this article, I try to explain the JavaScript TypedArray with examples. I hope this JavaScript TypedArray with Examples article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about TypedArray in the JavaScript article.

Leave a Reply

Your email address will not be published. Required fields are marked *