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
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
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.
I’ll add up to what @ILM 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