skip to content

In JavaScript, what do `new Uint8Array([300, -1, 1.7])` and `new Uint8ClampedArray([300, -1, 1.7])` contain, and why do they differ?

level: middleimportance: should knowfreq 28%

answer

  1. conversion happens on write
  2. truncate first, then low bits
  3. clamp first, then round
  4. exact halves go to even

basics

~20 s

Uint8Array holds 44, 255, 1: it truncates the fraction, then keeps the low 8 bits, so values wrap. Uint8ClampedArray holds 255, 0, 2: it clamps to 0 through 255, then rounds to nearest with ties to even.

solid answer

~40 s

`Uint8Array` holds `[44, 255, 1]` and `Uint8ClampedArray` holds `[255, 0, 2]`. Neither throws, because typed arrays normalise out-of-range numbers on every write. Integer element types use fixed-width conversion: truncate the fraction, then keep only the lowest bits, so 300 becomes `300 - 256 = 44`, -1 becomes 255 through two's complement, and 1.7 becomes 1. `Uint8ClampedArray` is the exception: it saturates at the ends and rounds to the nearest integer, with exact halves going to the even neighbour, so 1.5 and 2.5 both become 2. The consequence shows up in pixel arithmetic, where wrapping turns an overbright 300 into a dark 44 while clamping holds it at 255. The wrap applies at every integer width, so `new Int8Array([128])` holds -128. Float arrays instead round to the nearest value they can represent.

code

javascript · 7 lines
javascript
const wrapped = new Uint8Array([300, -1, 1.7]);
const clamped = new Uint8ClampedArray([300, -1, 1.7]);

console.log(wrapped.join()); // 44,255,1
console.log(clamped.join()); // 255,0,2
console.log(new Int8Array([200, 128]).join()); // -56,-128
console.log(new Uint8ClampedArray([0.5, 1.5, 2.5]).join()); // 0,2,2

go deeper

for a junior

Recall that typed arrays never reject a number: Uint8Array wraps and Uint8ClampedArray saturates. Be able to work out 300 and -1 by hand for both.

for a middle

Explain the order of operations for each type: truncate then keep low bits, against clamp then round with ties to even. Predict 2.5, -1.5 and a signed Int8Array case without running code.

for a senior

Reason from symptom to cause: speckled dark pixels in bright areas, or a counter that jumps backwards, point at a wrap. Say which element type or range check you would use to fix each one.

for a principal

The tradeoff angle is silent failure: no exception ever marks these conversions, so decide where range checks belong in a data pipeline and which element widths a team standardises on for values that may grow.

## A conversion runs on every write A typed array element has a fixed number of bits, while a JavaScript number is a 64-bit float. Each time you store a value, whether through `u8[0] = x`, the constructor, `set` or the results of `map`, the number is converted to fit. **No out-of-range number ever raises an error.** It produces a different number, silently, and that is why these bugs tend to surface as wrong output instead of an exception. ## Integer arrays: truncate, then keep the low bits All the integer element types except `Uint8ClampedArray` use **fixed-width conversion**: 1. Drop the fractional part, moving towards zero, so 1.7 becomes 1 and -1.5 becomes -1. 2. Take the lowest bits of the two's complement form of the result, as many as the element holds. 3. Read those bits back as the element type, signed or unsigned. The effect is arithmetic modulo the type's range: | Expression | Value | Why | |---|---|---| | `new Uint8Array([300])[0]` | `44` | 300 - 256 | | `new Uint8Array([-1])[0]` | `255` | all 8 bits set | | `new Uint8Array([-1.5])[0]` | `255` | truncated to -1 first | | `new Int8Array([200])[0]` | `-56` | 200 - 256 | | `new Int8Array([128])[0]` | `-128` | top bit is the sign | | `new Uint16Array([70000])[0]` | `4464` | 70000 - 65536 | | `new Uint32Array([-1])[0]` | `4294967295` | all 32 bits set | ## Uint8ClampedArray: clamp, then round **`Uint8ClampedArray`** stores the same 8 unsigned bits as `Uint8Array`, but it converts differently. Values above 255 become 255, values below 0 become 0, and anything in between is rounded to the nearest integer. When a number is exactly halfway, it rounds to the **even** neighbour: ```js const halves = new Uint8ClampedArray([0.5, 1.5, 2.5, 3.5]); console.log(halves.join()); // 0,2,2,4 ``` Two things are easy to get wrong here. This is not `Math.round`, which would send 0.5 to 1 and 2.5 to 3. And it is rounding, not truncation, so 1.7 becomes 2 here while `Uint8Array` makes it 1. Clamping also comes first, so `255.5` is held at 255 before any rounding could apply, while `254.5` stays in range and rounds to 254, its even neighbour. ## The same inputs, side by side | Input | `Uint8Array` | `Uint8ClampedArray` | |---|---|---| | `300` | `44` | `255` | | `-1` | `255` | `0` | | `1.7` | `1` | `2` | | `2.5` | `2` | `2` | | `NaN` | `0` | `0` | | `Infinity` | `0` | `255` | ## Which one you want - **Clamping** suits values that represent an intensity, such as colour channels, where too bright should mean as bright as possible. The browser canvas API exposes its pixels this way, through a `Uint8ClampedArray`. A brightness filter that adds 100 to a channel of 200 gets 255 here and 44 with `Uint8Array`, which shows up as dark speckles in bright areas. - **Wrapping** suits values that are defined modulo the width, such as an 8-bit checksum or a counter that is meant to roll over. - **Neither** is right when the value must stay exact. Use a wider element type, or check the range before you store. ## Other element types and small traps - **Float arrays** do not wrap. `new Float32Array([0.1])[0]` reads back as `0.10000000149011612`, the nearest representable value, and a number too large for the type becomes `Infinity`. - **`BigInt64Array` and `BigUint64Array`** take BigInt values, and assigning a Number to an element throws `TypeError`. BigInt values that are out of range wrap in the same modular way. - **An assignment expression keeps the original value.** `(u8[0] = 300)` evaluates to `300`, even though the element now holds `44`, so `const y = (u8[0] = 300)` gives you a value the array does not contain. - **Compound updates convert too.** `u8[0]++` on an element holding 255 gives 0, and on a `Uint8ClampedArray` the same increment stays at 255. - **Results of `map` convert.** A `Uint8ClampedArray` that doubles 200 through `map` gives 255, and a `Uint8Array` gives 144. These rules apply when a value enters a typed array, by whatever route it arrives. A read decodes whatever bits are already there, so reading never clamps or wraps anything.

  • What do `NaN` and `Infinity` become in a `Uint8Array` and in a `Uint8ClampedArray`?
    `NaN` becomes 0 in both. `Infinity` differs: a `Uint8Array` stores 0, because fixed-width conversion treats a non-finite number as 0, while a `Uint8ClampedArray` stores 255, because it clamps by value before anything else. So `-Infinity` gives 0 in both.
  • When is wrapping the behaviour you actually want?
    When the arithmetic is defined modulo the width. An 8-bit checksum can add every byte into a `Uint8Array` element and let it roll over, and a sequence number can do the same. Clamping there would stick at 255 and corrupt the result, so the choice follows from what the value means.
  • Does a `DataView` setter wrap or clamp?
    It wraps. `view.setUint8(0, 300)` stores 44, and `view.setInt16(0, 70000)` stores 4464, using the same fixed-width conversion as the integer typed arrays. There is no clamped setter on a `DataView`, so clamping behaviour needs a `Uint8ClampedArray` or your own range check.

A Uint8Array element is an odometer: push it past its maximum and it rolls over and carries on from zero. A Uint8ClampedArray element is a volume dial: turn it past the maximum and it simply stays at the maximum.

  • Assigning 300 to a Uint8Array element throws a RangeError.
  • A Uint8Array caps values at 255, because that is its maximum.
  • Uint8ClampedArray rounds exact halves upward, the way Math.round does.
  • Uint8ClampedArray truncates fractions, the same as the other integer arrays.
  • Storing -1 in an unsigned element gives 1, because the sign is dropped.