Tell us what’s happening:
This problem introduces recursion and I got the solution from another person online. However, I understand the concept of recursion but I don’t understand the following line: return sum(arr, n - 1) + arr[n - 1];
Does sum(arr, n - 1) recall the function with a different parameter of n - 1, and then arr[n - 1] adds the value of the nth element in the arr to the function and repeats this process until n <= 0?
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
}
console. log(sum([5, 3, 4], 3))
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36
If so, please edit your post to include it in the Tell us what’s happening section.
Learning to describe problems is hard, but it is an important part of learning how to code.
Also, the more information you give us, the more likely we are to be able to help.
The sum(arr, n - 1) is the recursive function call. In words, this line says, return the sum of the first n-1 elements in the arr plus the nth element in the arr.
Pretty much.
A recursion is a function that calls itself, and needs always a base case to start “unfolding” the operations, else it will keep calling itself forever
You can visualize the execution this way:
-> sum([5, 3, 4], 3)
-> is n <= 0? NO
-> then returns sum([5,3,4], 2) + 4
In order to do that, the engine realize that it has to “solve” this new call to sum first, to know exactly the value to add.
So it will add this function to the stack (the “pile” of stuff to do).