Typed Arrays

JavaScript arrays can grow and shrink dynamically and can have any JavaScript value. This flexibility comes at a performance cost. Many web applications, such as those manipulating WebGL, WebSockets, audio, and video, prefer access to raw fixed-length binary data. This results in the introduction of typed arrays into JavaScript.

There are several ways to initialize a TypedArray:
new TypedArray(); // new in ES2017

new TypedArray(length);

new TypedArray(typedArray);

new TypedArray(object);

new TypedArray(buffer [, byteOffset [, length]]);

Typed arrays are implemented using views: Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, and (added in ECMAScript 2025) Float16Array.
Uint8ClampedArray clamps the values between 0 and 255.
Float16Array stores IEEE 754 half-precision (16-bit) floats — a compact format popular in machine-learning and graphics workloads, convertible with the also-new Math.f16round() (17.2) and the getFloat16()/setFloat16() methods on DataView (13.2).

Typed Arrays share almost all properties and methods of Array. The unsupported methods include:

Array.isArray()

Array.prototype.concat()

Array.prototype.push()

Array.prototype.pop()

Array.prototype.unshift()

Array.prototype.shift()

Also, typed arrays have the following properties/methods:

.BYTES_PER_ELEMENT
.name
.prototype.buffer
.prototype.byteLength

.prototype.byteOffset

.prototype.length

.prototype.set()

.prototype.subarray()


var a = Int8Array.from([1, 2, 3]);
console.log(a.BYTES_PER_ELEMENT);
console.log(Int8Array.name);
console.log(a.buffer);
console.log(a.byteLength);
console.log(a.byteOffset);
console.log(Array.isArray(a));

a[1] = 3;
console.log(a);

a.set([4, 5], 1);
console.log(a);
// a.set(a, 1);   // RangeError: Source is too large

var b = a.subarray(1, 3);
console.log(b);
// b.concat(a);   // TypeError

[...c] = [...b];
console.log(c);
console.log(Array.isArray(c));

1 Int8Array ArrayBuffer {} 3 0 false [1,3,3] [1,4,5] [4,5] [4,5] true

This demonstrates the performance benefit of using a typed array.


var a = new Array(1024);
var ta = Float64Array.from(a);

var t1 = Date.now();
for (i = 0; i < 100000; i++) a.copyWithin(0);
var t2 = Date.now();

for (i = 0; i < 100000; i++) ta.copyWithin(0);
var t3 = Date.now();

console.log(t2 - t1);
console.log(t3 - t2);

3987 12