Creating Typed Arrays from Iterables
What you'll learn: How to construct typed arrays directly from regular arrays, array-like objects, and other iterable sources instead of starting from a fixed length.
Beyond Fixed-Length Construction
You've already seen how to create typed arrays with a specific length (like new Uint8Array(10)). But often you have existing data you want to convert into binary form—perhaps a list of measurements, pixel values, or sensor readings already stored in a regular JavaScript array.
Typed arrays accept iterables in their constructors, meaning you can pass in regular arrays, Sets, Map values, or any object that can be iterated over. The typed array will consume each value, coerce it to the appropriate numeric type, and store it in the underlying buffer.
Basic Syntax
// From a regular array
const numbers = [10, 20, 30, 40];
const uint8 = new Uint8Array(numbers);
// Uint8Array(4) [10, 20, 30, 40]
// From another typed array (creates a copy)
const int16 = new Int16Array(uint8);
// Int16Array(4) [10, 20, 30, 40]
// From an array-like object
const arrayLike = { 0: 5, 1: 15, 2: 25, length: 3 };
const fromLike = new Uint32Array(Array.from(arrayLike));
// Uint32Array(3) [5, 15, 25]
What Happens to the Values
When constructing from an iterable, each value is converted to fit the target type. Values exceeding the type's range will wrap around (like overflow), and non-integers get truncated:
const floats = [1.7, 2.9, 300];
const uint8 = new Uint8Array(floats);
// Uint8Array(3) [1, 2, 44] (300 wraps to 44 in 8-bit)
Key Takeaway: Typed arrays can be constructed directly from any iterable, automatically converting and storing values according to the array's numeric type—perfect for transforming existing data into binary format.