Recursion
MediumIn plain terms
Recursion is when a function calls itself. Need a base case to stop. Used for trees, factorial, Fibonacci. Can cause stack overflow for deep recursion.
What you need to know
- •Function calls itself
- •Base case
- •Call stack depth
Try it yourself
Copy the code below and run it in your browser console or a code editor:
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
function fib(n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}Learn more
Dive deeper with these trusted resources: