Computer >> Computer tutorials >  >> Programming >> Javascript

Sum of even Fibonacci terms in JavaScript


We are required to write a JavaScript function that takes in a number as a limit. The function should calculate and return the sum of all the Fibonacci numbers that are both smaller than the limit and are even.

For example −

If the limit is 100

Then the even Fibonacci terms are −

2, 8, 34

And the output should be −

44

Example

Following is the code −

const sumOfEven = (limit) => {
   let temp, sum = 0, a = 0, b = 1;
   while (b < limit) {
      if (b % 2 === 0) {
         sum += b;
      };
      temp = a;
      a = b;
      b += temp;
   };
   return sum;
};
console.log(sumOfEven(100));
console.log(sumOfEven(10));
console.log(sumOfEven(1000));

Output

Following is the output on console −

44
10
798