JavaScript: Nesting For Loops (multiplyAll)

Hi guys,

I’m having a real problem understanding this exercise. I KIND of get the nested loops concept, but I don’t get what we are producing by doing the following:


 product = product * arr[i][j]

What’s happening with the arr[i][j] here!

I also have no idea what the actual answer is as we are given three different outcomes, and this one in particular is baffling:

multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]]) should return 54

Any help appreciated, thank you

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]]);

Challenge: Nesting For Loops

Link to the challenge:

Hi @mtahir2020 !

Welcome to the forum!

So let’s focus on this nested array.

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;

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.

1 Like

Thanks jwilkins for such a thorough and patient explanation, I really appreciate it.

Really helped boost my understanding of this exercise! I just wrote it all out on paper and it worked!

1 Like

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