JavaScript Recursion

I don’t understand how " return sum(arr,n-1)+arr[n-1]" in recursion computes its result. I need More Explanation. thanks

Your code so far

function sum(arr, n) {
// Only change code below this line
   return 1
  return sum(arr,n-1)+arr[n-1];
// Only change code above this line
sum([2,3,4], 1);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36.

Challenge: Replace Loops using Recursion

Link to the challenge:

The two parameters that we have are an arr of numerical values, and a number for how many times we recurse the function.

So, on the first pass we invoke sum() but n is decremented plus the selected element/item in the arr parameter. Eventually the n reaches zero from the decremented value eventully reaching zero. This happens because we have conditional that checks n when it reaches 0.

What you probably noticed was that you saw the recursion ran twice: once at the invocation at the global space, and then the second invocation within the scope of sum()

This is because even after reaching n == 0, the function before the recursion has to finish the expression before returning.

Does that make sense? Recursion can be confusing when first learning it.

1 Like

I think you will understand the code better if you see how the code is executed line by line. Check this video how to execute your code line by line.

1 Like