How does the code in the example ever return anything other than 1?

I don’t understand why this loop will ever return anything other than ‘1’. At some point while the code runs n will equal 0, in which case the program stops and returns ‘1’.

Your code so far

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36.

Challenge: Replace Loops using Recursion

Link to the challenge:

multiply(arr, 0) returns 1

but multply(arr, 1) returns multiply(arr, 0) * arr[0]. we know from above the return value from the function call in there, so that is multiplied for arr[0] to get this returned value

and if the function call is multiply(arr, 2)? in this case the function returns multiply(arr, 1) * arr[1], and we know what’s the value from the function call from above, so that number is multiplied to arr[1] to get the returned value…

This has been discussed on the forum a lot, so it’s worth a search.

multiply([1, 3, 5], 3) calls multiply([1, 3, 5], 2)

multiply([1, 3, 5], 2) calls multiply([1, 3, 5], 1)

multiply([1, 3, 5], 1) calls multiply([1, 3, 5], 0)

multiply([1, 3, 5], 0) returns 1

multiply([1, 3, 5], 1) returns 1 * 1

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

multiply([1, 3, 5], 3) returns 3 * 5

1 Like

You’re right that at some point n will equal zero and the program will return 1, but the missing piece is that it’s going to return 1 as an answer to a function that was inside another function. We build a chain of functions until we finally reach one that gives us a real answer , (1 in this case), that gets passed back up the chain until we get back to the top. It sounds confusing. The easiest way to see what this really means is to work it out by hand with a simple case, like multiply([1,2], 2).
If you don’t want to do it by hand, I highly recommend . This website will step through your code one line at a time, showing you the values of everything as it goes, so you can see exactly what’s happening as code is executed. JavaScript is supported. Just type in the above code, then call the function, and watch what happens.
Additionally, there are lots of good videos on recursion on YouTube that make things easier to understand as well.

Thanks for the explanation, that made everything click into place! Had been struggling with this exercise for 2 hours until then.

1 Like