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 in bytes.

Syntax

arrayBuffer.byteLength

Return Value

Returns a number representing the length of the ArrayBuffer in bytes. This value is established when the ArrayBuffer is constructed and cannot be changed.

Example: Basic Usage

<html>
<head>
    <title>JavaScript ArrayBuffer 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: Different Buffer Sizes

<html>
<head>
    <title>JavaScript ArrayBuffer Sizes</title>
</head>
<body>
    <script type="text/javascript">
        var buffer1 = new ArrayBuffer(16);
        var buffer2 = new ArrayBuffer(1024);
        var buffer3 = new ArrayBuffer(0);
        
        document.write("Buffer 1 length: " + buffer1.byteLength + "<br>");
        document.write("Buffer 2 length: " + buffer2.byteLength + "<br>");
        document.write("Buffer 3 length: " + buffer3.byteLength);
    </script>
</body>
</html>

Output

Buffer 1 length: 16
Buffer 2 length: 1024
Buffer 3 length: 0

Common Errors

ArrayBuffer constructor throws errors for invalid size values:

Negative Values

<html>
<head>
    <title>ArrayBuffer Error Example</title>
</head>
<body>
    <script type="text/javascript">
        try {
            var obj = new ArrayBuffer(-72);
            document.write("Length: " + obj.byteLength);
        } catch (error) {
            document.write("Error: " + error.message);
        }
    </script>
</body>
</html>

Output

Error: Invalid array buffer length

Extremely Large Values

<html>
<head>
    <title>ArrayBuffer Large Size Error</title>
</head>
<body>
    <script type="text/javascript">
        try {
            var obj = new ArrayBuffer(Number.MAX_SAFE_INTEGER);
            document.write("Length: " + obj.byteLength);
        } catch (error) {
            document.write("Error: " + error.message);
        }
    </script>
</body>
</html>

Output

Error: Array buffer allocation failed

Key Points

  • The byteLength property is read-only and cannot be modified
  • ArrayBuffer size must be a non-negative integer
  • Maximum size is implementation-dependent but typically limited by available memory
  • Zero-length buffers are valid and return byteLength of 0

Conclusion

The ArrayBuffer.byteLength property provides a reliable way to determine the size of binary data buffers. Use it to validate buffer sizes and manage memory allocation in your applications.

Updated on: 2026-03-15T23:18:59+05:30

744 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements