Note: The SharedArrayBuffer constructor may not always be globally available unless certain security requirements are met.
The SharedArrayBuffer() constructor creates SharedArrayBuffer objects.
new SharedArrayBuffer(length)
new SharedArrayBuffer(length, options)Note: SharedArrayBuffer() can only be constructed with new. Attempting to call it without new throws a TypeError.
lengthThe size, in bytes, of the array buffer to create.
options OptionalAn object, which can contain the following properties:
maxByteLength OptionalThe maximum size, in bytes, that the shared array buffer can be resized to.
A new SharedArrayBuffer object of the specified size, with its maxByteLength property set to the specified maxByteLength if one was specified. Its contents are initialized to 0.
Note that these examples cannot be run directly from the console or an arbitrary web page, because SharedArrayBuffer is not defined unless its security requirements are met.
Create a buffer specifying its size in bytes.
// Create a SharedArrayBuffer with a size in bytes
const buffer = new SharedArrayBuffer(8);
console.log(buffer.byteLength); // 8SharedArrayBuffer constructors are required to be constructed with a new operator. Calling a SharedArrayBuffer constructor as a function without new will throw a TypeError.
const sab = SharedArrayBuffer(1024);
// TypeError: calling a builtin SharedArrayBuffer constructor
// without new is forbiddenconst sab = new SharedArrayBuffer(1024);In this example, we create an 8-byte buffer that is growable to a max length of 16 bytes, then grow() it to 12 bytes:
const buffer = new SharedArrayBuffer(8, { maxByteLength: 16 });
buffer.grow(12);Note: It is recommended that maxByteLength is set to the smallest value possible for your use case. It should never exceed 1073741824 (1GB), to reduce the risk of out-of-memory errors.