Replace loops using recursion comparison with loops

Tell us what’s happening:

I just can’t understand this part of the lesson of "Replace loops using recursion."

However, notice that multiply(arr, n) == multiply(arr, n - 1) * arr[n] . That means you can rewrite multiply in terms of itself and never need to use a loop.

especially this part.
multiply(arr, n) == multiply(arr, n - 1) * arr[n]

can anyone please tell what’s happening in this code? why they are equal?

Your code so far

function sum(arr, n) {
// Only change code below this line
let product = arr[0];
for (let i = 1; i <= n; i++) {
product += arr[i]

return product
// Only change code above this line


console.log(sum([2,3,4], 1))

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36.

Challenge: Replace Loops using Recursion

Link to the challenge: text

if multiply(arr, n) will output the numbers in arr multyplied to each other till index n, then you can take the multiplication of numbers till index n-1 and multiply that for the number at index n and get the same result


let arr = [2,3,4,5,6,7,8,9];
multiply(arr, 5); // this equal 2*3*4*5*6*7
multiply(arr, 4); // this equal 2*3*4*5*6
multiply(arr, 4) * arr[5]; // this equal (2*3*4*5*6)*7
// so line 2 and 4 of this block of code give the same value