Sub topic 4
Choosing an Element Type
This chapter assumes you know how to create an ArrayBuffer and wrap it in a typed array, as covered in the previous two chapters. It also assumes you know the difference between integers and floating-point numbers, and that you can read hexadecimal.
Every typed array has one fixed element type. That type decides three things: how many bytes each element uses, which values it can hold exactly, and what you get back when you read it. Choosing the type is usually the first design decision you make when you work with binary data.
The Element Types at a Glance
JavaScript has eleven typed array constructors that work in every current engine. A twelfth, Float16Array, was added in ES2025.
| Constructor | Bytes | Value range | Read as | Rough C equivalent |
|---|---|---|---|---|
| `Int8Array` | 1 | −128 to 127 | Number | `int8_t` |
| `Uint8Array` | 1 | 0 to 255 | Number | `uint8_t` |
| `Uint8ClampedArray` | 1 | 0 to 255 (clamped) | Number | `uint8_t` |
| `Int16Array` | 2 | −32,768 to 32,767 | Number | `int16_t` |
| `Uint16Array` | 2 | 0 to 65,535 | Number | `uint16_t` |
| `Int32Array` | 4 | −2,147,483,648 to 2,147,483,647 | Number | `int32_t` |
| `Uint32Array` | 4 | 0 to 4,294,967,295 | Number | `uint32_t` |
| `Float16Array` | 2 | about ±65,504, ~3 significant digits | Number | `_Float16` |
| `Float32Array` | 4 | about ±3.4×10³⁸, ~7 significant digits | Number | `float` |
| `Float64Array` | 8 | about ±1.8×10³⁰⁸, ~15–17 significant digits | Number | `double` |
| `BigInt64Array` | 8 | −2⁶³ to 2⁶³−1 | BigInt | `int64_t` |
| `BigUint64Array` | 8 | 0 to 2⁶⁴−1 | BigInt | `uint64_t` |
The names follow a pattern. Int means signed and Uint means unsigned. Float means IEEE 754 floating point. The number is the width in bits. Uint8ClampedArray is the odd one out. It stores the same bytes as Uint8Array, but it handles out-of-range writes differently. The next chapter covers that difference.
Asking a Type for Its Size
Every constructor and every instance has a BYTES_PER_ELEMENT property. Use it in your code instead of writing literal 2s, 4s, and 8s.
const types = [
Int8Array, Uint8Array, Uint8ClampedArray,
Int16Array, Uint16Array,
Int32Array, Uint32Array,
Float32Array, Float64Array,
BigInt64Array, BigUint64Array,
];
for (const T of types) {
console.log(T.name.padEnd(18), T.BYTES_PER_ELEMENT);
}
// Int8Array 1
// Uint8Array 1
// ...
// BigUint64Array 8
const f = new Float32Array(10);
console.log(f.BYTES_PER_ELEMENT, f.length, f.byteLength); // 4 10 40length counts elements and byteLength counts bytes. They are equal only for the 1-byte types. Mixing the two up is a common cause of off-by-a-factor bugs. A typical case is passing length to an API that expects a byte count.
const buf = new ArrayBuffer(16);
console.log(new Uint8Array(buf).length); // 16
console.log(new Int16Array(buf).length); // 8
console.log(new Float64Array(buf).length); // 2The Criteria for Choosing
Four questions settle almost every choice:
- Is the type already fixed? If a file format, a network protocol, or a browser API specifies the type, use that type. You have nothing left to decide.
- Do the values have fractional parts? If yes, you need a float type. If no, use an integer type.
- What range is needed? Pick the narrowest type that holds every value you might store. Include the sign.
- Is memory or bandwidth the bottleneck? If so, a narrower type, or
Float32instead ofFloat64, can halve or quarter the size, at a cost in range or precision.
Types Dictated by the Platform
Many web APIs expect one specific type, and passing a different one either throws or gives wrong results:
| Context | Expected type |
|---|---|
| Raw bytes: `fetch`, `Blob`, `TextEncoder`, crypto | `Uint8Array` |
| Canvas `ImageData.data` | `Uint8ClampedArray` |
| Web Audio sample buffers | `Float32Array` |
| WebGL/WebGPU vertex positions | usually `Float32Array` |
| WebGL index buffers | `Uint16Array` or `Uint32Array` |
| `crypto.getRandomValues` | any integer type (not float) |
Uint8Array is the general-purpose byte type. When you just need "some bytes", use it.
Precision: Float32 Versus Float64
A JavaScript Number is a 64-bit float, so Float64Array stores Numbers without any loss. Float32Array rounds every value to the nearest 32-bit float when you write it. When you read the value back, it is widened to a Number, and the rounding error becomes visible:
const f32 = new Float32Array([0.1, 16777217, 1e39]);
console.log(f32[0]); // 0.10000000149011612
console.log(f32[1]); // 16777216 (2^24 + 1 is not representable)
console.log(f32[2]); // Infinity (overflows float32)
console.log(f32[0] === 0.1); // false
console.log(f32[0] === Math.fround(0.1)); // trueMath.fround performs the same rounding without an array. Use it when you compare against values that have been stored in a Float32Array.
Float32 can represent every integer only up to 2²⁴ (16,777,216). Float64 can represent every integer up to 2⁵³. If you store integer IDs or timestamps in a float array, those limits apply.
Float16Array goes further. It saves memory for machine-learning weights and GPU textures, but it keeps only about three significant digits. Check for support before you use it:
if (typeof Float16Array !== 'undefined') {
const h = new Float16Array([1.1, 70000]);
console.log(h[0], h[1]); // 1.099609375 Infinity
}Integer Width and Signedness
For integers, pick the narrowest type that covers the full range, sign included. A list of 8-bit sensor readings between −40 and 85 fits in Int8Array. Port numbers fit in Uint16Array. Millisecond durations up to about 49 days fit in Uint32Array.
A common pattern is to choose the width at runtime from the largest value you will store, as you would for a mesh index buffer:
function smallestUintType(maxValue) {
if (maxValue <= 0xff) return Uint8Array;
if (maxValue <= 0xffff) return Uint16Array;
if (maxValue <= 0xffffffff) return Uint32Array;
return BigUint64Array;
}
const vertexCount = 70000;
const IndexArray = smallestUintType(vertexCount - 1);
const indices = new IndexArray(3 * 1000);
console.log(IndexArray.name, indices.byteLength); // Uint32Array 12000The savings add up quickly:
const n = 1_000_000;
console.log(new Float64Array(n).byteLength); // 8000000
console.log(new Float32Array(n).byteLength); // 4000000
console.log(new Uint16Array(n).byteLength); // 2000000
console.log(new Uint8Array(n).byteLength); // 1000000Gotcha: Uint32 and Bitwise Operators
Reading a Uint32Array element gives you a non-negative Number. JavaScript's bitwise operators, however, convert their operands to signed 32-bit integers. If you mix the two, large values turn negative:
const u = new Uint32Array([0xffffffff, 0x80000000]);
console.log(u[0]); // 4294967295
console.log(u[0] | 0); // -1
console.log(u[1] & 0xff00_0000); // -2147483648
console.log((u[1] & 0xff00_0000) >>> 0); // 2147483648Apply >>> 0 to bring a result back into the unsigned range. You can also write the result straight into a Uint32Array, because the store reinterprets it as unsigned.
What You Read Back
Whatever the element type, reading an element gives you an ordinary Number, except for the two 64-bit integer types, which give BigInt. The narrow storage type is not kept on the value you read.
const i8 = new Int8Array([-5]);
const x = i8[0];
console.log(typeof x, x * 100); // "number" -500, no 8-bit overflow hereArithmetic happens in full Number precision. Narrowing happens only when you write the result back into an array. Knowing where that conversion happens is the key to predicting typed array behaviour. The next chapter covers the rules for wrapping, truncation, and clamping. The BigInt types have their own chapter later in the tutorial.
Exercise
You need to store 2 million temperature readings in degrees Celsius with one decimal place (for example 21.4), ranging from −50.0 to 60.0. Memory is tight. Name two reasonable element types and the trade-off between them.
Show answer
Float32Array (8 MB) stores the values directly and keeps about 7 significant digits, which is plenty. Int16Array (4 MB) works if you store tenths of a degree as integers (−500 to 600) and divide by 10 when reading. It halves the memory but you have to scale every read and write yourself.
Exercise
What does this print, and why? const a = new Float32Array([0.5, 0.2]); console.log(a[0] === 0.5, a[1] === 0.2);
Show answer
It prints true false. 0.5 is a power of two and exactly representable in float32, so it survives the round-trip. 0.2 is rounded to the nearest float32 (0.20000000298023224), which is a different Number from the float64 literal 0.2.
Exercise
const u = new Uint32Array([0xdeadbeef]); What do u[0] ^ 0 and (u[0] ^ 0) >>> 0 evaluate to, and which one equals u[0]?
Show answer
u[0] ^ 0 is -559038737, because bitwise operators convert to signed 32-bit integers. (u[0] ^ 0) >>> 0 is 3735928559, which equals u[0].
Exercise
Write a one-line expression that gives the number of bytes needed for 500 elements of whatever typed array constructor is stored in the variable T, without hard-coding a size.
Show answer
500 * T.BYTES_PER_ELEMENT