Search⌘ K

Solution Review: Fibonacci Series

Explore how to create a generator function in JavaScript to produce Fibonacci numbers. Understand managing sequence state with variables, using yield to produce values, and controlling iteration with a loop and break condition to efficiently generate the series.

We'll cover the following...

Solution

The solution to the “Fibonacci series” challenge is given below.

Node.js
const fibonocciSeries = function*(n) {
let current = 0;
let next = 1;
yield* [current, next];
while(true) {
const temp = current;
current = next;
next = next + temp;
if(next > n) break;
yield next;
}
}
for(const value of fibonocciSeries(25)) {
console.log(value);
}

Explanation

We need to implement a generator function that will yield the Fibonacci numbers.

  • In the Fibonacci series, every subsequent number is the sum of two previous numbers. So, first, we need to set two starting points, which are
...
svg viewer