Introduction
In this lab, we will explore the concept of generating the Fibonacci sequence using JavaScript. We will be using the Array.from() method, along with reduce() and concat() methods to create an array that contains the Fibonacci sequence up to the nth term. By the end of the lab, you will have a deeper understanding of these methods and how they can be used to generate the Fibonacci sequence in JavaScript.
Fibonacci Sequence
To generate the Fibonacci sequence in JavaScript, follow these steps:
- Open the Terminal/SSH and type
node. - Use
Array.from()to create an empty array of the specific length, initializing the first two values (0and1). - Use
Array.prototype.reduce()andArray.prototype.concat()to add values into the array, using the sum of the last two values, except for the first two. - Call the
fibonacci()function and pass the desired length of the sequence as an argument.
Here's the code:
const fibonacci = (n) =>
Array.from({ length: n }).reduce(
(acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
[]
);
fibonacci(6); // [0, 1, 1, 2, 3, 5]
This will generate an array containing the Fibonacci sequence up until the nth term.
Summary
Congratulations! You have completed the Fibonacci lab. You can practice more labs in LabEx to improve your skills.