What Is Recursion?

Recursion is a programming technique where a function calls itself to solve a problem.

Instead of using loops such as for or while, a recursive function repeatedly calls itself until a stopping condition is met.

For this reason, every recursive function must include a base case. Without one, the function would continue calling itself indefinitely.

Example

Suppose we want to keep increasing a variable until it becomes greater than 10.

let total = 0;
function addToTotal(num) {
total += num;
if (total > 10) {
console.log("Total is now greater than 10");
return;
}
console.log(total);
addToTotal(num);
}
addToTotal(1);

How Does It Work?

Initially, total is:

0;

Each time the function runs, it executes:

total += num;

which is equivalent to:

total = total + num;

Then it checks:

if (total > 10)

If the condition is true, the function stops.

Otherwise, it calls itself again:

addToTotal(num);

This process repeats until the stopping condition is satisfied.

Why Did We Use return?

Inside the condition we wrote:

return;

In this case, return does not return a value.

Instead, it simply stops the function from continuing, preventing another recursive call.

Without this stopping condition, the function would continue calling itself until a Stack Overflow occurs.

When Is Recursion Used?

This example could easily be solved with a loop, but it demonstrates how recursion works.

Recursion is commonly used for problems such as:

  • Traversing folders and files.
  • Working with tree structures.
  • Processing nested data.
  • Many mathematical and algorithmic problems.

Key Takeaways

  • Recursion is when a function calls itself.
  • Every recursive function needs a base case.
  • return can be used to stop the recursive calls.
  • Without a stopping condition, recursion will eventually cause a Stack Overflow.