Sum All Odd Fibonacci Numbers - possible infinite loop

Sum All Odd Fibonacci Numbers - possible infinite loop
0.0 0

#1

Hello! I hope you could bear with me and explain me the error I got.
So far all the provided tests went through except for this one:

sumFibs(4000000) should return 4613732.

The reason for failing was provided as follow:

Error: potential infinite loop at line 7

I still haven’t seen why the code could produce an infinite loop (as I’ve set a condition i <= num and there’s no change made to num); and why the other tests went through…

My code so far

function sumFibs(num) {
  var sum = 0;
  var fib = [0, 1, 1];
//get array "fib" of Fibonaci numbers
  for (var i = 2; i <= num; i++) {
    if (i == (fib[fib.length - 1] + fib[fib.length - 2])) {
      fib.push(i);
    }
  }

//sum all odd numbers in it
  for (var j = 0; j < fib.length; j++) {
    if (fib[j] % 2 != 0) {
      sum += fib[j];
    }
  }
  return sum;
}

sumFibs(4000000);

Link to the challenge:


#2

See the error message:

Error: potential infinite loop at line 7. To disable loop protection, write
// noprotect
as the first line. Beware that if you do have an infinite loop in your code this will crash your browser.

The code you’ve wrote looks like it could, under certain circumstances, lead to an infinite loop - this error will crop up if you mutate the array you’re iterating over in such away that the more you iterate the larger the array you’re iterating over gets (so this is a good reason to avoid doing this, to modify your code to avoid it happening). It is just a warning, and in this case you can suppress the warning with no ill effects.