How to use JavaScript Typed Array? [SOLVED]


Written By - Olorunfemi Akinlua
Advertisement

Introduction

In JavaScript, a typed array is a special kind of array that allows you to store a collection of homogenous elements – that is, elements of the same data type – in a contiguous block of memory. This can be useful for improving the performance of certain operations, such as when working with large datasets or when performing mathematical calculations.

In this article, we will explore the concept of typed arrays in JavaScript and discuss how they are created and used. We will also compare typed arrays with regular arrays and look at some common use cases for typed arrays. Whether you are a beginner or an experienced developer, understanding typed arrays can be a valuable asset when working with large data sets in JavaScript.

 

Working with typed arrays

There are several different types of typed arrays in JavaScript, each of which corresponds to a specific data type:

  • Int8Array: an array of 8-bit signed integers
  • Uint8Array: an array of 8-bit unsigned integers
  • Int16Array: an array of 16-bit signed integers
  • Uint16Array: an array of 16-bit unsigned integers
  • Int32Array: an array of 32-bit signed integers
  • Uint32Array: an array of 32-bit unsigned integers
  • Float32Array: an array of 32-bit floating-point numbers
  • Float64Array: an array of 64-bit floating-point numbers

To create a typed array, you can use the new operator followed by the name of the typed array constructor, along with the length of the array in square brackets

const arr = new Uint8Array(5);

This creates a new Uint8Array with a length of 5, containing all zeros. You can also pass an array of values to the constructor to initialize the typed array with those values

const arr = new Uint8Array([1, 2, 3, 4, 5]);

 

Using methods with typed array

Typed arrays also have a number of methods and properties that you can use to manipulate the elements in the array. For example, you can use the .fill() method to fill the entire array with a specific value

const arr = new Uint8Array(5);
arr.fill(0);
console.log(arr);

Output

Uint8Array(5) [ 0, 0, 0, 0, 0 ]

You can also use the .slice() method to extract a subarray from the typed array

Advertisement
const subarray = arr.slice(1, 3);
console.log(subarray);

Output

Uint8Array(2) [ 0, 0 ]

This will create a new Uint8Array containing the elements at indices 1 and 2 of the original array.

Typed arrays also support many of the same methods and properties as regular JavaScript arrays, such as .push(), .pop(), and .length. However, keep in mind that typed arrays are low-level APIs and may not have all of the same features as regular arrays.

In addition to the methods and properties inherited from regular arrays, typed arrays also have several methods that are specific to their data type. For example, the .set() method allows you to set the values of multiple elements in a typed array at once

const arr = new Uint8Array(5);
arr.set([1, 2, 3], 1);

console.log(arr);

Output

Uint8Array(5) [ 0, 1, 2, 3, 0 ]

This will set the values of the elements at indices 1, 2, and 3 to 1, 2, and 3, respectively, leaving the element at index 0 unchanged.

Typed arrays also have a .buffer property that returns the underlying ArrayBuffer object for the typed array. You can use this to create a new typed array that shares the same memory as the original array:

const arr1 = new Uint8Array([1, 2, 3, 4, 5]);
const arr2 = new Uint8Array(arr1.buffer);

console.log(arr1, arr2);

Output

Advertisement
Uint8Array(5) [ 1, 2, 3, 4, 5 ] Uint8Array(5) [ 1, 2, 3, 4, 5 ]

In this case, arr2 will be a new Uint8Array containing the same values as arr1.

 

Mathematical operations with typed array

Here's an example of how you might use a typed array to improve the performance of a simple image grayscale conversion function

function grayscale(imageData) {
    const pixels = imageData.data;
    const numPixels = pixels.length;
    const grayscalePixels = new Uint8ClampedArray(numPixels);

    for (let i = 0; i < numPixels; i += 4) {
        const avg = (pixels[i] + pixels[i + 1] + pixels[i + 2]) / 3;
        grayscalePixels[i] = avg;
        grayscalePixels[i + 1] = avg;
        grayscalePixels[i + 2] = avg;
        grayscalePixels[i + 3] = pixels[i + 3];
    }

    return new ImageData(grayscalePixels, imageData.width, imageData.height);
}

Typed arrays can also be used to perform complex mathematical calculations more efficiently. For example, you might use a Float64Array to store a large dataset of floating-point values and then use the .map() method to apply a mathematical transformation to each value in the array

const data = new Float64Array([1.1, 2.2, 3.3, 4.4, 5.5]);
const transformedData = data.map((x) => x * 2);

console.log(transformedData);

Output

Float64Array(5) [ 2.2, 4.4, 6.6, 8.8, 11 ]

This will create a new Float64Array containing the transformed values [2.2, 4.4, 6.6, 8.8, 11].

 

How Typed Array is different from Regular Array?

Typed arrays have all methods of regular arrays, except for:

Advertisement
  • push, pop, shift, unshift - you can’t change the size of a typed array
  • flat, flatMap - a typed array can’t hold arrays
  • concat - use set instead

There are two methods that regular arrays don’t have. The set method copies values from an array or typed array at an offset:

targetTypedArray.set(source, offset)

By default, the offset is zero. The source must fit entirely into the target. If the offset and source length exceed the target length, a RangeError is thrown. (This means you cannot use this method to shift elements of a typed array.)

The subarray method yields a view into a subrange of the elements:

const sub = iarr.subarray(16, 32)

If omitted, the end index is the length of the array, and the start index is zero.

This seems to be just the same as the slice method, but there is an important difference. The array and subarray share the same elements. Modifying either is visible in the other.

sub[0] = 1024 // Now iarr[16] is also 1024

 

Summary

Overall, typed arrays are a useful tool for optimizing the performance of certain types of operations in JavaScript. Whether you're working with large datasets, performing complex calculations, or manipulating binary data, typed arrays can help you get the most out of your code.

 

References

JavaScript typed arrays - JavaScript | MDN (mozilla.org)

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment