Introduction to Typed Arrays
Typed Arrays in JavaScript provide a way to work with binary data directly, giving you an array-like view over raw memory buffers. Unlike regular arrays, Typed Arrays store data in fixed-size, strongly typed formats, which is ideal for performance-critical applications like WebGL, audio processing, and file manipulation.
Why Typed Arrays?
Regular JavaScript arrays can store any type of value, which makes them flexible but less efficient for numeric or binary data. Typed Arrays:
- Store elements of a single type.
- Use contiguous memory for fast access.
- Are suitable for low-level data processing and interfacing with Web APIs (like WebGL).
ArrayBuffer
A Typed Array works on top of an ArrayBuffer, which represents a raw, fixed-size binary buffer.
ArrayBuffer
itself cannot store data directly.- It provides raw memory for Typed Arrays to access.
// Create a buffer of 16 bytes
const buffer = new ArrayBuffer(16);
console.log(buffer.byteLength); // 16
Typed Array Views
Typed Arrays provide views over ArrayBuffer, defining how to interpret the raw binary data.
Common Typed Arrays:
Typed Array | Bytes per Element | Description |
---|---|---|
Int8Array | 1 | 8-bit signed integer |
Uint8Array | 1 | 8-bit unsigned integer |
Uint8ClampedArray | 1 | 8-bit unsigned clamped |
Int16Array | 2 | 16-bit signed integer |
Uint16Array | 2 | 16-bit unsigned integer |
Int32Array | 4 | 32-bit signed integer |
Uint32Array | 4 | 32-bit unsigned integer |
Float32Array | 4 | 32-bit float |
Float64Array | 8 | 64-bit float |
Creating Typed Arrays
From ArrayBuffer
const buffer = new ArrayBuffer(16);
const int32View = new Int32Array(buffer);
console.log(int32View.length); // 4 (16 bytes / 4 bytes per Int32)
From regular array
const floatArray = new Float32Array([0.5, 1.5, 2.5]);
console.log(floatArray); // Float32Array(3) [0.5, 1.5, 2.5]
With length
const uint8 = new Uint8Array(5); // 5 elements initialized with 0
console.log(uint8); // Uint8Array(5) [0, 0, 0, 0, 0]
Accessing and Modifying Elements
- Like normal arrays, elements are indexed starting from 0.
- Cannot exceed the bounds; no automatic resizing.
const intArray = new Int16Array([10, 20, 30]);
console.log(intArray[1]); // 20
intArray[2] = 40;
console.log(intArray); // Int16Array(3) [10, 20, 40]