ArrayBuffer.byteLength Property in JavaScript


ArrayBuffer object in JavaScript represents a fixed-length binary data buffer.The byteLength property of the ArrayBuffer returns an unsigned, 32-bit integer that specifies the size/length of the ArrayBuffer.

Syntax

Its syntax is as follows

array.byteLength

Example

Try the following example.

 Live Demo

<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var arrayBuffer = new ArrayBuffer(8);
      var result = arrayBuffer.byteLength;
      document.write("length of the array buffer is: " + result);
   </script>
</body>
</html>

Output

length of the array buffer is: 8

Example

You can also create an array buffer object by passing a string value and get its length as in the following example. Since here we haven’t passed any size value it returns 0 −

 Live Demo

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var obj = new ArrayBuffer("Hi welcome to Tutorialspoint");
      var byteLength = obj.byteLength;
      document.write(byteLength);
   </script>
</body>
</html>

Output

0

Errors

While creating an ArrayBuffer you cannot use negative values, complex numbers and, the size should be not more than 253 else this functions generates an error.

Size more than 253

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var obj = new ArrayBuffer(9007199254740995);
      var byteLength = obj.byteLength;
      document.write(byteLength);
   </script>
</body>
</html>

Output

Error: Array buffer allocation failed

Size with a complex number

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var obj = new ArrayBuffer(2+3i);
      var byteLength = obj.byteLength;
      console.log(byteLength);
      </script>
</body>
</html>

Output

Error: Invalid or unexpected token

Size with a negative value

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var obj = new ArrayBuffer(-72);
      var byteLength = obj.byteLength;
      console.log(byteLength);
   </script>
</body>
</html>

Output

Error: Invalid array buffer length

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 25-Jun-2020

385 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements