node js fibonacci series
To generate the Fibonacci series using Node.js, follow these steps:
- Define a function called
fibonacci
that takes a parameter calledn
to represent the number of terms in the series. - Inside the
fibonacci
function, create an array calledfibArray
to store the Fibonacci series. - Check if the value of
n
is less than or equal to 0. If it is, return an empty array, as there are no terms to generate. - Check if the value of
n
is equal to 1. If it is, return an array containing the number 0, as the Fibonacci series starts with 0. - Check if the value of
n
is equal to 2. If it is, return an array containing the numbers 0 and 1, as the first two terms of the series. - If none of the above conditions are met, initialize the
fibArray
with the first two terms of the series, which are 0 and 1. - Use a loop to iterate from the third term up to the
n
th term of the series. - Inside the loop, calculate each term of the series by adding the two previous terms and push it to the
fibArray
. - After the loop finishes, return the
fibArray
, which should now contain the Fibonacci series.
Here is the code snippet that implements the above steps:
function fibonacci(n) {
let fibArray = [];
if (n <= 0) {
return fibArray;
}
if (n === 1) {
fibArray.push(0);
return fibArray;
}
if (n === 2) {
fibArray.push(0, 1);
return fibArray;
}
fibArray.push(0, 1);
for (let i = 2; i < n; i++) {
fibArray.push(fibArray[i - 1] + fibArray[i - 2]);
}
return fibArray;
}
console.log(fibonacci(10)); // Example usage: prints [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Please note that this code snippet assumes that the value of n
will be a positive integer.