# Replace Loops using Recursion -1 explanation

**URL:** <https://forum.freecodecamp.org/t/replace-loops-using-recursion-1-explanation/368021>\
**Category:** Curriculum Help\
**Tags:** javascript\
**Created:** [April 4, 2020, 12:21pm UTC](https://forum.freecodecamp.org/t/replace-loops-using-recursion-1-explanation/368021 "2020-04-04T12:21:38Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![Sky020](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/sky020/32/128093_2.png) [@Sky020](https://forum.freecodecamp.org/u/Sky020)\
**Post date:** [April 4, 2020, 12:55pm UTC](https://forum.freecodecamp.org/t/replace-loops-using-recursion-1-explanation/368021/4 "2020-04-04T12:55:36Z")

</div>

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](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

```auto
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):

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

```

When this is called, the following will happen:

```auto
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:

```auto
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:

```auto
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.

---

_[View the full topic](https://forum.freecodecamp.org/t/replace-loops-using-recursion-1-explanation/368021)._
