Even Fibonacci Numbers

Hi!

I looked up to the decision on Even Fibonacci Numbers:


const fiboEvenSum = (number) => {
  if (number <= 1) {
    return 0;
  } else {
    let evenSum = 0,
      prevFibNum = 1,
      // According to problem description our Fibonacci series starts with 1, 2
      fibNum = 2; 
    for (let i = 2; fibNum <= number; i++) {
      if (fibNum % 2 == 0) {
        evenSum += fibNum;
      }
      [prevFibNum, fibNum] = [fibNum, prevFibNum + fibNum];
    }
    return evenSum;
  }
};

And I would like to know, why we should override variables like this [prevFibNum, fibNum] = [fibNum, prevFibNum + fibNum];
and why it doesnt work like this

prevFibNum = fibNum;
fibNum = fibNum + prevFibNum ;

THANK YOU VERY MUCH IN ADVANCE!

Using an array is just a smart way to reassign fibNum and prevFibNum without the need for an extra variable.

Otherwise, you’d have to write it like this:

let temp = prevFibNum;
prevFibNum = fibNum;
fibNum = fibNum + temp;

Maybe this mini piece of code makes it clearer:

let a = 5;
let b = 7;
[a,b] = [b,a];
console.log(a,b) // 7,5

this for loop does’t look good, try replacing it with a while loop which is easier to maintain or with a for loop desinged for fibNum. You got the concept, all you should do is improve your code formatting a bit

1 Like

Yeah, the fact that your iteration variable i is not in all three positions in the for loop head is a read flag that you probably want a different type of loop.

starting values, prevFibNum = 2 and fibNum = 3

line 1:
prevFibNum = fibNum so prevFibNum = 3

line 2:
fibNum = fibNum + prevFibNum so fibNum = 3 + 3, so fibNum = 6

end values:
prevFibNum = 3, fibNum = 6

6 is not in the Fibonacci series, fibNum at the end of this should have had value of 5

2 Likes

I’ll add up to what @ilenia said, after an iteration you want to assign fibNum value to prevFibNum and then add prevFibNum to fibNum, first, switch the order of the actions, first add and then assign. second, consider the equation to get FibNum:
fibNum = fibNum + prevFibNum - prevFibNum
there’s a part of the equation where fibNum will be the next number in the series, do the rest of math yourself

1 Like

Thank you all very much for your answers!!
Especially, @harel_avv and @ilenia you both made everything absolutely clear!