Tell us what’s happening:
Describe your issue in detail here. I got the code right but i do not understand the code How does this work? return sum(arr, n-1) + arr[n-1]
Your code so far
function sum(arr, n) {
// Only change code below this line
if(n <= 0){
return n;
}
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 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36
Challenge: Basic JavaScript - Replace Loops using Recursion
We have blurred this solution with [spoiler][/spoiler] tags so that users who have not completed this challenge can read the discussion in this thread without giving away the solution.
So it sounds like it is the larger issue of not understanding recursion.
That is very common. Recursion is weird. There have been many, many, many discussions about it in the forum, many on this exact questions, some with detailed explanations, some even by me. I would suggest search those first.
But like I said, it is a tricky subject. Don’t be discouraged if it takes a while to wrap your head around it.
You can use this tool to visualizing your code running Python tutor (it works with other languages too)
Remember call your function too, for example sum([2, 2, 2, 2], 2).
It is always helpful read different examples and explanations. The best two pages as reference are MDN Web Docs and this one Recursion and stack
A recursive function is like a family tree, you call the function and that function call another one with different arguments and so on (going down). After, the function start to run from the last one (with the last possible arguments) to the started point (going up in the tree). Every returning value it will be use for the parent function as keep going up.