Nesting for loops - why doesn't my code read the array as I expect?

It seems to manage to multiply the first array item fine - but then i = 1 but product is 15? I was expecting it to multiply [1][0] (3) and [1][1] (4) to get 12.

arr.length is 3 - so why does this loop twice? And why is my product returning decimals?

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

// Modify values below to test your code


When code doesn’t work, particularly if it’s something that many people have looked at already, it’s more often than not that your logic is flawed. The first thing you should do is to go through step-by-step what your code is doing:

Currently your code loops through the number of times for arr.length number of times—that’s 3 using the example included in your code. Indeed, if you simply include one line of console.log(i) inside the for loop, the output will be:


In each iteration of the for loop, you are carrying out the following operation:

product = product + arr[i][0] * arr[i][1];

In other words, during each iteration you are doing the following:

  1. Multiply the first and second numbers in arr[i]
  2. Add the result from Step 1 to product
  3. Assign the sum from Step 2 to product

Therefore, in the first iteration (i = 0) you get: product = 1 + 1 * 2; the second iteration (i = 1) you get product = 3 + 3 * 4; and the third iteration (i = 2) you get product = 15 + 5 * 6.

Reading through the example code and the description carefully will probably help a lot.

For future reference, it would be fantastic if you could either provide the test cases that you are talking about specifically or a link to the exercise. :slight_smile:

Thank you! I have a much better understanding now :slight_smile: