I’m currently in the Basic JavaScript section replace-loops-using-recursion and I don’t quite get the way in which the code works.
I have read the superb article on recursion found under “Get Help” → “Watch a Video” (theres no video) and understand the principle of recursion, and how it works, but don’t get how the code works.
Here is the code I have come up with, which works, but I don’t get how it works.
function sum(arr, n) {
if (n <= 0) {return 0;}
else {
//console.log(sum(arr, n - 1) + arr[n]);
return sum(arr, n - 1) + arr[n - 1];
}
}
console.log("\n" + sum([1,2,3,4,5,6],3));
Here is as far as I get it.
- function sum is called with an array and a single digit number passed into the function
- I don’t get exactly how the below line works. Can someone spell it out for me.
I get what return does but what doessum(arr, n - 1)
do and what doesarr[n - 1];
do
return sum(arr, n - 1) + arr[n - 1];
**Your browser information:**
User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36
.
Challenge: Replace Loops using Recursion
Link to the challenge: