Nesting For Loops why can't work

Tell us what’s happening:

Cannot read property ‘length’ of undefined
cannot read property ‘length’ of undefined
Cannot read property ‘length’ of undefined
I don’t know, what am I doing wrong?

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 = 1; j < arr[i].length; i++) {
      for (var l = 2; l < arr[j].length; i++) {
        console.log(product = product * arr[i][j][l]);
      }
    }
  }
  // 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 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36.

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

I think the first problem is that you have one too many nested loops. If you compare with the example in the challenge, it is also nesting through a 2D array. It only uses 2 for loops - arr[i] to get the subarray, like [1, 2], and then arr[i][j] to get the individual numbers inside.

The other issue I am noticing is the way your variables are initialized. Because j is initialized as 1, your second for loop is actually starting on the number 2 instead of the number 1. Comparing to the example again might help. :slight_smile:

Oh yeah! The reason it is giving you a message about “undefined”, is because arr[i][j][l] does not exist. :woman_facepalming:

There is also one other small typo in your second for loop - let me know if you need help identifying it or have any other questions!

i have delete [l],but can’t work
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; i++) {
console.log(product = product * arr[i][j]);

question:Cannot read property ‘length’ of undefined

Take a look at your second for loop; it needs to be incrementing j, not i.

Once you fix that line, you should be all set!

1 Like

still can’t work.
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[j].length; i++) {
console.log(product = product * arr[i][j]);

have solve it.I know why. thank you help me.:slightly_smiling_face:

1 Like

Awesome! You are very welcome. :relaxed: There are a million of these challenges… I was tempted to rush through them, but it really pays off to take your time and understand how each one works! Good luck with the next one!

1 Like