Advertisement
Advanced JavaScript, ArrayBuffer, TypedArrays & Binary Data

How do you handle out-of-range writes to a TypedArray safely?

Short answer

TypedArrays silently clamp or wrap out-of-range values instead of throwing (except Uint8ClampedArray, which clamps to 0-255). You must validate values yourself before writing if you need strict range enforcement.

Save JavaScript mock interview
Advertisement
AModel answer
TypedArrays silently clamp or wrap out-of-range values instead of throwing (except Uint8ClampedArray, which clamps to 0-255). You must validate values yourself before writing if you need strict range enforcement.
const arr = new Uint8Array(1);
arr[0] = 300;
console.log(arr[0]); // 44 (300 % 256)

const clamped = new Uint8ClampedArray(1);
clamped[0] = 300;
console.log(clamped[0]); // 255
Real-world example
Uint8ClampedArray is exactly what Canvas ImageData uses so pixel values never overflow past 255.
Likely follow-ups
  • Why doesn't JavaScript throw a RangeError here like some languages do?
Related topics