Javascript ArrayBuffer Type

Introduction

The Javascript ArrayBuffer is the basic unit referred to by all typed arrays and views.

ArrayBuffer() method is a normal JavaScript constructor that can be used to allocate a specific number of bytes in memory.

const buf = new ArrayBuffer(16);  // Allocates 16 bytes of memory 
console.log(buf.byteLength);            // 16 

An ArrayBuffer can never be resized once it is created.

We can copy all or part of an existing ArrayBuffer into a new instance using slice():

const buf1 = new ArrayBuffer(16); 
const buf2 = buf1.slice(4, 12); /*  w w  w  .j  a  v  a2 s  .  c  om*/
console.log(buf2.byteLength);  // 8  

Declaring an ArrayBuffer initializes all the bits to 0s.

To read or write data inside, you must use a view.

There are different types of views, and they all refer to binary data stored in an ArrayBuffer.

The Javascript ArrayBuffer object represents a fixed-length raw binary data buffer.

It is a "byte array".

We cannot directly manipulate the contents of an ArrayBuffer.

We have to create one of the typed array objects or a DataView object.

const buffer = new ArrayBuffer(8);
console.log(buffer);// ww w  .j  a  va2 s  .co  m
const view = new Int32Array(buffer);
console.log(view);



PreviousNext

Related