Syntax
const buffer = new ArrayBuffer(bytes);
const view = new Uint8Array(buffer);Examples
Creating a Typed Array
The simplest way to work with typed arrays - directly, without manually managing the buffer.
const numbers = new Uint8Array([10, 20, 30, 255]);
console.log(numbers[0]); // 10
console.log(numbers.length); // 4
numbers[0] = 300; // out of range for Uint8Array (0-255)
console.log(numbers[0]); // 44 - silently wraps around (300 - 256)Working with ArrayBuffer Directly
Creating a raw buffer and viewing it through different typed array lenses.
const buffer = new ArrayBuffer(4); // 4 bytes of raw memory
const view8 = new Uint8Array(buffer);
view8[0] = 255;
view8[1] = 1;
const view32 = new Uint32Array(buffer); // same buffer, viewed as one 32-bit number
console.log(view32[0]); // interprets those same 4 bytes differentlyFloat32Array for Numeric Data
A common use case: representing collections of floating-point numbers efficiently.
const positions = new Float32Array([1.5, 2.25, 3.75, 4.0]);
for (const value of positions) {
console.log(value);
}
// Typed arrays support familiar array methods too
console.log(positions.map(v => v * 2));Best practices
- Use typed arrays instead of regular arrays when working with binary data, files, or performance-critical numeric computation - they use less memory and are faster for these cases
- Pick the specific typed array (Int8, Uint16, Float64, etc.) that matches your actual data range and precision needs
- Remember typed array values silently wrap or truncate when out of range, rather than throwing an error - validate input if that matters
- Reach for regular arrays for everyday application code - typed arrays are a specialized tool for binary/numeric-heavy scenarios
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification