Remaider check creates an infinte loop

Can someone explain to me why adding the remaider check in the if statement creates an infinite loop? The code works fine without the remainder check and I can’t unedrstand why it is happening since the if statement has nothing to do with incrementing i.

The code:


function sumFibs(num) {
let fibArr = [1, 1];
let i = 0;

while (i <= num){
  i = fibArr[fibArr.length - 1] + fibArr[fibArr.length -2];
  if (i <= num && i % 2 == 1) {
    fibArr.push(i);
  }
}
console.log(fibArr)
return fibArr.reduce(function(a, b) {
  return a + b;
  });
}
sumFibs(4);

My browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36.

Challenge: Sum All Odd Fibonacci Numbers

Link to the challenge:

Notice that i is changed based on the values present in the fibArr. At the same time fibArr is having new value pushed only if i is odd. Do you see where this is going?

1 Like

Oh shiiiiii, thanks man, this has stumped me for a good couple hours