What is Recursion in JavaScript?
Writing functions that call themselves, and when that beats a loop.
There are times when the data you're working with has no fixed depth. A comment can have replies, and those replies can have replies of their own. A folder can hold files and other folders. A loop doesn't know how deep to go, but a function that calls itself does.
Recursion is when a function calls itself. It keeps calling itself until it reaches a condition that tells it to stop.
Base Case and Recursive Case
Every recursive function has two parts:
- The base case is the condition where the function stops and returns a value without calling itself.
- The recursive case is where the function calls itself with a smaller input, moving closer to the base case.
Here's a countdown:
function countdown(number) {if (number === 0) {console.log("Liftoff!")return}console.log(number)countdown(number - 1)}countdown(3)// 3// 2// 1// Liftoff!
number === 0 is the base case. Every other call logs the number and calls
countdown again with one less, so it always ends up at 0.
Factorial
A factorial multiplies a number by every whole number below it, so 4! is
4 * 3 * 2 * 1. Another way to say that is 4! is 4 * 3!, which is exactly
the kind of problem recursion is good at:
function factorial(number) {if (number <= 1) return 1return number * factorial(number - 1)}factorial(4) // 24
What Happens on the Call Stack
Each time a function is called, JavaScript adds it to the call stack. The function stays there until it returns. With recursion the calls pile up until the base case is reached, then they return one at a time in reverse order:
factorial(4)// factorial(4) waits for factorial(3)// factorial(3) waits for factorial(2)// factorial(2) waits for factorial(1)// factorial(1) returns 1// factorial(2) returns 2 * 1 = 2// factorial(3) returns 3 * 2 = 6// factorial(4) returns 4 * 6 = 24
The call stack only has so much room. If you forget the base case, or the input never reaches it, the function keeps calling itself until the stack runs out:
function factorial(number) {return number * factorial(number - 1)}factorial(4)// RangeError: Maximum call stack size exceeded
When you see that error, check that your base case exists and that every recursive call moves closer to it.
Summing a Nested Array
Countdown and factorial are easy to write with a loop too. Recursion really shines when the data is nested and you don't know how deep it goes. Here's a function that adds up every number in an array, no matter how many arrays are inside it:
function sumNested(items) {return items.reduce((total, item) => {if (Array.isArray(item)) {return total + sumNested(item)}return total + item}, 0)}sumNested([1, [2, 3], [4, [5, [6]]]]) // 21
If the item is a number it gets added to the total. If it's an array,
sumNested calls itself to get that array's total first. The base case here is
a plain number, which gets added without another call. (If you're new to
reduce, check out
How to Use the Reduce Method in JavaScript.)
Walking a File Tree
A more realistic example is a tree, like a folder structure from an API:
const folder = {name: "src",children: [{ name: "index.js" },{name: "components",children: [{ name: "Button.js" },{ name: "Modal.js" },{ name: "icons", children: [{ name: "Close.js" }] },],},],}
To get the path of every file, a function handles one node and calls itself for each child:
function getFilePaths(node, parentPath = "") {const path = parentPath ? `${parentPath}/${node.name}` : node.nameif (!node.children) {return [path]}return node.children.flatMap((child) => getFilePaths(child, path))}getFilePaths(folder)// [// "src/index.js",// "src/components/Button.js",// "src/components/Modal.js",// "src/components/icons/Close.js",// ]
A node without children is a file, which is the base case. A folder returns
the paths of everything inside it. The same pattern works for a comment thread,
a nested menu or rendering a tree of React components that render themselves.
Recursion vs Loops
Anything you write with recursion can be written with a loop, and the other way around. A few things to keep in mind:
- Loops are usually faster and can't run out of stack space, so reach for one when you're just counting or going through a flat list.
- Recursion is easier to read when the data is shaped like a tree, because the code follows the shape of the data.
- Very deep recursion (thousands of levels) can hit the stack limit. Most real trees like comments or folders are nowhere near that deep.
Memoized Fibonacci
The classic recursive Fibonacci is short but slow, because it calculates the same numbers over and over:
function fibonacci(n) {if (n <= 1) return nreturn fibonacci(n - 1) + fibonacci(n - 2)}fibonacci(40) // takes a noticeable amount of time
fibonacci(40) ends up calling fibonacci(2) millions of times. Saving each
result the first time you calculate it (memoization) fixes that:
function fibonacci(n, memo = {}) {if (n <= 1) return nif (memo[n]) return memo[n]memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo)return memo[n]}fibonacci(40) // 102334155, instantly
Now each number is only calculated once and every other call reads it from
memo.
Recursion takes a little getting used to, but once you start looking for the base case first, it becomes a natural fit for any data that nests inside itself.
Have some feedback on this post? .