JavaScript Recursion

I can only tell you what I guess is happening, because I’m not looking for help with code, but understanding.

It looks to me like this function takes an array and a number, and so long as that number is not 0, it multiplies the array at n, times array position n-1. I don’t however, see anything the decrements the index position or original number so that each number in the array is multiplied, or summed in the case of the solution.

Can someone please help me understand this? While I guessed the answer, I do not understand what is happening.

I will try to explain, but sometimes recursion takes doing to understand (some people just need to write more code to get it).

This is the function code with some line numbers I added:

01:  function multiply(arr, n) {
02:    if (n <= 0) {
03:      return 1;
04:    } else {
05:      return multiply(arr, n - 1) * arr[n - 1];
06:    }
07:  }

Now we can run through this code with some inputs to see what is happening:
arr possibly has 3 numbers, let’s say 5, 6, 7
n is 3 because I want to start my multiplication at the last number (so mulitply from 7)

line 1 multiply was called. multiply gets the array 5, 6, 7 and 3
line 2, is 3 less than or equal to 0? no

line 5, call my friend to help me multiply. His name is also multiply. Give him 5,6,7. & Tell him that n is 2.
Now wait for my friend to help me…

line 1 this is multiply’s friend who was called by multiply. This multiply gets the array 5,6,7 and 2
line 2, is 2 <= 0, nope

line 5, call my other friend to help me multiply. His name is also multiply. Give him 5,6,7 and tell him that n is 1.
Now wait for my other friend to help me…

line 1, this is the other friend of the friend of multiply. This multiply gets the array 5,6,7 and 1
line 2, is 1 <= 0, nope

line 5, call my other other friend to help me multiply. His name is also multiply. Give him 5, 6, 7 and tell him that n is 0.
Now wait for my other other friend to help me

line 1, this is the other other friend of the other friend of the friend of multiply. This multiply gets the array 5, 6, 7 and 0
line 2, is 0 <= 0, YES!
line 3, return 1 to my other friend

other friend gets back the 1 then continues with
line 5, multiply 1 with 5 (arr[n-1], recall that the ‘other friend’ got n=1) and
return 5 (result of 1 * 5) to my friend

my friend get back the 5 then continues with
line 5, multiply 5 with 6 (arr[n-1], recall that the friend got n=2) and
return 30

I get back 30, finally, now I can continue with my own
line 5, multiply 30 with 7 (arr[n-1], recall that my n was 3) and
return 210

done.

The reason all this worked is because we were taking a problem and breaking it up into incrementally smaller pieces.
Essentially multiply does only one multiplication at a time, but repeating it over a smaller and smaller set of numbers till finally there is only 2 numbers to multiply and return.

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