Recursion is one of those things that you just don't get the first time.
It seems like a simple concept, but then you end up even more confused.
Don't worry, your not stupid. It is a confusing topic to begin with.
Without further ado, here's my take on the subject.
What is recursion?
There's this old joke about recursion:
To understand recursion, you must first understand recursion
When I first read this, my mind was blown because I didn't understand shit. But now whenever someone asks me "What is recursion?" I simply quote the joke because it is true.
Simply explained recursion is a method of solving problems by breaking them down into smaller problems, aka Divide and Conquer.
Lets imagine a scenario:
Problem: You ordered a whole pizza and you want to eat it all, but the pizza is just big to eat at once.
Solution: You break down the pizza into slices, then you can eat the slices piece by piece.
This is a very abstract example of recursion but I just want you to understand the concept of divide and conquer because at it's core recursion is a way of solving problems that uses divide and conquer.
Example
Let's layout the groundwork:
Problem: I want a function that takes a number and counts down from it:
Sample Input: 5
Sample Output:
5
4
3
2
1
You might say this can be simply done using a loop and your right, but in the context of this post this is a good example to showcase recursions.
function countDownFrom(number){
if(number === 0){
return; // base case
}
console.log(number)
countDownNumber(number - 1); // recursive case
}
Let's break this down every recursive function should have:
Base case: It's a condition that stops function, without it our functions will go on endlessly.
Recursive case: It's where you call the function again with different parameters.
Now we can give recursion a new definition:
Recursion is when a function calls itself, until it doesnβt.
Conclusion
I hope by the end of this you are less confused about recursion. If you got any questions leave them down in the comments.
Top comments (0)