Creating an array of fibonachi numbers:
function sumFibs(num) {
var list = [1,1];
var next = list[list.length-1] + list[list.length-2];
while (true) {
if (next<=num) {
list.push(next);
} else {
return list;
}
}
}
sumFibs(10);
This gives me infinite loop.
If I add next = list[list.length-1] + list[list.length-2]; after list.push(next); it works fine.
Why?
nextnornumin the body of the loop, how could the conditionnext <= numever switch from being true to being false? Of course you have an infinite loop.nextvariable once, outside of the loop, so nothing changes inside the loop to ever fufill the return condition. BTW, you should use that condition as the condition for thewhileloop, instead oftrue, and return after the loop.nextis a Primitive value so it's not changing. The length oflistis changing as you're pushing onto it.