Recursion & the Call Stack
Learn how a function can call itself to solve complex problems, and how JavaScript uses the Call Stack to keep track of everything.
What is Recursion?
Recursion is a programming technique where a function calls *itself* in order to solve a smaller piece of a larger problem.
Think of it like opening nested boxes. You open a box, find another box inside, and open that one, repeating the exact same process until you finally find a box with a prize inside.
The Base Case
Every recursive function MUST have a 'Base Case'. This is the condition that tells the function to stop calling itself.
Without a base case, the function will call itself infinitely. In JavaScript, this eventually causes a 'Maximum call stack size exceeded' error, famously known as a Stack Overflow.
The Call Stack
JavaScript is single-threaded. It uses a data structure called the 'Call Stack' to keep track of what function is currently running.
When a function calls itself, it pauses its current execution and pushes a new 'frame' onto the top of the stack.
Once the base case is finally reached, the stack begins to 'unwind'. It pops frames off from top to bottom, resolving each one until the original call is finished.
The Call Stack Visualizer
Step through a recursive countdown function. Watch how the Call Stack grows taller with each recursive call, hits the base case, and then unwinds.
The Call Stack Visualizer
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Recursion is a function calling itself to solve a smaller piece of a problem.
- A Base Case is mandatory to stop the recursion.
- Each recursive call pauses execution and adds a new frame to the Call Stack.
- When the base case is hit, the Call Stack unwinds from top to bottom (LIFO order).
Done with this concept?
Mark it complete to track your progress. No login needed.