Loop is not breaking at said limit HELP!

Tell us what’s happening:

I am trying to push fibinacci sequence in array till its less than or equal to provided number. but loop doesnt stop at provided number. Please Help whats missing??

Your code so far


function sumFibs(num) {
let arr = [1, 1];
for (let i = 2; i <= num; i++){
  arr[i] = arr[i-2]+arr[i-1];
}
console.log(arr)
return arr.filter(x => x % 2 != 0).reduce(function sum(a,b){return a+b});
}

console.log(sumFibs(6));

Your browser information:

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

Challenge: Sum All Odd Fibonacci Numbers

Link to the challenge:

Hello~!

I loaded your function, and my console shows this array:

[ 1, 1, 2, 3, 5, 8, 13 ]

It does look like your loop is terminating at the condition you’ve set - but the condition isn’t doing what you think it is.

The challenge asks for the sum of Fibonacci numbers less than or equal to num, but your loop is generating the first num Fibonacci numbers (plus one more).

In your loop, i is the index of the arr array. So i <= num doesn’t say "Loop while the next number is less than or equal to num", but instead says "Loop while the last index of arr is less than or equal to num".

1 Like

if it says "Loop while the last index of arr is less than or equal to num ". then should it terminate at arr[4]??

Not for the function call in your code - num is 6, there.
So it loops 5 times, for i values of 2, 3, 4, 5, and 6.