Repository navigation
Recursion
Arghun-dev edited this page Jul 24, 2021
·
8 revisions
A process (a function in our case) which calls itself.
It's everywhere: JSON.parse, JSON.stringify
- Any time a function is invoked it is placed (pushed) on top of the call stack.
- When Javascript sees the return keyword, or when the function ends, the compiler will remove (pop)
The essential parts of a recursive function => Base Case and Different input
The condition when the recursion ends => this is the most important concept to understand.
CountDown.js
function CountDown(num) {
// this is our base case
if (num <= 0) {
console.log('all done!!!');
return;
}
console.log(num);
num--;
CountDown(num);
}Common problems that arrives when you writing recursive solutions
-
when base case is wrong or you don't have a base case => So you should have a base case, without it you put your function inside an infinite loop And you will get this error => maximum call stack size exceeded
-
Forgetting to return or return the wrong thing. => in this case as well you'll put your recursive function inside infinite loop.
Maximum Call Stack Size Exceeded === Stack Overflow :)))