I don't understand how this specific recursion works

Tell us what’s happening:
I’m wondering how the return statement calculates the sum.

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

Thank You

Your code so far

function sum(arr, n) {
// Only change code below this line
if(n <= 0){
  return 0;
  return sum(arr, n-1) + arr[n-1];
// Only change code above this line

// A recursion is the concept that a function can be expressed in terms of itself.

Your browser information:

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

Challenge: Replace Loops using Recursion

Link to the challenge:

The function call sum(arr, n) returns the sum of the first n elements of the array arr. So, the function call sum(arr, n - 1) returns the sum of the first n - 1 elements of the array arr.

arr[n - 1] is the nth element of the array, so sum(arr, n-1) + arr[n-1] is the sum of the ‘sum of the first n - 1 elements’ and the nth element… Which is the sum of the first n elements.

Hi @ahnaf4!

I have blurred out your solution for those who haven’t worked on the challenge yet.

One way to get a better understanding of recursion is to go through one of the test cases like this one sum([2, 3, 4], 1).

You can go through it with pen and paper or run a debugger on it and see what is happening.

This video also does a good job of explaining how recursion works.