# Sum All Odd Fibonacci Numbers help

Sum All Odd Fibonacci Numbers help
0

#1

Why am I getting 10 all the time ?

Your code so far

``````function sumFibs(num) {
var i;
var arr = [1,1];
var result = 0;
var fib = [];
fib[0] = 1;
fib[1] = 1;
for(i=0; arr[i] < num; i++)
{
result = fib[i]+fib[i+1];
fib.push(result);
if(result % 2 === 0){

} else {
arr.push(result);
}

}
var sum = arr.reduce(add, 0);

function add(a, b) {
return a + b;
}
return sum;
}

sumFibs(4000000);
``````

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

Link to the challenge:

#2

The reason your code returns 10 for sumFibs(4000000) is because at the start of the 5th for loop iteration, i = 4, so a[i] (which is arr[4]) is undefined and since undefined is not less than num (4000000), so the for loop condition is false and the for loop is exited. arr looks like [ 1, 1, 3, 5 ], so the sum variable becomes 10 after the reduce and 10 is returned.

Why is arr[4] undefined? Because arr only has 4 elements in it at the time arr[4] is evaluated, so it arr[4] references a 5th element which does not exists, so arr[4] evaluates to undefined.

If you put a console log in at the very last of the for loop code ( as I did below ), you will see what the value of i and arr[i] will be at the beginning of the next iteration.

``````  for(i=0; arr[i] < num; i++) {
result = fib[i]+fib[i+1];
fib.push(result);
if(result % 2 === 0){

}
else {
arr.push(result);
}
console.log('next iteration variable values: i='+ (i+1) + ', arr['+ (i+1) +']='+arr[i+1]+ ', num='+num);
}
console.log(arr);
``````

you will get the following in the console:

next iteration variable values: i=1, arr[1]=1, num=4000000
next iteration variable values: i=2, arr[2]=3, num=4000000
next iteration variable values: i=3, arr[3]=5, num=4000000
next iteration variable values: i=4, arr[4]=undefined, num=4000000
[ 1, 1, 3, 5 ]