After reading MDN and watching several tutorials Im still struggling to firmly grasp recursion.
I’ll use the first challenge from the JS curriculum as an example:
function sum(arr, n) {
if (n <=0){
return 0
}else return sum(arr , n -1) + arr[n - 1];
}
I am able to come to this answer however I’m not totally understanding how it works.
A test condition example would be sum([2, 3, 4], 1) should equal 2.
So if I pass that in:
if (1 <= 0){
return 0 //this evaluates as false so we move on//
} else return sum([2 , 3 , 4], 1) + [2 , 3 , 4][n-1];
//This line is where I get confused
I am confused on how to calculate the line in my head.
In my head:
([2 , 3 , 4] , 1)
I dont see any math that can be done here? So we add that line to:
[2 , 3 ,4][1-1];
Some math can be done here however Im confused as to what exactly. The array is multiply to the index of n -1? So am I multiplying (in this case) everything by 0? Or just 2 since thats technically index 0?
In my head this simplifies to:
([2 ,3 ,4] , 1) + [0][0]
Or:
([2 ,3 ,4]) , 1 + [0 , 3 ,4][0]
Either way both result in n = 0 which would satisfy the first condition of the if statment returning 0 ultimetly.
However the test condition says that
function sum([2 ,3 ,4]) , 1)
Should return as 2?
Can someone help me out here …
Any and all help is appreciated, thanks in advance!