JS Recursion explanation

Can someone explain to me how the recursion function works in the curriculum.

This is my code:

function sum(arr, n){
if (n <=0){
return arr[0];
else {
return sum(arr, n-1) + arr[n];

So this completes the challenge and i passed it, i’m just not quite sure how the value of 5 gets output when sum([2,3,4], 1) and the value of 9 gets output when sum([2,3,4], 2).

Any explanations would be greatly appreciated! :slight_smile:

I haven’t done these challenges, but from the code you provided, the function returns the sum of elements of an array from index of n to 0 by decreasing the value of n by 1, so
The first part of function if(n<=0) return arr[0], simply means return the value of array at index 0 if the value of n is less or equal to 0
For example arr = [2,3,4] , then arr[0] = 2.

The second part, where the recursion ( a function calling itself), is,
i.e return sum(arr, n-1) + arr[n], so for example, if initial value of n=2, then
Initially function checks is n<=0, no, it moves to the else block
return sum (arr, 2-1) + arr[2] same as
return sum(arr, 1) + arr[2] where n=1, checks again if n<=0, no, moves to else block
return sum(arr, 1-1) + arr[1] + arr[2], same as
return sum(arr, 0) + arr[1] + arr[2] , here n=0, therefore
return arr[0] + arr[1] + arr[2] same as
return 2 + 3 + 4 => 9

Hopefully you can understand my explanation, if not some one else may explain in better

1 Like