Nesting ForLoops

Nesting ForLoops
0

#1

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;i++){product*=arr[i][j];}}
  // 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:

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

Link to the challenge:


#2

My first suggestion is try to make your code more readable by not putting all the code on one line. The following is your same code, but had indentations to make it easier to read:

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

// Modify values below to test your code
multiplyAll([[1,2],[3,4],[5,6,7]]);

My second suggestion is to always ask a specific question about your code. You did not ask a question, so we to assume what you may be asking about.

In this case, I assume you are wondering why you are getting the following error in your console:

TypeError: Cannot read property ‘length’ of undefined

Because you put all your code on one line, it makes it a little harder to pin point the problem because your code has two references to length. Once you reorganize your code onto separate lines (like I did above), you would find the issues is in your second for loop (see below):

    for (var j = 0; j < arr[i].length; i++) {

Since you are wanting to iterate over the all the elements in arr[i], and you are using j as the index for the a[i] array, your i++ should changed to be j++.