JavaScript ArrayBuffer

JavaScript ArrayBuffer

In this article, we will learn about the ArrayBuffer object in JavaScript to create and manipulate ArrayBuffer objects.

Syntax:

var buffer = new ArrayBuffer(size);

The size parameter inside ArrayBuffer specifies the size of the created buffer in bytes.

Creating an ArrayBuffer in JavaScript

var buffer = new ArrayBuffer(8);
var view = new DataView(buffer);

In the code above, we created an 8-byte buffer. Also, we used the DataView view for referring and manipulating the buffer.

Let’s see some examples to get a clear idea of the ArrayBuffer object.

Example-1:

<!DOCTYPE html>
<html >
    <head>
        <title>JavaScript ArrayBuffer</title>
    </head>
    <body>
        <h1 style="color: blueviolet;"> DelftStack </h1>
        <h3><u>JavaScript ArrayBuffer object</u></h3>
      

        <script>
            var buffer = new ArrayBuffer(8);  // create a buffer of length 8
            var view = new DataView(buffer);  // view which is reffering to buffer
            document.write("Buffer Byte Length : " + buffer.byteLength);
            document.write("<br>");
            document.write("View Byte Length : " + view.byteLength);
           
        </script>
    </body>
</html>

Output:

DelftStack
JavaScript ArrayBuffer object
Buffer Byte Length : 8
View Byte Length : 8

Below is another example of how we can modify and perform operations on the ArrayBuffer object using DataView and typed arrays.

Example-2:

<!DOCTYPE html>
<html >
    <head>
        <title>JavaScript ArrayBuffer</title>
    </head>
    <body>
        <h1 style="color: blueviolet;"> DelftStack </h1>
        <p> <b> <u> Manipulating ArrayBuffer using DataView and TypedArray </b> </u> </p>
      

        <script>
            // ArrayBuffer
            var buffer = new ArrayBuffer(8);
            
            // DataView 
            var view1 = new DataView(buffer);

            // TypedArray
            var view2 = new Int8Array(buffer);

            //Put value of 32bits
            view1.setInt32(0, 0x76543210);

            //prints the 32bit value
            document.write( "32 bit value : " + view1.getInt32(0).toString(16) + "<br>"); 
                
            //prints only 8bit value 
            document.write("8 bit value : " + view1.getInt8(0).toString(16) + "<br>"); 
            document.write("32 bit value : " + view2[0].toString(16));   
        </script>
    </body>
</html>

Output:

DelftStack
Manipulating ArrayBuffer using DataView and TypedArray

32-bit value : 76543210
8-bit value : 76
32-bit value : 76

So, as demonstrated in the above example, we can add multiple DataView or TypedArray objects to a single ArrayBuffer and see any changes to one object by other object views.