When a TypedArray
is created as a view of a resizable buffer, resizing the underlying buffer will have different effects on the size of the TypedArray
depending on whether the TypedArray
is constructed as length-tracking.
If a typed array is created without a specific size by omitting the third parameter or passing undefined
, the typed array will become length-tracking, and will automatically resize to fit the underlying buffer
as the latter is resized:
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });
const float32 = new Float32Array(buffer);
console.log(float32.byteLength);
console.log(float32.length);
buffer.resize(12);
console.log(float32.byteLength);
console.log(float32.length);
If a typed array is created with a specific size using the third length
parameter, it won't resize to contain the buffer
as the latter is grown:
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });
const float32 = new Float32Array(buffer, 0, 2);
console.log(float32.byteLength);
console.log(float32.length);
console.log(float32[0]);
buffer.resize(12);
console.log(float32.byteLength);
console.log(float32.length);
console.log(float32[0]);
When a buffer
is shrunk, the viewing typed array may become out of bounds, in which case the typed array's observed size will decrease to 0. This is the only case where a non-length-tracking typed array's length may change.
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });
const float32 = new Float32Array(buffer, 0, 2);
buffer.resize(7);
console.log(float32.byteLength);
console.log(float32.length);
console.log(float32[0]);
If you then grow the buffer
again to bring the typed array back in bounds, the typed array's size will be restored to its original value.
buffer.resize(8);
console.log(float32.byteLength);
console.log(float32.length);
console.log(float32[0]);
The same can happen for length-tracking typed arrays as well, if the buffer is shrunk beyond the byteOffset
.
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });
const float32 = new Float32Array(buffer, 4);
buffer.resize(3);
console.log(float32.byteLength);