# Replace Loops using Recursion -- hung up

`function sum(arr, n) {`

`if(n <= 0) {`

``````return 0;
``````

`} else {`

``````return sum(arr, n - 1) + arr[n - 1];
``````

`}`

`}`

`console.log(sum([2, 3, 4, 5], 3))`

I don’t understand why "sum(arr, n-1) " is not being added to the total. It seems that the function is just looping through and adding arr, arr and arr, while "sum(arr, n-1) " is merely functioning as a counter.

How is it only functioning as a counter when it’s on the left side of an equation…that is, sum(arr, n-1) + arr[n-1] . The only thing that is being added is what is being looped on the right side of the equation.

I suspect that part of what makes this confusing is that you are used to thinking in terms of loops. This function doesn’t use a loop or counters.
This line:

``````return sum(arr, n - 1) + arr[n - 1];
``````

is adding two numbers together: the number in the array (`arr[n-1]`) and the result of calling the function `sum(arr, n-1)`.
`sum(arr, n - 1)` will resolve to a number before it is added to `arr[n-1]`. You’ve seen this sort of thing before when you’ve used built in methods - `Math.random() + 1` is an example where the function `Math.random()` returns a number and that is what is added to `1`.

Recursive functions call themselves, but it’s important to remember that a function isn’t a single entity like an assembly line - it’s a set of instructions. When `sum` calls itself it isn’t just going back to the top (like a loop does). It is creating a completely separate function call.

`sum(arr, n - 1) + arr[n - 1]` calls a function, waits for it to return, and then adds a number to it. `sum(arr, n - 1)` executes and returns a number. That number might be zero or it might not. If the second argument it was passed wasn’t zero, then it will call also have to call the `sum` function and wait for it to finish before it returns a number. It doesn’t know or care whether it was called recursively.

1 Like

Thank you for taking the time to respond, it makes more sense now I’m glad I could help. Happy coding!

1 Like

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