4-3 Fibonacci sequence with recursion

Thought analysis

Code implementation

    // Write a function that returns the n subscript of the Fibonacci sequence

    function fib(n) {
      // Index 0 and index 1 have values of 1
      if (n == 0 || n == 1) return 1;
      // The essential characteristic of the Fibonacci sequence is that each term is equal to the sum of the preceding two terms
      return fib(n - 1) + fib(n - 2);
    }

    // Write a loop to calculate the first 15 items of the Fibonacci sequence
    for (var i = 0; i < 15; i++) {
      console.log(fib(i));
    }
Copy the code