Typed Arrays
JavaScript Typed Arrays are array-like objects that provide a mechanism for reading and writing raw binary data in memory buffers. They were originally introduced for WebGL to handle binary data efficiently but are now used in many APIs (Canvas, WebSockets, File API).
1. Architecture
Typed arrays are split into Buffers and Views.
ArrayBuffer
An ArrayBuffer is a generic, fixed-length raw binary data buffer. You cannot directly manipulate the contents of an ArrayBuffer.
const buffer = new ArrayBuffer(16); // Create a buffer of 16 bytes
console.log(buffer.byteLength); // 16
Views
To read and write data in the buffer, you need a View. There are two types of views:
- Typed Array Views: Treat the buffer as an array of elements of a specific type.
- DataView: A low-level interface for reading/writing multiple number types in the buffer, regardless of platform endianness.
2. Common Typed Array Views
| Type | Size (Bytes) | Description |
|---|---|---|
Int8Array |
1 | 8-bit signed integer |
Uint8Array |
1 | 8-bit unsigned integer |
Uint8ClampedArray |
1 | 8-bit unsigned integer (clamped to 0-255) |
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 floating point number |
Float64Array |
8 | 64-bit floating point number |
BigInt64Array |
8 | 64-bit signed BigInt |
3. Basic Usage
You can create a Typed Array directly (which creates the buffer automatically) or pass an existing buffer.
// 1. Create directly
const int32View = new Int32Array(2);
int32View[0] = 42;
int32View[1] = 100;
console.log(int32View); // Int32Array [42, 100]
// 2. From an existing buffer
const buffer = new ArrayBuffer(16);
const view1 = new Uint32Array(buffer); // 16 bytes / 4 bytes per element = 4 elements
const view2 = new Uint8Array(buffer); // 16 bytes / 1 byte per element = 16 elements
view1[0] = 123456;
// view2 shares the same memory, so it sees the bytes of 123456
console.log(view2[0]);
4. Typed Arrays vs. Normal Arrays
| Feature | Normal Array ([]) |
Typed Array |
|---|---|---|
| Content | Any JS value (string, object, number) | Numbers only |
| Size | Dynamic (can grow/shrink) | Fixed length |
| Performance | Slower (engine optimization varies) | Faster (native binary access) |
| Sparse | Can have holes (empty slots) | Dense (always initialized to 0) |
5. Use Cases
- WebGL: Passing geometry data (vertices, colors) to the GPU.
- Canvas API: Manipulating image pixel data (
ImageData.datais aUint8ClampedArray). - Binary File Processing: Parsing custom file formats in the browser.
- WebSockets: Sending/receiving binary packets.
programming/javascript/vanilla/javascript programming/javascript/vanilla/data-types programming/javascript/vanilla/bigint