JavaScript: Print the Fibonacci Series

1. Introduction

The Fibonacci Series is a sequence of numbers in which each number is the sum of the two preceding ones. It often starts with 0 and 1. The series has profound importance in mathematics and even finds its place in nature, art, and architecture. In this article, we'll create a simple JavaScript program to generate and display the Fibonacci series up to a given number of terms.

2. Program Overview

In this tutorial, we'll:

1. Specify the number of terms we want from the Fibonacci series.

2. Construct a function to generate the Fibonacci series.

3. Display the resulting series.

3. Code Program

let nTerms = 10;  // Number of terms to be displayed

let fibonacciSeries = [];  // Array to hold the Fibonacci series

// Function to generate the Fibonacci series
function generateFibonacci(n) {
    let a = 0, b = 1, nextTerm;

    for (let i = 1; i <= n; i++) {
        fibonacciSeries.push(a);
        nextTerm = a + b;
        a = b;
        b = nextTerm;
    }
}

generateFibonacci(nTerms);

console.log("Fibonacci Series up to " + nTerms + " terms: " + fibonacciSeries.join(', ') + ".");

Output:

Fibonacci Series up to 10 terms: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.

4. Step By Step Explanation

1. Variable Declaration: We start with a declaration of nTerms, specifying how many terms of the Fibonacci series we wish to display. We also initialize an array fibonacciSeries to store the series.

2. Function to Generate Fibonacci: The generateFibonacci(n) function is tasked with the generation of the series:

  • We start with the two initial terms a (0) and b (1).
  • For each iteration up to n, we add the current term (a) to our series.
  • nextTerm calculates the sum of the last two terms.
  • The value of a is then updated to b and b is updated to nextTerm for the next iteration.

3. Generating the Series: We call the generateFibonacci function with the specified number of terms.

4. Displaying the Series: Finally, we utilize the console.log function to showcase the generated Fibonacci series in a structured format, separating terms with a comma.

Comments