What is the best way to utilize a while loop in order to calculate the Fibonacci sequence?

Just recently delved into the world of Js and encountered an issue that has me stumped. Despite exhaustive searching, I haven't been able to find a similar solution. Any assistance would be greatly appreciated.

var i = 0;
var j = 1;
var k = 0;

function calculateFibonacci(n) {
  if (n === 1) {
    console.log([0]);
  } else if (n === 2) {
    console.log([0, 1]);
  } else {
    while (k <= n) {
      var sequence = [0, 1];
      var length = sequence.length;
      sequence.push(sequence[length - 2] + sequence[length - 1]);
      k++;
    }

  }
  return sequence;
}
calculateFibonacci(4);
console.log(sequence);

Answer №1

Ensure that variables are declared locally within the function where they are used. Handling base cases can be done in a different way by setting the length property. Additionally, take advantage of the recent JavaScript method Array#at...

function calculateFibonacci(n) {
    const sequence = [0, 1];
    while (sequence.length < n) sequence.push(sequence.at(-2) + sequence.at(-1));
    sequence.length = n; // adjust length for cases when n is less than 2
    return sequence;
}
console.log(calculateFibonacci(4));

Answer №2

When trying to access l outside of the function, there is a possibility that your return statement will encounter issues if 0 or 1 are provided as input. It's important to note that defining l within the while loop can cause problems.

In addition, there are unused variables such as i and j, along with the problematic scope of k:

  1. k being declared outside of the function means it will continuously increment with repeated runs
  2. k is used to track iterations when the intention seems to be counting the quantity of numbers returned with n

A simpler approach could be taken assuming that n represents the number of Fibonacci numbers to return:

  1. If n === 1 or n === 2, you should return the seed array
  2. Otherwise, a while loop can be utilized until the seed array surpasses n. In this loop, push operations should remain intact without the need for additional variable increments.

Below is an example demonstrating a more straightforward logic:

function fibonacci(n) {
    if (n === 1) {
        return [0];
    } else if (n === 2) {
        return [0, 1];
    } else {
        const sequence = [0, 1];
        while (n > sequence.length) {
            const index = sequence.length;
            sequence.push(sequence[index - 2] + sequence[index - 1]);
        }
        return sequence;
    }
}
console.log(fibonacci(4));

Answer №3

My approach using a while loop is as follows:

n = 0 || n = 1. If n > 1, the loop will iterate n - 1 times and in each iteration, it adds the sum of the previous two values in the sequence to the last index.

After completing the loop, the entire sequence is trimmed to the length of n before being returned. (I added this trimming step to my solution after reading through trincot's answer)

const fibonacci = (n) => {
    const sequence = [0, 1];
    let i = 2;
    let next;
    
    while(i <= n) {
        next = sequence[i - 2] + sequence[i - 1];
        sequence[i++] = next;         
    }

    return sequence;
}

console.log(fibonacci(6));

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

What is the proper way to implement React's Link component from an external npm package to avoid the error message stating, "you should not use link outside router"?

A custom NPM package has been developed to display an icon menu that can be used across multiple projects. Users have the flexibility to provide a 'route' prop to each icon, allowing them to act as links to different pages. Despite importing and ...

Making an API call in a getter function using AngularJS

Recently, I came across a project in AngularJS that had some structural issues. One of the main problems was related to fetching settings from an API endpoint. There were times when the application tried to access these settings before they were fully load ...

Information in a Service is reset upon refreshing the page

After refreshing the page (e.g., by pressing F5), I noticed that the data in my service gets cleared. Is there a way to prevent this issue without using local storage? It's not a critical feature, but it does disrupt the application flow when users re ...

Switching from hover to onload事件 in the JavaScript code

I am currently modifying some preexisting code to suit my requirements. https://tympanus.net/codrops/2010/02/08/awesome-css3-jquery-slide-out-button/ The sliding effect of the content when hovered with the mouse is what I am looking for. It seems straigh ...

Determine the number of duplicate items in an array of objects using JavaScript and save the count as a separate object

I have a collection of objects in JavaScript representing products. These products are shown in a list similar to a shopping cart. The goal is to identify and count duplicate products in the array based on their _id value. Once duplicates are found, they ...

When working with Angular Universal, I encountered an issue where localStorage is not defined. This has caused a problem in a function that

I have a function in my application that requires an object as one of its parameters: const checkValues = { promoId: ..., ... unsaved: !JSON.parse(localStorage.getItem('unsaved')) ? [] : JSON.parse(localStorage.getItem('unsaved') ...

Is there a way to reduce the size of a div within another div using CSS?

Trying to resize a nested div (divB) within another div (divA) is proving challenging. The issue arises when the height of divA is determined by its content. When divB is resized, divA's height remains unchanged... This occurs due to the application o ...

Having trouble with *ngif not functioning properly after initial click in Angular 6

How do I create a Select field in Angular 6 that will hide or display another div based on the selected value? Below is the code snippet: <div class="form-group"> <label for="servicePriviledges">Managed</label> < ...

If you fail to include close() when using Java's PrintWriter to write an array to a file, the final portion of the array may be omitted. What causes this issue?

While working with Java's PrintWriter class to write an array to a file, a new discovery caught my attention. It turned out that omitting the close() method at the end caused the last elements of the array to not be written to the file. What could be ...

Troubleshooting the pushstate back function in HTML5 and jQuery

In my code, I have implemented an ajax call to load content dynamically. I am now looking to add a deeplinking effect, and after researching, I discovered that only raw coding can achieve this. Here is what I have implemented so far: jQuery("#sw_layered_c ...

Triggering focus on an MUI Input component upon clicking outside its designated region

Currently, I am working on an application using ReactJS and Material UI. Within this project, I have incorporated an Input component inside a FormControl component. My goal is to have the focus automatically set on the Input component whenever a user click ...

analyze testing data in a tabular format with Jest

I am working with an HTML table that contains the following data: id | name 2 | C 1 | B 3 | A My task is to test the order of items in the table. I am currently able to retrieve the rows using: wrapper.findAll('table tr') However, I am unsu ...

Issue with submitting VueJS form on mobile devices, works fine on web browsers but not on

I have encountered a similar problem before, but I haven't found a suitable solution yet. In my VueJS application, the submit function works perfectly fine on desktop browsers like Chrome and Firefox, but for some reason it refuses to submit on mobil ...

Launch a modal from a separate webpage

I've been trying to implement a modal using Bootstrap 4, and after referring to the documentation, it seems to be working smoothly. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/> <scri ...

Is my understanding of HTML and JavaScript code accurate?

Explaining lines of code to my class for homework has been a challenge. I tried my best to break it down, but I'm not entirely confident in my accuracy. My grade depends on being 100% precise and detailed. <!DOCTYPE html> The first command dec ...

What is the best way to allocate inner JSON to an object within a promise?

Exploring the Angular2 tutorial "Tour of Heroes" showcases how to handle JSON data within a promise. But what if the JSON structure is more complex? JSON: let complexMessage = [{ "heroes":[ {id: 11, name: 'Mr. Nice'}, {id: 12, ...

The NicEditor is malfunctioning due to a ReferenceError with the variable bkLib

Encountering an issue with my NicEditor. When using a simple HTML page like this: <html> <head> <script src="http://js.nicedit.com/nicEdit-latest.js" type="text/javascript"></script> <script type="text/javascript">bkLib.onDom ...

Developing a custom jQuery plugin that incorporates the getJSON method within its functionality

There seems to be some confusion regarding the asynchronous nature of the getJSON function. I suspect that this could be the reason for the issue, but I lack a clear understanding of how it operates. When I invoke the healthCheck method in my js file on th ...

Manipulating prop values through dropdown selection

I'm currently working on implementing filtering based on a prop value that changes according to the dropdown selection. Here's my progress so far: template(v-for="field in tableFields") th(:id="field.name") select(@change="filterScope(sc ...

PHP website freezes unexpectedly in Firefox version 4

For over a year, our website has been functioning perfectly. However, with the release of Firefox4, we have noticed a new issue. Occasionally, the page hangs randomly. I have tested the website on IE8/9, Chrome10+, Safari, and Opera, and the issue only see ...