Creating Typed Arrays from Length
You'll learn how to instantiate typed arrays by specifying how many elements you need, creating zero-filled buffers ready for binary data.
The Core Idea
When you create a typed array by passing a single number to its constructor, JavaScript allocates a buffer large enough to hold that many elements of the specified type and automatically fills every slot with zeros. This is different from regular arrays, where new Array(5) creates empty slots—typed arrays guarantee initialized memory.
Think of it like ordering a custom ice cube tray: you specify how many cubes you want, and the manufacturer delivers a tray with exactly that many compartments, all empty (zero) and ready to fill.
How It Works
Pass an integer to any typed array constructor to specify the element count:
// Create an Int16Array with 4 elements (8 bytes total: 4 × 2 bytes each)
const int16s = new Int16Array(4);
console.log(int16s); // Int16Array(4) [0, 0, 0, 0]
// Create a Float32Array with 3 elements (12 bytes total: 3 × 4 bytes each)
const floats = new Float32Array(3);
console.log(floats); // Float32Array(3) [0, 0, 0]
// Create a Uint8Array with 10 elements (10 bytes total)
const bytes = new Uint8Array(10);
console.log(bytes.length); // 10
console.log(bytes[0]); // 0
Notice every element starts at zero—no undefined values, no empty slots. The underlying buffer is created automatically based on the type and count you specify.
Why Zero-Filling Matters
Zero-initialization ensures predictable behavior and memory safety. You know exactly what's in your buffer from the start, which is critical when working with binary protocols, file formats, or numeric computations where uninitialized data could cause serious bugs.
Key Takeaway: Creating a typed array from a length allocates a zero-filled buffer with exactly that many elements, giving you a clean, predictable starting point for binary data manipulation.