Length and ByteLength Properties
You'll learn how to distinguish between the number of elements in a typed array and the total memory it occupies.
Two Ways to Measure Size
When working with typed arrays, you have two related but distinct properties that measure "size":
length: The number of elements in the typed arraybyteLength: The total number of bytes the array occupies in memory
Think of it like counting boxes versus measuring weight. If you have 10 boxes (length), but each box weighs a different amount depending on its type, the total weight (byteLength) will vary.
Why They Differ
Different typed array types use different amounts of memory per element:
const int8 = new Int8Array(10);
console.log(int8.length); // 10 elements
console.log(int8.byteLength); // 10 bytes (1 byte per element)
const int16 = new Int16Array(10);
console.log(int16.length); // 10 elements
console.log(int16.byteLength); // 20 bytes (2 bytes per element)
const float64 = new Float64Array(10);
console.log(float64.length); // 10 elements
console.log(float64.byteLength); // 80 bytes (8 bytes per element)
All three arrays hold 10 elements, but their memory footprints are dramatically different.
When to Use Each
Use length when you care about how many values you're working with—for loops, bounds checking, or logical operations.
Use byteLength when you need to know memory consumption—allocating buffers, network transmission size, or optimizing performance.
Key Takeaway: length counts elements; byteLength measures memory. They're related by the bytes-per-element of your typed array type.