Recursive Count In Js What Happen After Reaching 0?
Solution 1:
As you are not getting the hang of function calls, before diving into recursion, you have to first absolutely understand the following program. I have added comments with full flow as well. Here we are calling one function from another. Recursion is also same but the same function getting called by itself. So first understand the below :-
functionfunction1(a,b)
{
let result1 = function2(a,b);
return result1 + a + b;
}
functionfunction2(a,b){
let result2 = function3(a,b);
return result2 * a * b;
}
functionfunction3(a,b){
let result3 = function4(a,b);
return result3 - a - b;
}
functionfunction4(a,b){return a/b}
console.log(function1(4,2))
// It will work like this :-/*
function1 gets called with a=2,b=4
function2 gets called with a=2,b=4
function3 gets called with a=2,b=4
function4 gets called with a=2,b=4 and doesn't call anymore function inside. Evaluates a/b = 4/2 = 2 and returns 2 back to point inside function3 where it was called
Now function 3 evaluates 2 - 2 - 4 = -4 and returns -4 back to point inside function 2 where it was called
Now function 2 evaluates -4 * 2 * 4 = -32 and returns -32 back to point inside function 1 where it was called
Now function 1 evaluates -32 + 2 + 4 = -26 and returns -26 back to point where it was called which was inside console.log
*/
Let's go bottom-up approach (when we reach base case of returning empty array) :-
for n=0
An empty array []
gets returned to the countArray
where n
was 1.
So for n=1
, [].push(1)
happens and now this array is returned to the countArray
where n
was 2.
So for n=2, [1].push(2)
happens and now this array is returned to the countArray
where n
was 3.
This goes on till n=5
when it all started and also this is where you are logging the final result.
The crux is that all this happend while backtracking from n=0
to n=5
and not from top to down.
Following is the visualization (Starts with going top to bottom and then bottom to top) :-
Post a Comment for "Recursive Count In Js What Happen After Reaching 0?"