What is Recursion in JavaScript: Simple Explanation and Example
recursion is when a function calls itself to solve smaller parts of a problem until it reaches a simple case. This technique helps break down complex tasks into easier steps by repeating the same process inside the function.How It Works
Recursion works like a set of nested boxes, where each box contains a smaller box inside it. When a function calls itself, it creates a new 'box' or layer of work to do. Each call handles a smaller piece of the problem.
Imagine you want to count down from 5 to 1. Instead of counting all at once, you say "count 5, then count 4," and so on, until you reach 1. Each step waits for the next smaller step to finish before completing itself. This waiting and calling itself again is how recursion solves problems step-by-step.
Example
This example shows a function that calculates the factorial of a number using recursion. Factorial means multiplying a number by all smaller numbers down to 1.
function factorial(n) { if (n === 0) { return 1; // base case: stop recursion } return n * factorial(n - 1); // recursive call } console.log(factorial(5));
When to Use
Use recursion when a problem can be divided into similar smaller problems. It is helpful for tasks like searching trees, sorting data, or calculating sequences. Recursion makes code simpler and easier to understand for these cases.
For example, navigating folders on your computer, solving puzzles like the Tower of Hanoi, or processing nested lists are good uses of recursion.
Key Points
- Recursion means a function calls itself.
- It needs a base case to stop calling itself.
- Each call solves a smaller part of the problem.
- Useful for problems with repeating similar steps.