Use recursion for naturally recursive problems like tree traversal, divide-and-conquer, and backtracking. Use iteration for deep inputs or when stack depth is a concern, since iteration uses constant stack space.
Recursive Functions and the Call Stack in JavaScript
When should you use recursion vs iteration in JavaScript?
The answer
More FAQs in Recursive Functions and the Call Stack in JavaScript
Each recursive call pushes a new frame with its own local variables. The stack grows with depth. When the base case returns, frames pop in reverse order and return values combine on the way back up.
Without a base case, the function calls itself forever, frames pile up, and the engine throws RangeError: Maximum call stack size exceeded. The base case is what stops the recursion.
The ES6 spec includes it, but most engines (including V8 in Chrome and Node.js) do not implement it. In practice, deep recursion still overflows the stack and should be converted to iteration or use a trampoline.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.