Recursion in JavaScript

This example demonstrates recursive functions in JavaScript. Here’s a classic implementation of factorial using recursion.

// This `fact` function calls itself until it reaches the
// base case of `fact(0)`.
function fact(n) {
    if (n === 0) {
        return 1;
    }
    return n * fact(n - 1);
}

console.log(fact(7));

// In JavaScript, functions are first-class citizens,
// so we can create recursive anonymous functions (closures)
// without explicitly declaring them first.
const fib = function(n) {
    if (n < 2) {
        return n;
    }
    // The function calls itself recursively
    return fib(n - 1) + fib(n - 2);
};

console.log(fib(7));

To run this code, you can save it in a file named recursion.js and execute it using Node.js:

$ node recursion.js
5040
13

In this JavaScript version:

  1. We define a fact function that calculates the factorial of a number recursively.

  2. We then define a fib function as a constant, which calculates the Fibonacci number for a given index using recursion.

  3. Both functions are called with the argument 7, and their results are printed to the console.

The main differences from the original example are:

  • JavaScript doesn’t require explicit type declarations.
  • In JavaScript, we can define the recursive closure (fib) directly without needing to declare its type beforehand.
  • We use console.log() instead of fmt.Println() for output.

This example showcases how JavaScript supports recursive functions, both as named functions and as anonymous function expressions (closures).