Basic JavaScript - Replace Loops using Recursion

Hi all,
I’m working on replacing loops using recursion but am realizing that I’m not understanding something with functions. I am simply trying to console.log this example before I try to make it a recursive function:

function multiply(arr, n) {
    let product = 1;
    for (let 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. (End of example)

How would I console.log the above example to better understand what is happening with that function. Also, I’m not sure I understand why the “n” is “n - 1”. Any advice would be appreciated. Thanks

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

  // Only change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Replace Loops using Recursion

Link to the challenge:

One option is to log the input parameters right at the start of the function.
Another one (not mutually exclusive) is to log the value that is being returned by storing it in a variable first, then logging it, then returning it.

I would use both of these.

Recursion requires a “reduction” in problem size. Each time the function is called, the work being asked for is smaller. So that is what n-1 is about.
Initially we have a task of adding n numbers. Then we reduce that to a task of adding n-1 numbers, then less again until we have no numbers to add.

Thank you very much! I now understand where I was going wrong.

1 Like

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