Introduction to Fibonacci Series in JavaScript

Jul 27, 2024

Introduction to Fibonacci Series in JavaScript

The Fibonacci series is a well-known mathematical sequence named after the Italian mathematician Leonardo of Pisa, also known as Fibonacci. This series starts with 0 and 1, and each subsequent number is the sum of the two preceding ones. The Fibonacci sequence is widely used in various fields, including mathematics, computer science, and nature.In this blog post, we will explore how to implement the Fibonacci series in JavaScript using different approaches, including loops and recursion. We will also discuss the time and space complexities of each method and provide examples to help you understand the concepts better.

What is the Fibonacci Series?

The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. The sequence is defined as follows:

Fn=Fn−1+Fn−2Fn​=Fn−1​+Fn−2​

where:

  • $F_0 = 0$

  • $F_1 = 1$

  • $n \geq 2$

The first few terms of the Fibonacci series are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...

Fibonacci Series in JavaScript Using for Loop

One of the most common ways to generate the Fibonacci series in JavaScript is by using a for loop. Here's an example:

function fibonacciSeries(n) {
  let fib = [0, 1];

  for (let i = 2; i < n; i++) {
    fib[i] = fib[i - 1] + fib[i - 2];
  }

  return fib.slice(0, n);
}

// Example: Generate the first 10 numbers in the Fibonacci series
console.log(fibonacciSeries(10));
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Explanation:

  1. The fibonacciSeries(n) function is defined to calculate the Fibonacci series up to n numbers.

  2. We start with an array fib initialized with the first two numbers of the Fibonacci series: [0, 1].

  3. The for loop starts from index 2 and runs until it reaches the length n specified by the user. This is because the first two numbers of the series are already defined.

  4. Inside the loop, each number is calculated by adding the two preceding numbers in the series using fib[i - 1] + fib[i - 2], and the result is stored in fib[i].

  5. The function returns the Fibonacci series up to n numbers using fib.slice(0, n). The slice() method is used to ensure that the length of the returned array matches the number n specified by the user.

  6. Finally, we call fibonacciSeries(10) to print the first 10 numbers of the Fibonacci series to the console.

This code is a simple and efficient way to use JavaScript for generating the Fibonacci series and is particularly useful for beginners to understand how arrays and loops work in the language.

Fibonacci Series in JavaScript Using while Loop

Another approach to generate the Fibonacci series in JavaScript is by using awhileloop. Here's an example:

function fibonacciSeriesUpTo(maxValue) {
  if (maxValue === 0) return [];
  if (maxValue === 1) return [0, 1];

  let fib = [0, 1];

  while (true) {
    let nextFib = fib[fib.length - 1] + fib[fib.length - 2];
    if (nextFib > maxValue) break;
    fib.push(nextFib);
  }

  return fib;
}

// Prompt user for input
let userInput = prompt("Enter the number:");
userInput = parseInt(userInput, 10); // Convert the input to an integer

if (!isNaN(userInput)) {
  console.log(fibonacciSeriesUpTo(userInput));
} else {
  console.log("Please enter a valid number.");
}
Enter the number:2000
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597]

Explanation:

  1. The fibonacciSeriesUpTo(maxValue) function is defined to generate the Fibonacci series up to a specified maximum value.

  2. If the maxValue is 0 or 1, the function returns an empty array or an array with [0, 1], respectively.

  3. The fib array is initialized with the first two numbers of the Fibonacci series: [0, 1].

  4. The while loop continues until the next Fibonacci number exceeds the maxValue.

  5. Inside the loop, the next Fibonacci number is calculated by adding the last two numbers in the fib array using fib[fib.length - 1] + fib[fib.length - 2].

  6. If the calculated next Fibonacci number is greater than the maxValue, the loop is broken using the break statement.

  7. The calculated next Fibonacci number is added to the fib array using fib.push(nextFib).

  8. Finally, the function returns the fib array containing the Fibonacci series up to the specified maxValue.

  9. The user is prompted to enter a number, which is converted to an integer using parseInt().

  10. If the user input is a valid number, the fibonacciSeriesUpTo() function is called with the user input, and the result is logged to the console.

  11. If the user input is not a valid number, an error message is displayed.

This approach allows you to generate the Fibonacci series up to a certain number based on user input.