Learning pains: Nesting For Loops

Tell us what’s happening:
Hi all,
I am not sure what I am doing wrong but this is an attempt to use a nested for loop. As you can see in my code below, once ending the “return product;” I receive an error message of “TypeError: unknown: Cannot read property ‘0’ of undefined”

Sorry for the newb question, but if anyone can explain what I doing wrong or point me in the right direction to read more about the issue, I would greatly appreciate. All the other forum post seem to differ from my exact scenario.

Your code so far


function multiplyAll(arr) {
  var product = 1;
  // Only change code below this line
  for (var p = 0; p < arr.length; p++); {
    for(var q = 0; q < arr[p].length; q++) {
      product = product * arr[p][q];
    }
  }
  // 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/71.0.3578.98 Safari/537.36.

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

I may be wrong but this looks like a scope issue. Read Kyle Simpon’s YDKJS Scopes & Closures.

1 Like
for (var p = 0; p < arr.length; p++); {

on that line you have a semicolon where there shouldnt be
everything else is fine

2 Likes

Thank you @alkapwn3d ! Your suggestion worked like a charm. Much respect!


function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for (var p = 0; p < arr.length;p++) {
for (var q = 0; q<arr[p].length; q++)
product = product * arr[p][q];
}

// Only change code above this line
return product;
}

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

I didn’t even see that extra semicolon. Huh.

1 Like