Explanation for Basic JavaScript: Replace Loops using Recursion

Hello everyone, please help me understand how this code works, I’m confused:

  • Why do we set: n<=0?
  • Why do we have to return 1 instead of 0 or other numbers in this case?
  • And this, I don’t understand what it does: multiply(arr, n - 1) * arr[n - 1];

Please send me a link of previous post about this topic, if you have. Thanks!

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

Link to the challenge:

Recursion is complicated…

Let’s take a lazy example where arr=[2,3] and n=2

On the first iteration, the return state is:

multiply([2,3], 1)*3

Second stage (I’m executing ↑)

multiply([2,3], 0)*2*3

If we don’t stop this machine, it will count forever

multiply([2,3], -2)*multiply([2,3], -1)*2*3

Luckily we set the first condition and…

multiply([2,3], 0) 

returns 1. So we have 1*2*3

2 Likes

@anon10002461 well explained!!!

1 Like

thank you wendy!! :heart:

Hi @Americano,

I found this helpful when I was trying to understand recursion
Intro to recursion

1 Like

Thanks, @Vumbhoni! This guy has brought me back to high school right at 00:54 about 10 years ago, I was not very good at math, anyway. His tutorials are helpful and understandable.
Thank you for your explanation, @anon10002461!
And I’m really sorry, guys! I posted incorrect code instead of the correct one(example code) below. I just want to understand every single line of code but accidentally messed up.

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