Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

What is the use of TypedArray Object in JavaScript ?

  • Last Updated : 15 Oct, 2021

Introduction: Arrays in Java and C++ are data structures, that are of fixed-size contiguous and store homogeneous data. These arrays utilize contiguousness and caching to improve performance thus reducing the random access time. However, JavaScript arrays are different beasts. Unlike typical arrays, they are dynamic, sparse, and non-homogeneous. This at first gives a presumption of their low performance(due to the inability of caching features), but under the hood things are different. Javascript engines are incredibly clever beasts. Whenever the data is not sparse and is homogeneous, transparently Javascript stores them in contiguous blocks of memory. Thus behaving a little like typical arrays and giving us improved performance.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

Need of TypedArrays: Though Javascript arrays performed well, but with improvements in web applications due to the addition of WebGL, Sockets, etc. improvement in performance was needed. It was required for JavaScript code to be able to quickly and easily manipulate raw binary data.  This is where TypedArrays come into the picture.  But the question arises: if the JavaScript engine can optimize the things underneath, why do we need TypesArrays?  To answer this, we need to know how numbers and JavaScript arrays behave? Actually, all numbers in JavaScript are going to 64-bit floating-point numbers according to the IEEE-754 standard which is not that efficient. However, TypedArrays allow us to have contiguous blocks of 8, 16, 32, and 64 bits for signed and unsigned integers as well as 32-bit and  64-bit floating numbers.

This allows us to be more efficient as it specifies how much amount of memory is to be utilized and also helps in the transfer of binary data in the expected format.



Uses of TypedArrays:  If we want to transfer binary data as a 16-bit contiguous integer format rather than a conventional 64-bit floating-point, TypedArrays will be efficient. In simpler words, with TypedArrays, we are creating arrays with their content strictly controlled.

Example 1: Let’s say you wanted to render some 3d graphics on the web. This requires being able to transfer an array of numbers, say pixel values as RGB, or some data to a native interface, which needed it to be in some specific size(for RGBA in (0,255) ). But for TypedArrays, we would have implemented a lot of data handling to make sure things work properly, and that too in 64-bit floating-point format.                                                 

Javascript




<script>
 
    // pixelData array with pixel values
    const pixelData = [143, 1432, 728,
        913, 182, 64, 023, 343, 183, 194]
 
    // To convert pixel data into RGBA range ie. (0,255)
    const clampedRGBA = new Uint8ClampedArray(pixelData);
 
    console.log("Clamped PixelData: " + clampedRGBA)
</script>

Output:

Clamped PixelData: 143,255,255,255,182,64,19,255,183,194

Explanation: The above output shows how easily pixel values are clamped achieved using Uint8ClampedArray without requiring any explicit data handling.

Example 2: In this example,  we will see how we can attach typed array views and DataViews to the buffer to reads the contents of the specified file. Many API’s make use of TypedArrays such as FileReader.prototype.readAsArrayBuffer() . The FileReader can read file contents as an ArrayBuffer.

HTML




<!DOCTYPE html>
<html lang="en">
 
<body>
 
    <input type="file" onchange='readFile(event)' />
 
    <br><br>
    <textarea cols="50" rows="10"></textarea>
 
    <script>
        var readFile = function (event) {
            var input = event.target;
            var text = "";
            var reader = new FileReader();
 
            reader.onload = function () {
                var arrayBuffer = reader.result;
                var idView = new Uint8Array(arrayBuffer);
                idView.forEach(function (alpha) {
 
                    // console.log(String.fromCharCode(alpha))
                    text = text + String.fromCharCode(alpha)
                });
                console.log(text);
                document.getElementsByTagName(
                    'textarea')[0].innerText = text;
            };
            reader.readAsArrayBuffer(input.files[0]);
        };
    </script>
</body>
 
</html>

Output:

Explanation: The above example shows us how with the help of FileReader API and TypedArray views, we can view the contents of the file or blob.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!