Generating Fibonacci Sequence with JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28295{{"`Generating Fibonacci Sequence with JavaScript`"}} javascript/data_types -.-> lab-28295{{"`Generating Fibonacci Sequence with JavaScript`"}} javascript/arith_ops -.-> lab-28295{{"`Generating Fibonacci Sequence with JavaScript`"}} javascript/comp_ops -.-> lab-28295{{"`Generating Fibonacci Sequence with JavaScript`"}} javascript/higher_funcs -.-> lab-28295{{"`Generating Fibonacci Sequence with JavaScript`"}} javascript/destr_assign -.-> lab-28295{{"`Generating Fibonacci Sequence with JavaScript`"}} end

Fibonacci Sequence

To generate the Fibonacci sequence in JavaScript, follow these steps:

  1. Open the Terminal/SSH and type node.
  2. Use Array.from() to create an empty array of the specific length, initializing the first two values (0 and 1).
  3. Use Array.prototype.reduce() and Array.prototype.concat() to add values into the array, using the sum of the last two values, except for the first two.
  4. 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.

Other JavaScript Tutorials you may like