ArrayBuffer.prototype.transferToFixedLength()
Baseline 2024
Newly available
Since March 2024, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
The transferToFixedLength()
method of ArrayBuffer
instances creates a new non-resizable ArrayBuffer
with the same byte content as this buffer, then detaches this buffer.
Syntax
transferToFixedLength()
transferToFixedLength(newByteLength)
Parameters
newByteLength
-
The
byteLength
of the newArrayBuffer
. Defaults to thebyteLength
of thisArrayBuffer
.- If
newByteLength
is smaller than thebyteLength
of thisArrayBuffer
, the "overflowing" bytes are dropped. - If
newByteLength
is larger than thebyteLength
of thisArrayBuffer
, the extra bytes are filled with zeros.
- If
Return value
A new ArrayBuffer
object. Its contents are initialized to the contents of this ArrayBuffer
, and extra bytes, if any, are filled with zeros. The new ArrayBuffer
is always non-resizable. The original ArrayBuffer
is detached.
Exceptions
TypeError
-
Thrown if this
ArrayBuffer
is already detached.
Description
Unlike transfer()
, transferToFixedLength()
always creates a non-resizable ArrayBuffer
. This means newByteLength
can be larger than the maxByteLength
, even if this ArrayBuffer
is resizable. See transferring ArrayBuffers for more information.
Examples
Transferring a resizable ArrayBuffer to fixed-length
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });
const view = new Uint8Array(buffer);
view[1] = 2;
view[7] = 4;
const buffer2 = buffer.transferToFixedLength();
console.log(buffer2.byteLength); // 8
console.log(buffer2.resizable); // false
const view2 = new Uint8Array(buffer2);
console.log(view2[1]); // 2
console.log(view2[7]); // 4
Using transferToFixedLength
, newByteLength
can be larger than the maxByteLength
of the original ArrayBuffer
.
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });
const view = new Uint8Array(buffer);
view[1] = 2;
view[7] = 4;
const buffer2 = buffer.transferToFixedLength(20);
console.log(buffer2.byteLength); // 20
console.log(buffer2.resizable); // false
const view2 = new Uint8Array(buffer2);
console.log(view2[1]); // 2
console.log(view2[7]); // 4
Specifications
Specification |
---|
ECMAScript Language Specification # sec-arraybuffer.prototype.transfertofixedlength |
Browser compatibility
BCD tables only load in the browser