Javascript replace loops with recursion

what does “product” refer to in the code below?

function multiply(arr, n) {
    var product = 1;
    for (var i = 0; i < n; i++) {
        product *= arr[i];
    }
    return product;
  }

Product is a mathematical term that refers to the result of multiplying values. The product of 2 and 3 is 6, for example.

but why are we defining product =1 in the equation? where does it come into play? i=0 i assume is the index of the array starting at 0 and going up to n

I’m not sure how much you know. It seems like this might be your first introduction to loops. Is that correct?

I believe we’re multiplying product by the index of arr, i could go back and review this stuff it might be more beneficial

i is the index. arr[i] is a value in arr.

i just cant comprehend this line, I feel like i understand everything else

why si product being initially set to 1?

Because it needs an initial value. Without one you will get an error when you try to multiply it.

Hello there,

The assignment of product = 1 is the identity value. Another example of this is:

function sumAllTheNumbersFromZero(num) {
  let sum = 0; // `0` is the identity of summing
  for (let i = 0; i < num; i++) {
    sum = sum + i;
  }
}

So, for addition, the identity is 0, because, if we set it to another number (let us say 1), then the sum of the numbers would be off by that amount.

For multiplication, the identity is 1, because, if we set it to another number (let us say 0), then the product would always be 0 -> 0 * 1 = 0 (and so it goes on)

Hope this helps

1 Like

thank you very much for the response I appreciate it, this is helpful. (thanks ArielLeslie as well)