Basic JavaScript : Replace loops using recursion

Tell us what’s happening:
let sum([2,3,4],3);
return sum(arr,n-1)+arr[n-1];//How it returns number 9.

note :i know 9 is sum of first three elements of array.But i really don’t know how it came,i tried by analyze like this, sum([2,3,4],2)+arr[2]; //since n=3;
can anybody answer me.please correct me if i wrong.

Your code so far


function sum(arr, n) {
// Only change code below this line
if(n<=0){
return 0;
}
else{
return sum(arr,n-1)+arr[n-1];
}
// Only change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36.

Challenge: Replace Loops using Recursion

Link to the challenge:

that’s correct
and sum([2,3,4], 2) will return the sum of the first two elements in the array, which is 5
so 5+4 makes 9

how does sum([2,3,4], 2) makes 5?
in this case n=2
so inside there is return sum([2,3,4], 1) + arr[1], the function returns the sum of the first one elelements in the array, so just 2, and 2+3 makes 5

how does sum([2,3,4], 1) returns 2?
in this case n=1 so inside it we have return sum([2,3,4], 0) + arr[0], the function returns 0, so it’s 0+2

how does sum([2,3,4], 0) returns 0?
in this case n=0, so the if statement execute, where there is written return 0

1 Like

@ieahleen if n=2, return sum([2,3,4],1)+arr[1]; //returns 2+3=5;
here, how function sum([2,3,4],1) returns 2?
thanks a lot ,it makes sense,still i have doubt.

what doubt do you have?

yeah,if n=1, sum([2,3,4],0)+arr[0]; here function sum([2,3,4],0) returns 0 since n=0; This case understood,
i have doubt in cases where n=2,n=3
If n=2, sum([2,3,4],1)+arr[1]; here how function sum([2,3,4],1) returns 2.
can you break down the stack especially for sum([2,3,4],1), how it returns 2 ?
Hope you understood my confusion :grimacing:

sum([2,3,4], 1) returns the sum of the first one items in the array

inside this function you have return sum([2,3,4], n-1) + arr[n-1] as n is 1, it’s return sum([2,3,4], 0) + arr[0]
sum([2,3,4], 0) returns 0, and arr[0] has value of 2
so it’s return 0 + 2 or just return 2

1 Like

@ieahleen thank you ,understood.
Actually, " that returns the sum of the first n elements of an array " ,is given in
condition itself.