Can you you guys help how is the outcome 6?

Tell us what’s happening:
Describe your issue in detail here.

   **Your code so far**

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

 console.log(multiply([1,2,3,4,5], 3));
   **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.36

Challenge: Replace Loops using Recursion

Link to the challenge:

Hello there.

Do you have a question?

If so, please edit your post to include it in the Tell us what’s happening section.

Learning to describe problems is hard, but it is an important part of learning how to code.

Also, the more information you give us, the more likely we are to be able to help.

I wonder why the outcome is 6? I have a problem dealing with return multiply(arr, n -1) * arr[n - 1];

I have a hard time wrapping my head around recursion too.

What’s happening is that it passes in:

[1, 2, 3, 4, 5]

and n == 3.

Because N > 0, it goes to the ELSE, which calls multiply again with n -1

So it continues until it gets to n = 0, and it returns 1 to the version of multiply which called that.

So, we get the else call that says:

return {1} * arr[n-1].

In this case we know that the n == 1 since that was the value that must have been in play when it called multiply with n == 0. Since n == 1, we have return {1} * arr[0], which is also one. We return 1 to the multiply call when n == 2.

So now we have

return {1} * arr[2-1], == 2.

And now we go up another step to:

return {2} * arr[3-1] == 6.

And since that was the initial n value, you get six.

1 Like

There are a lot of posts on recursion. Please try out the search function. On this particular function, I’ve given a detailed explanations here , among other places.

Recursion is a very confusing topic, especially for beginners. It takes a while to wrap your head around it.

2 Likes

thanks man makes my brain explode

1 Like

I was right there with you just like two weeks ago. I recommend going to leetcode and doing some recursion practice problems. That’s what I did. I still can’t knock them out immediately, but I can now knock out the medium-difficulty ones with a bit of debugging and tinkering.

1 Like