Nesting For Loops-- what am I doing wrong?

Tell us what’s happening:

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++) {
    arr[i][j]) * product;
  }
}
  // Only change code above this line
  return product;
}

// Modify values below to test your code
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/69.0.3497.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/nesting-for-loops

You have a stray ) in your code
Where are you keeping the results of arr[i][j]) * product; ?

I got the right answer. Can you please help me better understand why we need to use .length ? What would happen if it wasn’t used?

Let me try.

If you have this array [20,25,30]
it has a length of 3
and has these three indices 0,1,2 arr[0] is 20, arr[1] is 25 and arr[2] is 30

So the .length property will always be one more than the largest index

When you loop through this array you want to visit arr[0], arr[1] and arr[2]
So you start at i = 0 and you continue while i < arr.length (aka 3) is true
Each cycle of the loop you visit arr[i] and then add 1 to i
When i actually becomes 3 the condition is false - 3 is not < arr.length - and the loop stops.
That is good because there is not an arr[3]

2 Likes