Question about JS Recursive Functions

I have read articles on the internet to better understand recursive functions, but I did not find an answer to what eludes me.

In the Replace Loops using Recursion from the JavaScript section we have the following code:

 function multiply(arr, n) {
    if (n <= 0) {
      return 1;
    } else {
      return multiply(arr, n - 1) * arr[n - 1];
    }
  }

What I would like to understand is when the function is invoked what is the value of multiply(arr, n -1)?

Let’s say the function is invoked like this

multiply([2, 3, 6, 5, 8], 5);

So in the first iteration, the return line would be:

 return multiply([2, 3, 6, 5, 8],  4) * arr[4];

I don’t understand how we are multiplying [2, 3, 6, 5, 8], 4 to arr[4] (8 in our case).

I found this example:

function factorial(x) {
  // TERMINATION
  if (x < 0) return;  
  // BASE
  if (x === 0) return 1;  
  // RECURSION
  return x * factorial(x - 1);
} 

factorial(3);
// 6

of a recursion that makes sense to me because we are multiplying by a single number when the recursion occurs, but I don’t understand how the example from freeCodeCamp works.

Thank you in advance :slight_smile:

If we want the product of the elements of an array, that is the last number times the product of all the elements before it. If we want to multiply the first four elements, for example, it would be the fourth number times the product of the first three.
So what’s the product of the first three? It’s the third one, times the product of the first two.

The return multiply(arr, n-1) * arr[n-1] is “The product of the first n numbers is the nth number times the product of all the stuff before it.”

Thank you for the reply.

I understand how the multiplication of it works. My question was about understanding how multiply(arr, n-1) results to those n numbers before the n times that we want to multiply.

So in our case, how does the initial recursion become 5 * 8 and then 6 * 40 and so on. Does multiply(arr, n-1) somehow go inside the array to access the numbers to multiply them to arr[n-1]?

multiply([2, 3, 6, 5, 8], 5);

returns

multiply([2,3,6,5,8], 4) * 8

and

multiply([2,3,4,6,5,8], 4)

returns

multiply([2,3,4,6,5,8], 3) * 5

and so on so that

multiply([2,3,6,5,8], 4) * 8

recurses down to

multiply([2,3,6,5,8], 0) * 2 * 3 * 6 * 5 * 8

and

multiply([2,3,6,5,8], 0) 

is our “base case”. It just returns 1. So we now get to

1 * 2 * 3 * 6 * 5 * 8
1 Like