What exactly does sum(arr, n - 1) do. Also, in this scenario, what is it equal to?

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

Challenge: Replace Loops using Recursion

Link to the challenge:

Hello there.

Do you have a question?

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.

Hello. I have edited the Tell us what’s happening section and I tried describe what I want to know.

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 :slight_smile:

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).

Which at this point can be visualized as:

-> sum([5, 3, 4], 3)
  -> sum(5, 3, 4], 2) + 4
     -> sum(5, 3, 4], 1) + 3
        -> sum(5, 3, 4], 0) + 5
          -> Finally n <=0 so we return 0

Which means that when the base condition is reached, values start to unfold
so

0 + 5
5 + 3
8 + 4
-> print 12

Hope this helps :slight_smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.