Skip to content
the poor coder

generator function fibonacci

Poor Man
Published
Reading time
1 min read

Generator Function Fibonacci#

As a programmer, I have come across the concept of Fibonacci numbers quite often. A Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding numbers.

A generator function is a special type of function that allows us to generate a sequence of values on the fly, rather than computing them all at once and returning them as an array or list.

The generator function for the Fibonacci sequence is quite simple. It involves using the yield statement to generate each number in the sequence one by one. Here is an example:

Text

function* fibonacci() {
  let a = 0, b = 1;
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}

const gen = fibonacci();

for (let i = 0; i < 10; i++) {
  console.log(gen.next().value);
}
  • The function* keyword indicates that this is a generator function.
  • The yield keyword generates each number in the sequence.
  • The while loop continues indefinitely, generating values until the program is interrupted.
  • The [a, b] = [b, a + b] syntax is a shorthand way of swapping the values of a and b and updating their values to the next numbers in the sequence.

You can see this code in action here:

There are many other ways to generate Fibonacci numbers in JavaScript, including using recursion or memoization. However, the generator function approach is particularly elegant and efficient, and it allows us to generate the sequence lazily as needed.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC