fibonacci loop in javascript

To generate the Fibonacci sequence using a loop in JavaScript, you can use an array to store the numbers and a loop to calculate the next number based on the previous two numbers.

Here's the code:

index.tsx
function fibonacciLoop(n) {
  var fib = [0, 1];
  for (var i = 2; i <= n; i++) {
    fib[i] = fib[i-1] + fib[i-2];
  }
  return fib;
}

// example usage
fibonacciLoop(10); // returns [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
221 chars
11 lines

This function takes a parameter n which specifies the number of Fibonacci numbers to generate. It initializes the array with the first two numbers [0, 1] and then uses a loop to calculate each subsequent number based on the previous two numbers. Finally, it returns the entire Fibonacci sequence in an array.

gistlibby LogSnag