How do i use while loop while figuring out Fibonacci series?

Solution 1:

Make sure to declare variables locally inside the function, if that is where they are used. You can deal with the base cases differently (setting the length property), and there is the recent JS method Array#at... :

function fibo(n) {
    const l = [0, 1];
    while (l.length < n) l.push(l.at(-2) + l.at(-1));
    l.length = n; // for the case n < 2
    return l;
}
console.log(fibo(4));

Solution 2:

Besides attempting to access l outside of the function, your l in the return statement is sometimes undefined when 0 or 1 is provided to the function. More importantly, l shouldn't be defined in the while loop but outside of it.

Moreover, you have variables such as i and j that are unused, and k which is being used but its scope is problematic:

  1. It is outside of the function, so repeated runs will cause k to be continuously increased
  2. k is used to track number of iterations, while your code indicates that n should be the quantity of numbers returned

Here is a way more simplified logic, assuming that n is supposed to the number of Fibonacci numbers to be returned:

  1. If n === 1 or n === 2, you return the seed array
  2. Otherwise you simply run a while loop that will only stop running once the seed array exceeds n. In the while loop, we retain the logic of pushing numbers, but otherwise there is no need to have any other variables being incremented.

See proof-of-concept example:

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

Solution 3:

Using a while loop, my take will be as follows:

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

Once the loop finishes the whole sequence gets trimmed to the length of n and returned. (This last trimming piece was originally missing in my solution and added after reading trincot's answer)

const fibbo = (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(fibbo(6));