Basic JavaScript - Replace Loops using Recursion

How does multiply(arr,n) == multiply(arr, n - 1) * arr[n - 1] how does the two statemtents above equal each , n and n - 1??

function sum(arr, n) {
  // Only change code below this line
if (n <= 0) {
  return 0;
} else {
return sum(arr, n - 1) + arr[n - 1]
}

**Challenge:** Basic JavaScript - Replace Loops using Recursion

**Link to the challenge:**
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion

Hi @bushra.ghames2707
Could you explain your question more

If you are asking about recursion, I’ll do my best to explain it.
let’s say that n=3:

function sum(arr, n) {
  // Only change code below this line
  if (n <= 0) {
    return 0;
  } else {
    return sum(arr, n - 1) + arr[n - 1];
  }
  sum([5,2,2,5,3],3);// ans = 9
  // The first recursive will return sum(arr, 2) + arr[2];
  // The second recursive will return sum(arr, 1) + arr[1];
  // The third recursive will return sum(arr, 0) + arr[0];
  // Because n = 0, it will return 0 this time.
  // Now, we can combine all the 'RETURNS' : arr[0] + arr[1] + arr[2] + 0;

the same applies to multiply.

2 Likes

Thanks i get it now!!

1 Like

I wanted to know why does we subtract 1 from n, and i understand it now. It’s to take the first element of an array, since the first element index < last element index and thanks for your time!

1 Like