JS Typed Arrays

Typed arrays handle binary data efficiently. Learn how they are used in performance-sensitive applications.

On this page

Typed Arrays

Typed Arrays provide a way to work with raw binary data in JavaScript. They are used in performance-sensitive code such as graphics, audio processing, WebGL, WebAssembly, and network protocols.

Unlike normal arrays, typed arrays store data in fixed-size binary format.

const arr = new Uint8Array(4);

arr[0] = 255;
arr[1] = 128;

console.log(arr);

Common typed array types:

  • Int8Array / Uint8Array
  • Int16Array / Uint16Array
  • Int32Array / Uint32Array
  • Float32Array / Float64Array
  • BigInt64Array / BigUint64Array

Typed Methods

Typed arrays share many array methods, but they are fixed length.

const nums = new Uint8Array([1, 2, 3, 4]);

nums.forEach(n => console.log(n));

const doubled = nums.map(n => n * 2);
console.log(doubled);

console.log(nums.includes(3));

Important differences:

  • No push() or pop()
  • Fixed length
  • Memory efficient

Typed Reference

Typed arrays are views over an ArrayBuffer. Multiple views can share the same buffer.

const buffer = new ArrayBuffer(8);

const view1 = new Uint8Array(buffer);
const view2 = new Uint16Array(buffer);

view1[0] = 255;
console.log(view2[0]); // Interpreted differently

Array Buffers

An ArrayBuffer represents a fixed-length raw binary data buffer.

const buffer2 = new ArrayBuffer(16);
console.log(buffer2.byteLength);

ArrayBuffers do not have direct read/write methods. You must use a TypedArray or DataView.

DataViews

DataView allows reading and writing multiple number types in the same buffer with explicit control over byte order (endianness).

const buffer3 = new ArrayBuffer(8);
const view = new DataView(buffer3);

view.setInt16(0, 256);
console.log(view.getInt16(0));

DataView is useful when working with binary protocols or file formats.

JS Atomics

Atomics provides atomic operations for shared memory (SharedArrayBuffer). It is mainly used in multi-threaded environments like Web Workers.

const shared = new SharedArrayBuffer(4);
const int32 = new Int32Array(shared);

Atomics.store(int32, 0, 100);
console.log(Atomics.load(int32, 0));

Atomics.add(int32, 0, 10);
console.log(Atomics.load(int32, 0));

Atomics ensures thread-safe operations when multiple workers access the same memory.

When to Use Typed Arrays

  • Working with binary data
  • High-performance numerical operations
  • WebGL / Canvas pixel manipulation
  • WebAssembly interop

Next Step

Continue with JS Web APIs or JS DOM Navigation depending on your learning path.

JS Typed Arrays Examples (8)