print fibonacci series in javascript

To print the Fibonacci series in JavaScript, you can use a loop to calculate the series and then print each number. Here's an example code snippet:

index.tsx
function fibonacciSeries(n) {
  let fibArray = [0, 1]; // initialize the array with the first two Fibonacci numbers

  for (let i = 2; i < n; i++) {
    fibArray[i] = fibArray[i - 1] + fibArray[i - 2]; // calculate the next Fibonacci number
  }

  // Print the Fibonacci series
  for (let i = 0; i < fibArray.length; i++) {
    console.log(fibArray[i]);
  }
}

// Example usage: print the first 10 Fibonacci numbers
fibonacciSeries(10);
437 chars
16 lines

This code defines a function fibonacciSeries that takes a parameter n, which represents the number of Fibonacci numbers to print. It initializes an array fibArray with the first two Fibonacci numbers (0 and 1), and then uses a loop to calculate and store the remaining numbers. Finally, it uses another loop to print each Fibonacci number.

Running fibonacciSeries(10) in this example will print the first 10 Fibonacci numbers: 0 1 1 2 3 5 8 13 21 34.

related categories

gistlibby LogSnag