Open In App

JavaScript SharedArrayBuffer.prototype.slice() Method

Last Updated : 09 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

JavaScript SharedArrayBuffer.prototype.slice() method is specifically for the objects of the SharedArrayBuffer type. It is used to create a new SharedArrayBuffer object that references the same memory region as the original but with a different range.

Syntax:

sharedArrayBufferVariable.slice(start, end);

Parameters:

  • start: An optional parameter representing the start index.
  • end: An optional parameter representing the end index. If omitted, the new SharedArrayBuffer will extend to the end of the original buffer.

Return Value:

  • It returns a new SharedArrayBuffer object representing the specified portion of the original buffer.

Example 1: The code example practically implements the SharedArrayBuffer.prototype.slice() method.

JavaScript
const buffer = new SharedArrayBuffer(16);
const intArray = new Int32Array(buffer);

// Fill the array with the some values
intArray[0] = 1;
intArray[1] = 2;
intArray[2] = 3;
intArray[3] = 4;

// Use the slice() function to 
// create a new view of SharedArrayBuffer
const GFG = intArray.slice(0, 2);
console.log("Original Array:", intArray);

// Display the new array created 
// using the slice()
console.log("New Array:", GFG);

Output
Original Array: Int32Array(4) [ 1, 2, 3, 4 ]
New Array: Int32Array(2) [ 1, 2 ]

Example 2: The below code example also implements the slice() method of SharedArrayBuffer.

JavaScript
const Buffer = new SharedArrayBuffer(8);
const Array = new Uint8Array(Buffer);

// Use slice on the TypedArray to create 
// a new buffer from 2nd to the 5th byte
const slicedArray = Array.slice(1, 5);

// Create a new SharedArrayBuffer 
// from sliced TypedArray
const slicedBuffer = slicedArray.buffer;
console.log(slicedBuffer.byteLength);

Output
4

Next Article

Similar Reads