Basic JavaScript #103: Replace Loops using Recursion

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

In the base case, where n <= 0 , it returns 1.

What is the purpose for, and result of, returning 1 here?


Edit: multiply(arr, 0) would equal 0, right? Instead of doing the multiplication in this instance, we are returning 1, which isn’t the same result as if we had done multiplication, right? I’m awful at math.

I think there is an assumption here that you would never directly call this function passing 0 in for the second argument. This recursive function is just being used as a simple example of how recursion works. You would never use it in real code. But you can’t return 0 when you hit the base case because anything multiplied by 0 is 0 and that would wipe out the total product that you had computed with all the other recursive calls.

2 Likes

Okay, thank you. I thought that maybe I had been wrong about my fundamental understanding of what the function was doing.

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