**Challenge:** Replace Loops using Recursion: what is this n-1?

Tell us what’s happening:
Hello folks.
I just read through this code example:

  function multiply(arr, n) {
    var product = 1;
    for (var i = 0; i < n; i++) {
        product *= arr[i];
    }
    return product;
  }

And then I am totally confused by the lines :

However, notice that multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1] . That means you can rewrite multiply in terms of itself and never need to use a loop.

What? n-1? What’s that all about? I did not notice it because it’s not in the original code block example.

Your code so far
There is no code because I don’t understand what is going on.


function sum(arr, n) {
 // Only change code below this line

 // Only change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0.

Challenge: Replace Loops using Recursion

Link to the challenge:

This image is how I worked out to understand recursion from the example. Like you, I didn’t “notice that (etc.)” and never would notice that, so I think perhaps that phrase is confusing. I think all it means is that you’ll get the same result by doing it this way. But I think this particular challenge skips over fully breaking down the many steps in recursion. Hopefully my image helps someone.

n-1 is not in the original code block example like you say. You wouldn’t notice that solving the problem recursively (the second code example - broken down in my image) gets the same result as the first block, because they haven’t told you yet. I agree this is confusing way of saying… “Look now, the first way of doing it gets the same result as this new way of doing it which is written below”. The new way of doing it is hard to get head around. It involves choosing element in array by “one less than number entered as argument”. Each time the function is called again, the number is getting one less each time. Until it hits zero. Then the value 1 is returned and used to resolve the multiplication in the one level up. The result of that is used to resolve the one level up above that. Etc until you only have one final multiplication to make, which is the answer.

Thank you for posting that. I’ll look at it more closely when my eyes feel less sore.
It’s things like this that remind me I’m more creative and visual than numerical.

I think the logic of these more complex aspects of JS need to be more thoroughly explained as you have done.

Thanks again. I shall mark this as a solution.