Tell us what’s happening:
So I was able to do the solution just from mirroring the example provided… however I have no idea whats going on. I was hoping someone could help explain what js is doing in simpler terms. I’m trying to grasp recursion at the moment and my head hurts thinking about it.
so, I pass the arguments array and 3, it checks if 3 == 0 which it doesn’t, so then moves to the else statement. It takes in array and n - 1 (2?), then adds arr[n-1] so the second index of the array (4?) so 6 so far? And then it checks the first condition, n is at 2 now so moves on to the else. n-1 (1) + arr[1] which is 3…and i guess that does equal 9. so now n is at 1, it goes to else statement n-1 = 0, adds that to index 0 which is 2… so shouldn’t it end at 11? Or does it see the n -1 = 0 and go back to the if statement to end it?
I’m also trying to comprehend where this is stored in memory. Since the total adding up isn’t assigned to any variable. does js just know to hold that value and keep adding to it?
I’m struggling with the self teaching at the moment I also didn’t get much sleep last night and doing this alongside my real job so apologies if i missed something simple!
Your code so far
let array = [2, 3, 4]
function sum(arr, n) {
if (n == 0) {
return 0
} else {
return sum(arr, n - 1) + arr[n - 1]
}
}
console.log(sum(array, 3))
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.97 Safari/537.36
.
Challenge: Replace Loops using Recursion
Link to the challenge: