WHAT IS RECURSION?
The simplest definition of recursion is simply when a function solves a problem by calling itself. Confusing right? Yes and no. I am going to illustrate how recursion works in both real life and in javascript in order to make things clearer.
HUNGER ILLUSTRATION
Imagine that you are hungry now and you will like to eat 'Jollof Rice'. Let us write the solution in pseudo code
First you need to dish the Jollof Rice
then you need to eat the Jollof rice
In Javascript, the code will look like this.
function eat(food) {
dish(food)
eatFood();
}
if(hungry) {
eat('Jollof Rice')
}
If hungry is true, to eat, you dish the food and start eating. Simple right?
Except eating is not that simple. It involves carrying the rice with fork and chewing it before swallowing it.
function eat(food) {
dish(food)
eatFood()
}
function eatFood() {
carryForkOfRice()
chewAndSwallow()
}
if(hungry) {
eat('Jollof Rice')
}
And then again and again, you carry fork and chew, the process only stops when you are satisfied. One spoonfull can not possible satisfy you right? You need to do it again and again. And that is why recursion comes in, the eat food function has to keep calling itself for the hunger to quench. Which means your eat food function has now gone recursive as it now calls itself over and over.
function eatFood() {
carryForkOfRice()
chewAndSwallow()
eatFood()
}
But just as a computer has a limited memory, in the same way, your stomach can only take a sizeable amount of food. Which means your brain has to check after each for of rice whether you are satiated or not, in order to prevent overfeeding. This we implement by checking if you are satiated after swallowing food.
function eatFood() {
carryForkOfRice()
chewAndSwallow()
if(satiated) {
return
} else {
eatFood()
}
}
In programming, a recursive function will continue to run perpetually until the computer runs out of memory. To prevent this, a breaking comdition is set. A good example is the if satiated clause condition in our eat food condition above.
Top comments (0)