Are you confused with how recursions work?
If so, I’ll try to explain it in a simple way.
You need to find a key you kept in a box long time ago.
You open a box to find out that there is another box inside it. When you open that one, you find yet another one it in.
This repeats x number of times. You dont know which one has the key.
Lets write a program for this.
As you can see, this function keeps on opening the box till the key is found.
What the above code does is → if the box has the key , it will return the value of the box containing the key and the code stops executing.
Else, the function keeps opening the next box until the value in the if() block is met, that is, till the key is found
As you can see, the function calls itself, but it changes its value passed into it each time. In this case , the functions tells itself to open the next box.
This is exactly what recursions do ! They keep on executing until the value passed into the if() block is met. Otherwise, in the else block it will call the function but with a modified value so that it can check if the modified value can pass the code in the if statement.
This is a very simple explanation of recursion imo.
This is something I tried explaining to someone long ago.
What this piece of code does is multiply the first n elements of an array.
multiply([2, 3, 4, 5], 3) would return
2 x 3 x 4 returns 24.
n-1 helps give the correct index of the array. Remember that the index starts at 0.
SO each time this would become
multiply([2, 3, 4, 5], 2) * arr ,
multiply([2,3,4,5],1) * arr …
Lets take another example.
If you put a
console.log(n) statement before the return we get this.
3, 2, 1 are the values of n .
Here, 60 is the value of
multiply([2, 5 ,6 ], 3)
console.log(n-1) would give the values
Notice how it stops at 0 (as it satisfies the condition met in the if statement of
n <= 0 )
The function multiplies the current value with the previous value and then returns the answer when the condition in the
if() block is met. So here, this would multiply the returned values until
Loops are actually easier than recursions. You might only really need them for interviews or maybe rarely. Imo, you can do pretty much anything recursion does with loops. But its always good to know how something works .