DEV Community

Discussion on: JavaScript typed arrays: Unexpected overflow

Collapse
 
lexlohr profile image
Alex Lohr

This is not as much of a quirk as it seems. ++ is supposed to return the result and assign it to the variable. It's neither supposed to evaluate the variable for the result nor to make the calculation in the same type as the variable.

Collapse
 
antogarand profile image
Antony Garand

I consider this a quirk for two reasons:

  1. In C/C++, the answer would be 0 for both variables
  2. The following two snippets don't have the same value
const first = Uint8Array.of(255);
const second = Uint8Array.of(255);
const firstValue = ++first[0];
second[0]++;
const secondValue = second[0];

This is counter-intuitive.

Collapse
 
lexlohr profile image
Alex Lohr

Just because a language is specified different to C/C++ doesn't make it quirky. All of your example are just showing the specified behavior of any flavour of modern ECMAscript.

I would only consider this a quirk if the standard operators suddenly changed the specified behavior to handle typed arrays differently, i.e. if you assigned the result to another field of a Uint8Array and the results would differ or if assignments to untyped variables suddenly exposed the same overflow as the typed array ones.