Replace Loops using Recursion | I dont understand

Tell us what’s happening:
I just don’t understand this lecture.
I find the explanation very hard to grasp.
Can anyone explain it to me in more eazy way?

Your code so far


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

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36.

Challenge: Replace Loops using Recursion

Link to the challenge:

Hi and welcome to the forum.

Can you be a bit more specific about what part you want explained?

There are a few threads about explaining recursion if you use the forum search feature. These may be helpful to you.

As a first step in understanding any code, I’d try adding some console.log statements to see what is going on.

I don’t think there is an easy way to understand recursion. One part is that the base case (the if (n <=0) ) is what stops the loop. The calls to the function beneath that have to eventually result in (n <=0) to stop the loop.

This is similar to the stop condition in a while loop (while n <=0) or a for loop (let n = 10; n<=0; n–).

The calls beneath it need to have a mechanism to change n in such a way that the stop condition is eventually reached. In this case, the [n-1] accomplishes that, as with enough calls, each reducing n by 1, it will eventually get to 0.

Okay, now the hard part is how all that comes out to a nice, tidy, answer. That is where the hard thinking comes into play, unfortunately. For me, I will get pen and paper and make a chart that shows how each part is changed at every step of the way.That usually helps me understand what’s going on.

Good luck!

1 Like