Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is recursion in JavaScript

Understanding the Concept of Recursion

If you're learning programming, you must have come across the term "recursion". What does it mean? How is it used in JavaScript? These are the questions we'll be answering in this blog post. So, let's start our journey of understanding recursion, one step at a time.

In simple terms, recursion is a process in which a function calls itself as a subroutine. This allows the function to be repeated several times, as it can call itself during its execution.

You can think of it like a loop. The main difference between a loop and recursion is that a loop is a control structure, whereas recursion is a technique of solving a problem where the solution depends on solutions to smaller instances of the same problem.

The Anatomy of a Recursive Function

Let's simplify this concept with an example. Suppose you have a stack of books that you want to count. But here's a twist: you can only see the topmost book and can't see the rest. So, how would you count the books?

You would start by counting the topmost book, and then remove it from the stack. Then, you'd count the next book and remove it. You'd keep repeating this process until there are no more books to count. This is exactly how recursion works.

In JavaScript, a recursive function looks something like this:

function countBooks(stack) {
  if (stack.length == 0) {
    return 0;
  } else {
    return 1 + countBooks(stack.slice(1));
  }
}

In the above code, countBooks is a recursive function. It checks if the stack of books is empty. If it is, it returns 0. Otherwise, it counts the topmost book (adds 1) and then calls itself with the remaining books (stack.slice(1)).

The Base Case and Recursive Case

In a recursive function, there are two scenarios to consider: the base case and the recursive case.

The base case is the condition that stops the recursion. In our example, the base case is when the stack of books is empty (stack.length == 0).

The recursive case is the condition where the function calls itself. In our example, the recursive case is when the stack of books is not empty, so the function counts the topmost book and then calls itself with the remaining books.

Without a base case, a recursive function would keep calling itself indefinitely, creating an infinite loop.

Breaking Down the Process

Let's see what happens when we call the countBooks function with a stack of 3 books:

console.log(countBooks(['book1', 'book2', 'book3']));
  1. The function checks if the stack is empty. It's not, so it counts the topmost book (returns 1) and calls itself with the remaining books (['book2', 'book3']).
  2. The function checks if the stack ['book2', 'book3'] is empty. It's not, so it counts the topmost book (returns 1) and calls itself with the remaining book (['book3']).
  3. The function checks if the stack ['book3'] is empty. It's not, so it counts the topmost book (returns 1) and calls itself with no more books ([]).
  4. The function checks if the stack [] is empty. It is, so it returns 0.
  5. The returned values are added up: 1 + 1 + 1 + 0 = 3.

So, the console.log statement outputs 3, which is the number of books.

The Power and Danger of Recursion

Recursion can be a powerful tool in programming. It can simplify code and make it easier to understand. However, it can also be dangerous if not used correctly.

As we mentioned earlier, without a base case, a recursive function would keep calling itself indefinitely, creating an infinite loop. This can cause the program to crash or run out of memory.

Moreover, recursion can be less efficient than iteration (loops) in JavaScript, because each recursive call adds a layer to the stack (the place where JavaScript keeps track of function calls), which takes up memory.

Conclusion

To understand recursion is to open the door to a new level of coding expertise. Recursion, like a skilled painter with their brush, allows us to paint intricate details into our code, creating solutions to complex problems with elegance and simplicity. While it may seem intimidating at first, like any good book, once you delve into its pages, you are bound to get lost in its beauty. Remember, every recursive function has its base case, its moment of rest. So, take a cue from recursion, and don’t forget to rest your own mind as you journey through the captivating world of programming. Happy coding!