I need your feedback on Project Euler: Problem 2: Even Fibonacci Numbers

Although I managed to solve this problem, I feel that my code isn’t that of a professional programmer, so please I need your feedback on my code

function fiboEvenSum(n) {
  let sequence = [0, 1], accumulator = 0, i = 0, total = 0;

  while (accumulator <=n){
      sequence.push(sequence[i] + sequence[i+1]);
      accumulator =sequence[i] + sequence[i+1];
      if (accumulator % 2 === 0 && accumulator <= n){
         total+= accumulator;
      }
      i++;
  }
  return total  
}

console.log(fiboEvenSum(4000000));

Generally it’s fine, few minor problems:

  1. Keeping the whole sequence seems unnecessary
  2. Not well structured while loop - you’re immediately re-assign accumulator which makes loop condition almost pointless and forces you to check if it’s less than n again later - think if you can avoid this
  3. Naming is a bit confusing, normally you would expect something called accumulator to accumulate sum

If, let’s say, you start with the following variables:

let [prev, next] = [0, 1];
let sum = 0;

this will make this function way cleaner in my opinion

Thanks a lot my bro for this invaluable feedback . I have made some modifications to my code and now it looks concise and clear. Please check it.

function fiboEvenSum(n) {
  let [prev, next] = [0, 1], value = 0, total = 0;

  while (next <n){
      if (value % 2 === 0){
         total += value;
      }
      value = prev + next;
      prev = next; 
      next = value;
  }
  return total;  
}

console.log(fiboEvenSum(60));```

Good job! A small hint for you :wink: :

let [a, b] = [0, 1];
[a, b] = [b, a];
console.log(a); // 1
console.log(b); // 0
1 Like