Sub topic 5
What Happens When a Value Does Not Fit
A regular JavaScript array can hold any value. A typed array element is a fixed number of bits, so every value you write has to be converted to fit those bits. The conversion is silent: no exception, no warning, just a different number when you read it back. This chapter covers the exact rules so you can predict the result of any write and catch the cases where silent conversion would cause a bug.
This chapter assumes you know how to create typed arrays over a buffer, know the element types and their sizes from the previous chapter, and are comfortable with binary and hexadecimal numbers.
The conversion pipeline
Every write to a typed array goes through the same steps. These include index assignment (a[i] = v), constructing from an array (new Uint8Array([...])), set(), fill(), and from(). First the value becomes a Number. Then the element type's own rule turns that Number into something that fits.
BigInt64Array and BigUint64Array use their own path. They require a BigInt and throw a TypeError for a Number. A later chapter covers them.
Step one: everything becomes a Number
The first step is the ordinary ToNumber coercion, the same one unary + performs. Strings, booleans, null, undefined, and objects with valueOf are all accepted:
const a = new Uint8Array(['42', '0x10', 'abc', '', true, null, undefined]);
console.log(a); // Uint8Array(7) [42, 16, 0, 0, 1, 0, 0]
const b = new Uint8Array(1);
b[0] = { valueOf() { return 300; } };
console.log(b[0]); // 44
try {
b[0] = Symbol('x');
} catch (e) {
console.log(e instanceof TypeError); // true
}'abc' and undefined become NaN, which integer types store as 0. Bad input can therefore show up as a real-looking zero rather than an error. When you fill a buffer from parsed text or user input, validate before writing.
Integer types: truncate, then wrap
For Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, and Uint32Array, the rule has four parts:
NaN,Infinity, and-Infinitybecome 0.- The number is truncated toward zero. 1.7 becomes 1 and -1.9 becomes -1. It does not round and does not floor.
- The result is reduced modulo 2^n, where n is the element's bit width. Only the low n bits are kept.
- For signed types, those n bits are read as two's complement. If the top bit is set, the value is negative.
console.log(new Uint8Array([255, 256, -1, 1.7])); // Uint8Array [255, 0, 255, 1]
console.log(new Int8Array([127, 128])); // Int8Array [127, -128]
console.log(new Int8Array([200, -129, -1.9])); // Int8Array [-56, 127, -1]
console.log(new Uint8Array([-1.9, NaN, Infinity])); // Uint8Array [255, 0, 0]
console.log(new Uint16Array([65541, 70000])); // Uint16Array [5, 4464]
console.log(new Int32Array([2 ** 31])); // Int32Array [-2147483648]
console.log(new Uint32Array([-1])); // Uint32Array [4294967295]Here is how 200 goes into an Int8Array. 200 is already an integer below 256, so the modulo step leaves it as 0b11001000. The top bit is set, so the value is read as 200 − 256 = −56. For -1.9 in a Uint8Array, truncation gives -1, and -1 modulo 256 is 255.
Writing the rule yourself
Reimplementing the rule is a good way to check that you understand it:
function toInt8(value) {
let n = Number(value);
if (!Number.isFinite(n)) return 0; // NaN, Infinity, -Infinity
n = Math.trunc(n); // toward zero
const m = ((n % 256) + 256) % 256; // modulo that is always non-negative
return m >= 128 ? m - 256 : m; // two's complement
}
const samples = [200, -129, -1.9, 1e10, NaN, '300'];
const native = new Int8Array(samples);
console.log(samples.map(toInt8)); // [-56, 127, -1, 0, 0, 44]
console.log(Array.from(native)); // [-56, 127, -1, 0, 0, 44]The % 256 step is needed because JavaScript's % keeps the sign of the dividend, so -1 % 256 is -1, not 255.
The link to bitwise operators
You may already use these conversions without the typed array names. JavaScript's bitwise operators apply the same 32-bit rules:
| Typed array element | Equivalent expression | Example | Column | Column |
|---|---|---|---|---|
| `Int32Array` | `x \ | 0` | `2 ** 31 \ | 0` is `-2147483648` |
| `Uint32Array` | `x >>> 0` | `-1 >>> 0` is `4294967295` | ||
| `Uint8Array` | `x & 0xff` (for integer `x`) | `300 & 0xff` is `44` | ||
| `Int8Array` | `(x << 24) >> 24` | `(200 << 24) >> 24` is `-56` |
This equivalence helps when you port C or Java code that depends on integer overflow.
Uint8ClampedArray: saturate and round
Uint8ClampedArray was designed for canvas pixel data, where an overflowing brightness should stay at full white instead of wrapping to black. Its rule is different:
NaNbecomes 0.- Values below 0 become 0, and values above 255 become 255.
Infinitybecomes 255. - Fractions are rounded to the nearest integer, and ties go to the even neighbour.
console.log(new Uint8ClampedArray([300, -5, 1.5])); // Uint8ClampedArray [255, 0, 2]
console.log(new Uint8ClampedArray([0.5, 2.5, 3.5, 254.5])); // [0, 2, 4, 254]
console.log(new Uint8ClampedArray([Infinity, -Infinity, NaN])); // [255, 0, 0]Float types: rounding instead of wrapping
Float64Array stores a JavaScript Number exactly, because Numbers are already 64-bit floats. Float32Array rounds to the nearest 32-bit float, which keeps about 7 significant decimal digits:
const f = new Float32Array([0.1, 16777217, 1e40, -1e40, NaN]);
console.log(f[0]); // 0.10000000149011612
console.log(f[1]); // 16777216
console.log(f[2], f[3]); // Infinity -Infinity
console.log(f[4]); // NaN
console.log(Math.fround(0.1) === f[0]); // trueFloat types do not wrap. Too-large values become Infinity, and NaN stays NaN. Integers above 2^24 (16,777,216) cannot all be represented, so 16777217 rounds to its even neighbour. Math.fround applies the same rounding, which is useful in tests: compare f[i] to Math.fround(expected) rather than to expected.
A common bug looks like this:
const f32 = new Float32Array(1);
f32[0] = 0.1;
console.log(f32[0] === 0.1); // falseThe stored value is correct. You are just comparing a float32 value against a float64 one.
Recent engines also ship Float16Array (ES2025) with Math.f16round. It follows the same rounding model with only about 3 significant digits and a maximum finite value of 65504.
Summary of the rules
| Type | Out of range | Fraction | NaN | Infinity |
|---|---|---|---|---|
| `Int8`/`Int16`/`Int32Array` | Wraps modulo 2^n, read as signed | Truncated toward zero | 0 | 0 |
| `Uint8`/`Uint16`/`Uint32Array` | Wraps modulo 2^n | Truncated toward zero | 0 | 0 |
| `Uint8ClampedArray` | Clamped to 0 or 255 | Rounded half to even | 0 | 255 (or 0 for -Infinity) |
| `Float32Array` | Becomes ±Infinity | Rounded to nearest float32 | NaN | ±Infinity |
| `Float64Array` | Stored as is | Stored as is | NaN | ±Infinity |
Conversion between typed arrays
The same rules apply when the source is another typed array. Building a Uint8Array from an Int16Array, or calling set() across types, converts element by element. It does not copy raw bytes:
const wide = new Int16Array([300, -1, 128]);
console.log(new Uint8Array(wide)); // Uint8Array [44, 255, 128]
console.log(new Int8Array(wide)); // Int8Array [44, -1, -128]
const target = new Uint8ClampedArray(3);
target.set(wide);
console.log(target); // Uint8ClampedArray [255, 0, 128]If you want the raw bytes of the Int16Array instead, create a Uint8Array over its buffer: new Uint8Array(wide.buffer, wide.byteOffset, wide.byteLength).
Writes outside the array are ignored
One more silent case: a write to an index outside the array does nothing. Unlike a regular array, a typed array never grows, and integer-like keys never become ordinary properties.
const small = new Uint8Array(2);
small[5] = 1;
small[-1] = 1;
small['1.5'] = 1;
console.log(small.length, small[5], small[-1]); // 2 undefined undefined
console.log(Object.keys(small)); // ['0', '1']Catching overflow on purpose
The engine never reports lost information, so check for it yourself where it matters. One way is a checked writer:
function setUint8Checked(arr, index, value) {
if (index < 0 || index >= arr.length || !Number.isInteger(index)) {
throw new RangeError(`index ${index} out of bounds`);
}
if (!Number.isInteger(value) || value < 0 || value > 255) {
throw new RangeError(`${value} does not fit in a Uint8`);
}
arr[index] = value;
}
const out = new Uint8Array(4);
setUint8Checked(out, 0, 200);
try {
setUint8Checked(out, 1, 256);
} catch (e) {
console.log(e.message); // "256 does not fit in a Uint8"
}Another way is a round trip: write the value, read it back, and compare. If arr[i] !== value after the write, the value did not fit. For float types, use Object.is so that a stored NaN is not reported as a mismatch.
Exercise
Predict the contents of new Int8Array([129, -130, 255.9, '-0.5']) and new Uint8ClampedArray([129, -130, 255.9, '-0.5']).
Show answer
Int8Array [-127, 126, -1, 0]. 129 wraps to 129 − 256 = −127. −130 modulo 256 is 126, which is below 128 and so stays positive. 255.9 truncates to 255, read as −1. '-0.5' becomes −0.5 and truncates to 0. Uint8ClampedArray [129, 0, 255, 0]. 129 is in range, −130 clamps to 0, 255.9 clamps to 255, and −0.5 clamps to 0.
Exercise
A loop sums pixel values with sums[i] += pixel into a Uint16Array, and the totals sometimes come out smaller than expected. Explain why and give two fixes.
Show answer
Uint16Array elements hold at most 65535. When a sum passes that, it wraps modulo 65536, so it drops to a small number. Fix 1: accumulate into a wider type, such as Uint32Array or Float64Array, or into a plain Number variable. Fix 2: if the result must be 16-bit, decide on the overflow behaviour explicitly, for example clamp with Math.min(sum, 65535) before writing.
Exercise
Why does new Float32Array([0.3])[0] === 0.3 print false, and what comparison should a test use instead?
Show answer
Float32Array rounds 0.3 to the nearest 32-bit float, 0.30000001192092896, while the literal 0.3 is a 64-bit float. Compare against Math.fround(0.3), which applies the same rounding, or check that the difference is within a small tolerance.