'Sum All Odd Fibonacci Numbers' code hangs my browser

'Sum All Odd Fibonacci Numbers' code hangs my browser
0

#1

function sumFibs(num) {
var fib = [0,1];
for(var i=fib.length; i<num; i++){
fib[i] = fib[i-2] + fib[i-1];
}
return fibs;
}

sumFibs(10);

My page freezes and I even had to clear my browsing data just to access it again. I think I have made an infinite loop. I want to know how and what should I do to prevent it in the future? TIA :slight_smile:


#2

The code you’ve written should throw an error. You wrote return fibs, but you never defined a variable called fibs. If you change fibs to fib, your code should run fine.

It will return the following array: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

There is no infinite loop in the code presented, but it’s easy to do accidentally with this kind of problem.