Replace Loops using Recursion -1 explanation

Ah well, it is difficult for me to explain everything from square-one. I assume you have completed all the challenges before this one: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion
If not, please do.

Otherwise, let me rephrase what I said: You have this function

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

You would use this function by calling it like so (this is an example):

var myArr = [2, 3, 4, 5];
var numberOfElements = 2;
multiply(myArr, numberOfElements);

When this is called, the following will happen:

function multiply(arr, n) {
// Now arr = [2, 3, 4, 5], and n = 2
// n > 0, So this does not run
    if (n <= 0) {
      return 1;
    } else { // The function is called again, but the arguments have changed
      return multiply(arr, n - 1) * arr[n - 1]; // arr[2-1] is the same as arr[1] == 3 (the second element of arr)
    }
  }

Next, this:

function multiply(arr, n) {
// arr = [2, 3, 4, 5];
// n = 2-1
    if (n <= 0) { // This still does not apply
      return 1;
    } else { // This is called again, again with different arguments
      return multiply(arr, n - 1) * arr[n - 1]; // arr[1-1] == arr[0] which is equal to 2 (the first element of arr)
    }
  }

Next this:

function multiply(arr, n) {
// arr does not change...
// n = 2 - 1 - 1 which is equal to 0
    if (n <= 0) { // This is true!
      return 1; // So, 1 is returned...
    } else {
      return multiply(arr, n - 1) * arr[n - 1];
    }
  }

Now, follow everything backwards to get to the original return statement.

I hope this helps. If not, search this forum for posts about recursion, as others have answered with much better responses.

1 Like