Help Me Understand How Recursions Works

I don’t quit understand how my code magically ran and successfully passed all the test cases ^^

So I’d appreciate it if you break it down for me, so I can understand wha what happened behind the scene!


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
}
const ahmedArray = [10, 20]
console.log(sum(ahmedArray, 2))

Challenge: Replace Loops using Recursion

Link to the challenge:

Hey ahmed520,

I still remember when I learned about recursion for the first time. It was confusing for me too :slight_smile:

A recursive function is a functon that calls itself again to calculate some result.

In your case, the function sum calls itself as long as “n” is greater than -1.

Let’s look into an example together:

sum([5, 3, 4],  2)

This function call should return 5 + 3 + 4 =12

Your JavaScript interpreter resolves this function call step by step like so:

sum([5, 4, 3], 2)
sum([5, 4, 3], 1) + 3 
sum([5, 4, 3], 0) + 4 + 3 
sum([5, 4, 3], -1) + 5 + 4 + 3
0 + 5 + 4 + 3
12

The recursion concept originates from math. In math, you can define a function recursively.

Take the factorial function for example.

factorial(n) =  n * factorial(n-1)        n > 0
factorial(0) = 1                          n = 0

As you might see now, there are two essentials parts of a recursion:

(1) a part that computes something. This is the case n > 0 in our factorial example

(2) a termination condition. So a condition that when it becomes true stops the recursion. This is the case n = 0 in our factorial example

best
Dennis

2 Likes

I genuinely I appreciate you taking time just to explain this to me! And I want to tell you that I finally understand my code and your code… thank you to the moon and back. :heart:

1 Like

You are welcome ahmed520 and keep coding! :slight_smile:

best ,
Dennis

1 Like

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