What are Typed Arrays?

Typed Arrays provide a mechanism for accessing raw binary data efficiently. They're essential for WebGL, audio processing, file I/O, and any performance-critical binary operations.

ArrayBuffer and Views

// ArrayBuffer - raw binary data container
const buffer = new ArrayBuffer(16); // 16 bytes
console.log(buffer.byteLength); // 16

// Create typed array views
const int8View = new Int8Array(buffer);
const uint16View = new Uint16Array(buffer);

// Views share the same buffer
int8View[0] = 42;
console.log(uint16View[0]); // Reads same memory

Typed Array Types

// 8-bit signed integer (-128 to 127)
const int8 = new Int8Array([1, 2, 3]);

// 8-bit unsigned integer (0 to 255)
const uint8 = new Uint8Array([255, 254, 253]);

// 16-bit signed integer
const int16 = new Int16Array([1000, 2000]);

// 32-bit floating point
const float32 = new Float32Array([3.14, 2.71]);

// 64-bit floating point
const float64 = new Float64Array([Math.PI, Math.E]);

// Clamped 0-255 (for canvas)
const clamped = new Uint8ClampedArray([300, -10, 128]);
console.log(clamped); // [255, 0, 128]

Creating Typed Arrays

// From length
const arr1 = new Uint8Array(10);

// From array
const arr2 = new Uint8Array([1, 2, 3, 4, 5]);

// From ArrayBuffer
const buffer = new ArrayBuffer(16);
const arr3 = new Uint8Array(buffer);

// From buffer with offset and length
const arr4 = new Uint8Array(buffer, 4, 4);

// From another typed array
const arr5 = new Uint16Array(arr2);

DataView for Mixed Types

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

// Write different types to same buffer
view.setInt8(0, 127);
view.setUint16(1, 65535, true); // little-endian
view.setFloat32(4, 3.14159, false); // big-endian

// Read back
console.log(view.getInt8(0)); // 127
console.log(view.getUint16(1, true)); // 65535
console.log(view.getFloat32(4, false)); // 3.14159

Real-World: Image Processing

function grayscale(imageData) {
    const pixels = imageData.data; // Uint8ClampedArray
    
    for (let i = 0; i < pixels.length; i += 4) {
        const r = pixels[i];
        const g = pixels[i + 1];
        const b = pixels[i + 2];
        
        // Calculate grayscale
        const gray = 0.299 * r + 0.587 * g + 0.114 * b;
        
        pixels[i] = pixels[i + 1] = pixels[i + 2] = gray;
        // pixels[i + 3] is alpha, leave unchanged
    }
    
    return imageData;
}

Key Takeaways

← Back More Tutorials →