Newbie here: I need someone to see if Im understanding this recursion challenge correctly
I have been stuck on this challenge for almost a week trying to understand it. I could not wrap my head on >>return sum(arr, n - 1) + arr[n - 1] part of the code and how this code was being executed. After looking into many resources I think I finally understand it. Hopefully someone can review my train of thought and see if I’m on the right track!I Apologize in advanced if I didn’t structure this post correctly or if its a bit confusing!
//Im going to be breaking it down on how I think this code is being executed
// This what we are calling are function with: sum([2,3,4,5,6,7], 5)
function sum(arr, n) {
// Only change code below this line
if (n <= 0) {
return 0
} else {
return sum(arr, n - 1) + arr[n - 1]
}
// Since 5 is not less or equal to 0 we will move on to are Else statement with 5-1 which = 4
// return sum([2,3,4,5,6,7], 5) + arr[5]
// This when the recursion starts and the function starts calling itself
// return sum([2,3,4,5,6,7], 4) + arr[4] = 6 (since its the 4th element in are array)
// n does not = 0 so it will call the function again with 3
// return sum([2,3,4,5,6,7], 3) + arr[3] = 5 (since its the 3rd element in are array)
// n does not = 0 so it will call the function again with 2
// return sum([2,3,4,5,6,7], 2) + arr[2] = 4 (since its the 2nd element in are array)
// n does not = 0 so it will call the function again with 1
// return sum([2,3,4,5,6,7], 1) + arr[1] = 3 (since its the 1st element in are array)
// n is now is equivalent to and will return the 0
// return sum([2,3,4,5,6,7], 0) + arr[0] = 2 (since in are array indexing starts at 0 )
// After we get the value of 0 we add all the elements together to get are output
// 6 + 5 + 4 + 3 + 2 = 20
// Only change code above this line
}
console.log(sum([2,3,4,5,6,7], 5))
// This should output 20
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36
Challenge Information:
Basic JavaScript - Replace Loops using Recursion