Back to all posts

Recursion in JavaScript.


Recursion is a concept that is not only prevalent in JavaScript but in many other programing languages as well. In simple terms, recursion is a process of a function calling itself.

Understanding Recursion

A recursive function will keep calling itself until a certain condition is met. This condition is known as the base case. If the base case is not defined, the function will continue to call itself indefinitely, leading to a stack overflow error.

Simple example

function recurse() {
    if(condition) {
        recurse();
    }
    else {
        // stop calling recurse()
    }
}
recurse();

Recursion vs Loops

Recursion and loops are two different ways to achieve repetition in programming. While loops are straightforward and easy to understand, recursion can be a bit tricky to grasp initially. However, in some cases, using recursion can lead to cleaner and more readable code compared to loops

Let’s dive into example

function factorial(n) {
  // Base case: factorial of 0 or 1 is 1
  if (n === 0 || n === 1) {
    return 1;
  }

  // Recursive case: n! = n * (n-1)!
  return n * factorial(n - 1);
}

// Calculate the factorial of 5
const result = factorial(5);
console.log(result); // Output: 120