Need assistance in Sum All Odd Fibonacci Numbers


Challenge Name

Sum All Odd Fibonacci Numbers has an issue.

Issue Description

So I tried the code within my console, it giving back all the correct answer, however the freecodecamp testing suite is showing that I do not have the correct answer.

These are the values I am supplying to my function, currently using the latest 
version of  visual code studios console to test them. They return the answer as 
below but for the FCC test says that the values returned are not correct.

sumFibs(4); // should return 5
sumFibs(75024); // should return 60696;
sumFibs(75025); // should return 135721;

Browser Information

User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0.


Your Code

let a = 0;
let b = 1;
let arr = [];

function sumFibs(num) {
    if (num == 1)
        return 1;
    if (a <= num || a == 1) {
        b += a;
        a = b - a;
        return sumFibs(num);
    return arr.filter(x => { return x % 2 !== 0; }).reduce((a, b) => { return a + b; });


```<img src="//" width="690" height="388">


Code that uses global variables generally fail, because the value in the globals are retained and carried on to the next test. See this repl:

You may want to revise your code so it doesn’t use global variables.


If you care to give me some of your time, much appreciated :slight_smile:

a) Why does the same occur after console.log(4000000), not for the other values?

b) How do I introduce variables into the local space, for recursion? Any ideas? Without using a for loop - I wanna see if I can practice without using them


Probably because the array retains the values it contains for calculating sumFibs(4000000). When you do sumFibs(5), the values from the previous call are still there, and no further pushing to the array is needed because 5 is much smaller than 40000000, so those last calls have the same value.

You could write a helper function that does the actual recursion, and call that in the sumFibs function. Then move the globals inside sumFibs.

function sumFibs(num) {
  let a = 0;
  let b = 1;
  let arr = [];

  return fib(num, a, b, arr);

function fib(num, a, b, arr) {
  // the old `sumFibs` body goes here, with some modifications