Preamble: In JavaScript, all of us must be familiar enough with arrays to know that they are dynamic in nature and can hold any JavaScript object. However, if you’ve ever used another language like C, you know that arrays are not dynamic in nature. And you can only store specific data types in that array, which ensures that the array is more efficient from a performance perspective. But the dynamic nature of arrays and the variety of information types they store doesn’t actually make JavaScript arrays inefficient. With the help of JavaScript engine optimization, array execution in JavaScript is actually very fast.

As Web applications become more powerful, we begin to need to let them process and manipulate raw binary data. JavaScript arrays can’t handle raw binary data, so we introduced JavaScript typed arrays.

Typed array

A typed array is a very similar object to an array, but it provides a mechanism for writing raw binary data to an memory buffer. All major browsers support this functionality well, and ES6 has integrated it into the JavaScript core framework, as well as access to Array methods such as map() and filter(). I strongly encourage you to browse the resources mentioned at the end of this article to learn more about typed arrays.

composition

A typed array consists of two main parts, Buffer and View.

The buffer

A Buffer is an object of type ArrayBuffer that represents a block of data. This raw binary data block cannot be accessed or modified separately. You may wonder what use data objects that cannot be accessed or modified can have. The view is actually the read/write interface to the buffer.

view

A View is an object that allows you to access and modify the raw binary content stored in an ArrayBuffer. In general, there are two views.

  • An instance of a TypedArray object

    These types of objects are very similar to ordinary arrays, but store only numeric data of a single type. Data types such as Int8, Uint8, Int16 and Float32 are typed arrays. The number in the type represents the number of bits assigned to the data type. For example, Int8 represents an 8-bit integer.

  • DataView object instance

    DataView is a low-level interface that provides a getter/setter API to read and write arbitrary data to a buffer. This makes development much easier, especially when you need to deal with multiple data types in a single typed array.

    Another benefit of using DataView is that it lets you control the byte order of your data — typed arrays use the platform’s byte order. Of course, if your program is running locally, this won’t be a problem because your device will use the same byte order as the input array. In most cases, your typed array will be in low endian order, because Intel takes small endian order. Because Intel is so common in computer processors, most of the time there is no problem. However, if data encoded in small endian is transferred to a device that uses large endian, errors in reading can result in data loss. Because DataView allows you to control the direction of the byte order, you can use it if necessary.

What makes them different from ordinary arrays

As mentioned earlier, normal JavaScript arrays are optimized by the JavaScript engine, and you don’t need to use typed arrays for performance, because it won’t give you much of an upgrade. But there are some features that make typed arrays different from normal arrays, and that’s probably why you chose them.

  • Allows you to process raw binary data
  • Because they deal with a finite number of data types, your engine can optimize typed arrays more easily than ordinary arrays, which can be a very complex process.
  • There is no guarantee that normal arrays will always be optimized, as your engine may decide not to for a variety of reasons.

Use in Web development

  1. XMLHttpRequest API

    You can receive the data response as an ArrayBuffer based on your response type.

    const xhr = new XMLHttpRequest();
    xhr.open('GET', exampleUrl);
    xhr.responseType = 'arraybuffer';
    
    xhr.onload = function () {
        const arrayBuffer = xhr.response;
        // Process data
    };
    
    xhr.send();
    Copy the code
  2. Fetch API

    Similar to the XMLHttpRequest API, the Fetch API also allows you to receive responses in an ArrayBuffer. You simply use the arrayBuffer() method in the FETCH API response and you receive a Promise parsed using arrayBuffer.

    fetch(url)
    .then(response= > response.arrayBuffer())
    .then(arrayBuffer= > {
       // Process data
    });
    Copy the code
  3. HTML Canvas

    The HTML5 Canvas element allows you to render dynamic 2D shapes and bitmap images. This element simply acts as a container for the graphics, which are drawn with the help of JavaScript.

    Canvas’s 2D Context allows you to retrieve bitmap data as an instance of the Uint8ClampedArray. Let’s take a look at the sample code provided by Dr. Axel:

       const canvas = document.getElementById('my_canvas');
       const context = canvas.getContext('2d');
       const imageData = context.getImageData(0.0, canvas.width, canvas.height);
       const uint8ClampedArray = imageData.data;
    Copy the code
  4. WebGL

    WebGL allows you to render high performance interactive 3D and 2D graphics. It relies heavily on typed arrays because it processes the raw pixel count to output the necessary graphics on the canvas.

    You can read more about WebGL basics in this article.

  5. Web Socket

    Web sockets allow you to send and receive raw binary data as blobs or array buffers.

    const socket = new WebSocket("ws://localhost:8080");
    socket.binaryType = "arraybuffer";
    
    / / to monitor the message
    socket.addEventListener("message".function (event) {
        const view = new DataView(event.data);
        // Process the received data
    });
    
    // Send binary data
    socket.addEventListener('open'.function (event) {
        const typedArray = new Uint16Array(7);
        socket.send(typedArray.buffer);
    });
    Copy the code

Although typed arrays may not be necessary for beginners, they are essential as you move into mid-to-advanced JavaScript development. This is mainly because you may want to develop more complex applications that need to use typed arrays.

Thanks for reading and have fun programming!!