Plenty of π
Module 5: Functions
Recursion: Understanding and Writing Basic Recursive Functions

Recursion is a programming technique where a function calls itself in order to solve a problem. A recursive function typically has two parts:

  1. Base Case: A condition that stops the recursion. Without a base case, a recursive function would call itself indefinitely, leading to a stack overflow error.
  2. Recursive Step: The part of the function where it calls itself with a modified argument, moving closer to the base case.

Example: Factorial The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. 5! = 5 * 4 * 3 * 2 * 1 = 120 0! = 1 (by definition)

function factorial(n) {
  // Base case: if n is 0 or 1, factorial is 1
  if (n === 0 || n === 1) {
    return 1;
  }
  // Recursive step: n * factorial of (n-1)
  else {
    return n * factorial(n - 1);
  }
}

console.log(factorial(5)); // Output: 120
console.log(factorial(0)); // Output: 1

How factorial(3) works:

  1. factorial(3) calls 3 * factorial(2)
  2. factorial(2) calls 2 * factorial(1)
  3. factorial(1) hits the base case and returns 1.
  4. Back to factorial(2), it returns 2 * 1 = 2.
  5. Back to factorial(3), it returns 3 * 2 = 6.

Recursion can be elegant for problems that can be broken down into smaller, self-similar subproblems (e.g., traversing tree structures, some sorting algorithms). However, it can sometimes be less efficient than iterative solutions due to function call overhead.