ArrayBuffer.slice() function in JavaScript

The ArrayBuffer object in JavaScript represents a fixed-length binary data buffer. The slice() method creates a new ArrayBuffer containing a copy of the specified portion of the original buffer.

Syntax

arrayBuffer.slice(start, end)

Parameters

  • start (optional): The byte index where the slice begins (inclusive). Defaults to 0.
  • end (optional): The byte index where the slice ends (exclusive). Defaults to buffer length.

Return Value

Returns a new ArrayBuffer containing the copied bytes from the specified range.

Example: Basic ArrayBuffer Slicing

<html>
<head>
    <title>ArrayBuffer Slice Example</title>
</head>
<body>
    <script type="text/javascript">
        // Create a 16-byte ArrayBuffer
        var arrayBuffer = new ArrayBuffer(16);
        var int32View = new Int32Array(arrayBuffer);
        
        // Set some values
        int32View[0] = 100;
        int32View[1] = 200;
        int32View[2] = 300;
        
        // Slice from byte 4 to 12 (bytes 4-11)
        var sliced = arrayBuffer.slice(4, 12);
        var slicedView = new Int32Array(sliced);
        
        document.write("Original buffer length: " + arrayBuffer.byteLength + "<br>");
        document.write("Sliced buffer length: " + sliced.byteLength + "<br>");
        document.write("Sliced values: " + slicedView);
    </script>
</body>
</html>
Original buffer length: 16
Sliced buffer length: 8
Sliced values: 200,300

Example: Negative Indices

<html>
<head>
    <title>ArrayBuffer Negative Slice</title>
</head>
<body>
    <script type="text/javascript">
        var buffer = new ArrayBuffer(12);
        var view = new Uint8Array(buffer);
        
        // Fill with values
        for(var i = 0; i < view.length; i++) {
            view[i] = i * 10;
        }
        
        // Slice last 4 bytes using negative index
        var lastBytes = buffer.slice(-4);
        var lastView = new Uint8Array(lastBytes);
        
        document.write("Last 4 bytes: " + Array.from(lastView));
    </script>
</body>
</html>
Last 4 bytes: 80,90,100,110

Key Points

  • slice() creates a new ArrayBuffer with copied data, not a view
  • Negative indices count from the end of the buffer
  • The original ArrayBuffer remains unchanged
  • Byte indices must be aligned with the data type when using typed arrays

Conclusion

ArrayBuffer's slice() method provides an efficient way to extract portions of binary data. It creates independent copies, making it useful for data processing and manipulation without affecting the original buffer.

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

585 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements