Basic JavaScript - Replace Loops using Recursion

Hi,
I read the discussion, but still failing to understand this bit of code: why is the following?

multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]

Could someone please break it down into what is where?

Sorry if the question seems dumb, but I don’t want to move on until I fully understand what’s happening here :slight_smile:
Many many thanks!
Describe your issue in detail here.

Your code so far

function sum(arr, n) {
  // Only change code below this line
let product = 1;

  // Only change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Replace Loops using Recursion

Link to the challenge:

Welcome Eugene,

I will try my best to explain this to you using a example:

let X = [1, 3, 4, 6, 10]

and we want to do multiply(X, 4) which means “multiply the first four elements of the array X”

The function as it is defined in the theory goes:

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

So, let us agree that multiplying the first four elements of X is equivalent to multiplying the first three elements of the array X times the fourth element of the array X. This is as follows:

1 X 3 X 4 X 6 = multiply (X, 4)

(1 X 3 X 4) X 6 = multiply (X, 3) * X [3] = multiply (X,3) * 6

We can repeat the same routine with multiply (X,3) and say that:

multiply (X, 3) = multiply (X, 2) * X[2]

When does this same routine stops? Until you do multiply (X, n <=0) in which case it returns a value of 1.

So, let’s give your multiply function a try:

let X = [1, 3, 4, 6, 10]
  
function multiply(arr, n) {
    if (n <= 0) {
    return 1;
    } else {
    return multiply(arr, n - 1) * arr[n - 1];
    }
}

console.log(multiply(X,4));

// 72

console.log(multiply(X, 3) * X[3])

// 72

console.log(multiply(X, 2) * X[2] * X[3])

// 72

console.log(multiply(X,1) * X[1] * X[2] * X[3])

// 72

console.log(multiply(X,0) * X[0] * X[1] * X[2] * X[3] )

// 72

// Notice that multiply(X,0) = 1

console.log(multiply(X,0))

// 1

Did that make any sense?

Hi @eugenesoch,

  • There are 2 examples of the function multiply:
    • multiply using a for loop (left)
    • multiply using recursion (right)

Can you identify how the two versions are similar?

I have made a video explaining (step by step) this lesson https://youtu.be/_NsEWXD4lJ8 .

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