What is recursion?
In short
Recursion is when a function calls itself to solve a smaller piece of the same problem, until the piece is so small the answer is obvious.
To count down from 3, you could say "3" and then count down from 2. Counting down from 2 is the same problem, just smaller. A recursive function works like that: it handles one step, then calls itself for the rest.
Every recursive function needs a base case, the point where it stops calling itself. Without one, it would call itself forever and the program would crash.
Python
A countdown that calls itself
def countdown(n):
if n == 0:
print("Lift off!")
return
print(n)
countdown(n - 1)
countdown(3)Output
3
2
1
Lift off!JavaScript
The same idea in JavaScript
function countdown(n) {
if (n === 0) {
console.log("Lift off!");
return;
}
console.log(n);
countdown(n - 1);
}
countdown(3);Output
3
2
1
Lift off!Learn it properly
These free lessons teach it step by step, with questions and a program you write yourself.
- Functions That Call ThemselvesLearn Python →
- Functions That Call ThemselvesLearn JavaScript →
- Functions That Call ThemselvesLearn C →
Try your first lesson free
Codiqo teaches coding in five-minute lessons with real code. Free on the web, iPhone and Android.