# Basic JavaScript - Replace Loops using Recursion

Hello, I passed the test, but I have no idea what I’m doing.

Why does my code only sum the first `n` elements of an array `arr`? If it only works once, why can recursion alter the `while` and `for` loops?
What if I want to add the first two numbers of the array? What should I do?

``````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
}
``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36`

Challenge: Basic JavaScript - Replace Loops using Recursion

I’m not sure I understand what you mean by “If it only works once”. Can you elaborate a little more?

The you would pass `2` as the second argument to the function. But I’m not sure if that is what you were asking. Again, please explain in a little more detail if it was not.

This task requires the function to sum the first `n` elements of an array `arr` . So if the array contains [2, 3, 4, 5], the function will return 2.
Did I misunderstand that it only works once because it only sums the first elements of the array and not the others? Can you explain to me exactly how this function works? Thank you in advance.

Remember, you call the function with two arguments: the array and how many numbers from the array you want to add together. So in your example above, if you called the function as `sum([2, 3, 4, 5], 1)` then it will return `2`. But if you call it as `sum([2, 3, 4, 5], 2)` then you are telling it to add the first two numbers in the array and thus it will return `5`.

I think you should explain it to me Let’s take the function call `sum([2, 3, 4, 5], 2)`. What will happen when this function executes? Which `return` statement will it trigger? What will that `return` statement look like? Replace the variables names with their actual values.

Oh my God, I’ve got it now! Thank you so much. Initially, I just didn’t understand what `sum(arr, n - 1)` does. But now, with your guidance, I realize that `sum(arr, n - 1)` is the returned value of the function for the previous iteration.

That’s why the overall value will change depending on the second argument I assign to the function. Am I right?

I’m really sorry for my bad explanation throughout this entire discussion

1 Like