Reduce wrongly returning infinity

when I try to use math power in reduce it’s not working as expected and returns infinity

const array1 = [1,2,3,4];

const initialValue = 0;
const sumWithInitial = array1.reduce(
  (a,b) => a + Math.pow(b, b + a),
  0
);

console.log(sumWithInitial);

but if there’s only 1-3 numbers in arr1 it works as intended

>Solution :

As of the last iteration, you’re exceeding the capacity of the JavaScript number type (which is an IEEE-754 double-precision binary floating point value). It has nothing to do with reduce, it’s just that Math.pow(4, 4 + 531450) (the last value produced by your reduce loop) goes past the limit:

console.log(Math.pow(4, 4 + 531450));

You can see when pow will do that via the Number::exponentiate abstract operation in the specification (in the text, infinity is denoted by +∞𝔽, negative infinity by -∞𝔽). This is just a fact of trying to use a 64-bit value to try to represent a truly, truly, truly massive number.

Leave a Reply