"simple" question about a function

I am on lesson 101 of Javascript. I’m SO close to finishing the basics (although I’m probably going to need to keep peeking back and forth at it). But I don’t understand one of the things its saying here.

"Recursion is the concept that a function can be expressed in terms of itself. To help understand this, start by thinking about the following task: multiply the first n elements of an array to create the product of those elements. Using a for loop, you could do this:

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

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."

Now what I’m not understanding, is where does the (n - 1) come from at the bottom where it says multiply(arr, n) == **multiply(arr, n - 1) * arr[n - 1]? I thought it would be n + 1 since statement 3 in the forloop is that i increases by 1 each time.

1 Like

With recursion you need to ‘count down’ to a smaller case by reducing your input each time so that you can reach a base case. Reaching the smallest possible input is how your code knows to stop calling itself.

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