Sum All Odd Fibonacci Numbers - questions on the solustions

Hi all,
I am trying to work out how this solution works, but I’m a bit lost when if(curr % 2 !== 0) return false and how the code continues.
Please could someone explain it? Thank you.

The challenge is from https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers

function sumFibs(num) {
let prev = 0, curr = 1, result = 0;

while(curr <= num){
  //curr=> 1 <= 4
  //curr=> 1 <= 4
  //curr => 2 <= 4
  if(curr % 2 !== 0){
    //1%2 !== 0 => true
    //1%2 !== 0 => true
    //2%2 !== 0 => false (because it returns false,does it continue the codes below? I'm confused in how to continue after)
    result += curr;
    //result => 0 + 1 = 1
    //result => 1 + 1 = 2
  }
  curr += prev;
  //curr => 1 + 0 = 1
  //curr => 1 + 1 = 2
  prev = curr - prev;
  //prev => 1 - 0 = 1
  //prev => 2 - 1 = 1 
}

return result;
}

sumFibs(4);

Its easier to explain if I can compare it to the solution you wrote. Can you post that?


There is no return statement there? I’m not sure what you mean by ‘returns false’. The body of an if statement only runs if the condition is true, but then the code proceeds no matter if the condition was true or false.

This is pretty far into the curriculum for you to not understand how to use if. You may be going much to fast.

Hi,
Thanks for the reply.
Sorry. I shouldn’t use ‘return false’. I understand the if statement only runs if the condition is true. But how does the code proceed if the condition is false?

What would stop the function from running if the condition is false?

All an if statement does is conditionally run the contents of it’s body. It doesn’t stop a function unless the contents of the body say to do so.

Thanks. I’ve just realised why I was stuck. I thought the code stop running when 2%2 !== 0 => false but it only affect result += curr , the code continues to run curr += prev;prev = curr - prev;

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.