I am so confused by this

Tell us what’s happening:
why is it necessary to multiply :
product= product*arr[i][j];
if product is equal 1 anyways .

  **Your code so far**

function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
 product= product*arr[i][j];}
}
// Only change code above this line
return product;
}

multiplyAll([[1,2],[3,4],[5,6,7]]);
  **Your browser information:**

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

Challenge: Nesting For Loops

Link to the challenge:

1 Like

As the nested loops continue through all iterations, the value of product keeps getting updated. The value starts at 1 but it keeps getting multiplied by different values on each loop iteration to make it larger.

1 Like

HI @mayanwiner !

Welcome to the forum!

As mentioned earlier, product does not just stay at one .
It is constantly being updated.

I am going to copy and paste a reply I made to another user on how this works and hopefully it will help you too.

So let’s focus on this nested array.

[[1,2],[3,4],[5,6,7]]

Our task is to get the product of all of the numbers in the subarrays.

These are the sub arrays

[1,2]
[3,4]
[5,6,7]

When i=0 this piece of code arr[i] targets the first sub array [1,2].

We check the condition

Is i < arr.length; Yes

Now we enter the inner loop(or the j loop) and have this code arr[i][j]

That translates to arr[0][0] or the number 1.
That second [0] targets the first element of the subarray because remember arrays are zero based index.

So now we can execute this line of code

product = product * arr[i][j];

translates to

1 = 1*1

Now we increment j by 1 ( j++)
And product is still 1.

We check the condition

Is j < arr[0].length; Yes

Now arr[i][j] turns into arr[0][1]

arr[0][1] is the second element in our first subarray.
The second element is the number 2.

Now we execute this line of code

product = product * arr[i][j];

translates to

2 = 1 * 2;

Now product is 2.
We now have to increment j by 1 ( j++)
Now j =2
Now we check the condition of the j loop

Is j < arr[0].length?
No, because 2 is not less than 2. This subarray [1,2] only has two elements.

Now we leave the j loop and increment i by 1 (i++)
Now i=1

We check the condition
Is i < arr.length; Yes

Now arr[i][j] is arr[1][0]

Then we go through the same steps as before and always assigning the new result to the product.

Hope that makes sense on how nested arrays work.

5 Likes

Also, remember that this doesn’t mean equals.

In programming, it means 1 is being assigned to the variable called product.
If you want to say equals then you would have to write this product === 1

3 Likes

Thanks for the detailed explanation, this one is a bit of a doozy when you’re new.