What is the best way to implement a Fibonacci sequence using a for...of loop?

**Can someone show me how to generate Fibonacci numbers using the for...of loop in JavaScript?**

I've tested out the following code and it's giving me the desired output:


function createFibonacci(number) {
    var i;
    var fib = []; // Initial array set up

    fib[0] = 0;
    fib[1] = 1;
    for (i = 2; i <= number; i++) {
        // Logic to find next Fibonacci number
        fib[i] = fib[i - 2] + fib[i - 1];
        console.log(fib[i]);
    }
}

createFibonacci(8);

Although this works fine, I'm curious if there's a way to achieve the same result using the for..of loop. Is there any method available for this?

Answer №1

Here is a suggestion for generating Fibonacci numbers using a generator in JavaScript:

function generateFibonacciNumbers(num) {
  // fibonacci generator
  const gen = (function *(i) {
    let a = 1, b = 1, c;
    if (i--) yield a;
    if (i--) yield b;
    while (i--) {
      yield c = a + b;
      [a, b] = [b, c];
    }
  });

  for (let fib of gen(num)) {
    console.log(fib);
  }
}

generateFibonacciNumbers(8);

As noted by @T.J. Crowder, the sequence is actually generated by the generator and consumed using the for...of loop.

Answer №2

Consider utilizing a generator function.

function* generateFibonacci(number, a = 0, b = 1) {
    if (a === 0)
        if (number--) yield 1;
        else return;
    if (!number--) return
    yield a + b;
    yield* generateFibonacci(number, b, a + b);
}

console.log(...generateFibonacci(0));
console.log(...generateFibonacci(1));
console.log(...generateFibonacci(2));
console.log(...generateFibonacci(3));
console.log(...generateFibonacci(4));
console.log(...generateFibonacci(5));
console.log(...generateFibonacci(6));
console.log(...generateFibonacci(7));
console.log(...generateFibonacci(8));
.as-console-wrapper { max-height: 100% !important; top: 0; }

An alternative method inspired by assistance from Rup.

function* generateFibonacci(number, index = 1) {
    generateFibonacci.values = generateFibonacci.values || [0, 1];
    for (; index < generateFibonacci.values.length && index < number + 1; ++index)
        yield generateFibonacci.values[index];
    if (index >= number + 1) return;
    yield generateFibonacci.values[index] = generateFibonacci.values[index - 2] + generateFibonacci.values[index - 1];
    yield* generateFibonacci(number, index + 1);
}

console.log(...generateFibonacci(0));
console.log(...generateFibonacci(1));
console.log(...generateFibonacci(2));
console.log(...generateFibonacci(3));
console.log(...generateFibonacci(4));
console.log(...generateFibonacci(5));
console.log(...generateFibonacci(6));
console.log(...generateFibonacci(7));
console.log(...generateFibonacci(8));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The JSON file is not filling the options in the dropdown menu

procedure Add the objects from the dropdown into the dropdown menu. The Json file is located in root/ajax/.json and the working file is stored in root/.html. Problem: None of the objects from the JSON file are appearing in the dropdown menu. I attempted ...

Error encountered in attempting to create an embed using discord.js v14.7.1: TypeError - The value being extended, either undefined or null, is not a valid

The specific problem arises when defining the module export for the HelpCommand class: **module.exports = class HelpCommand extends Command {** The content of the help.js file, without URLs, is as follows: const fs = require('fs'); const { Comma ...

The functionality of AC_FL_RunContent is failing after an UpdatePanel postback

In the code for the repeater item, I have a JavaScript function that calls AC_FL_RunContent to display a flash file when a link within the repeater item is clicked. The datasource I am using displays the first page of video links with five items per page, ...

The issue with displaying Fontawesome icons using @import in CSS-in-JS was not resolved

I recently changed how I was importing Fontawesome icons: src/App.css @import "@fortawesome/fontawesome-free/css/all.css";` After shifting the @import to CSS-in-Js using emotion: src/App.js // JS: const imports = css` @import "@fortawes ...

Fetch information from the database, Send it via AJAX to refresh the database, Then circle back to retrieve fresh data! Utterly perplexed

I am looking to retrieve data from a MySQL database using PHP and assign them to a JavaScript array. There are 200 records in my database, and I want to randomly select 10 records. $myQuery = mysql_query("select * from tblx where xyz=1 order by rand() lim ...

Code snippet for a click event in JavaScript or jQuery

I initially wrote the code in JavaScript, but if someone has a better solution in jQuery, I'm open to it. Here's the scenario: I have multiple questions with corresponding answers. I want to be able to click on a question and have its answer dis ...

Internet Explorer struggling to function due to JavaScript errors

While Chrome and Firefox breeze through the page, it seems to hang for an eternity in Internet Explorer. Here is the problematic page: ============= Error Details: User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2 ...

A guide to replicating HTML using AngularJS

I am attempting to replicate HTML content using AngularJS. While I was successful using jQuery, it caused conflicts with Angular. Therefore, I aim to achieve the same result using AngularJS. Here is the code I have written: function printContent(el){ ...

Trying to use the `await` keyword results in a "SyntaxError: Unexpted identifier" message, even when used within an `async` function

Encountering an error with Javascript's await when using it inside an async module let ImagesArray = await getImages(); ^^^^^^^^^ SyntaxError: Unexpected identifier at createScript (vm.js:80:10) at Object.runInThis ...

"Using Node.js to create a simulated mobile environment: a step-by-step guide

I am seeking a way to replicate the functionalities of a mobile browser using Node.js. This means that all mobile browser features should be accessible on the client-side, even if they are simulated. The goal is for webpages to believe they are being load ...

Enzyme/Jest Testing Issue - Invariant Violation: The specified container is not a valid DOM element

I have recently started exploring unit testing and I am encountering the following error: Invariant Violation: Target container is not a DOM element. After reviewing my app.js file, I suspect that the issue lies with the line ReactDOM.render(, document.get ...

Puppeteer: Navigate to a specific page number

I'm encountering an issue with a table and page numbers as links, such as: 1, 2, 3, 4 etc… -> each number is a link. Attempted to create a loop to click on different page numbers. On the first iteration, I can reach page 2. However, on the secon ...

Why will the experimental activation of React concurrent features in Nextjs 12 disable API routes?

I just upgraded to Next.js version 12 and set up some API routes (e.g. "/api/products"). These routes were functioning properly, but when I enabled concurrentFeatures: true in my next.config.ts, the API routes stopped working. The console display ...

I am having issues with the external CSS and JS files not functioning properly in my project

I'm currently working on a project that has the following file structure: However, I am facing issues with loading my CSS and JS files... <link rel="stylesheet" href="./css/main.css"> <script src="./js/main.js" ...

Is there a way to create an effect where the color of a floating action button changes when you hover over it, similar to a filter?

I'm new to using the <Fab /> element and I'm struggling to figure out how to implement a hover effect that will change the button's color. Here's what I have so far: JavaScript: <Fab variant="extended" className=&quo ...

Dealing with the challenges posed by middleware such as cookie access and memory leaks

Utilizing express with cookieParser() where my client possesses the cookie named: App.Debug.SourceMaps. I've crafted a middleware as follows: app.get('/embed/*/scripts/bundle-*.js', function(req, res, next) { if (req.cookies['App ...

Integrating Amazon external images in NextJS

There is a specific issue with loading images from a URL stored on Amazon S3 within the domain configured in next.config.js. Strangely, when using external URLs like Unsplash, the images load fine. The problematic URL is: idinheiro-admin-images.s3.sa-east ...

Leveraging partials on their own

I am currently exploring the possibility of loading a partial in linkedin-dustjs without having to load its parent along with it. For instance, consider this partial (login.dust): {>layout/} {<content} <!-- Login Screen --> {/content} Th ...

Create an Interactive Menu Using JSON Data

Looking for guidance with angularjs as a beginner, I'm interested in creating a dynamic menu using JSON array. { "Pages": [{ "PageId": 1, "PageTitle": "Home", "PageContent": "Home Page Content", "MenuType": "MainMenu", "ParentMenu": null, "PageStatu ...

Use promises instead of directly calling res.json(data) when working with Node.js

When I make a post request to the payment_url, it triggers the second block of my function. Unfortunately, I am unable to retrieve any data in the then method because I am unsure how to pass the data back to the resolve function. Client-side call paypal. ...