Nesting For Loops - "i is not defined" (but I think it is!)

I have run into an odd problem. Below is my solution for “Nesting For Loops”. It keeps coming back as “i is not defined”.

Here’s the kicker though, I have tried it within other javascript sandboxes and it comes out fine. It gives me the product number I expect.

So my question is, is there a flaw in my code that I am missing or could this be an error on FreeCodeCamps end?


function multiplyAll(arr) {
  var product = 1;

  for(i=0; i <arr.length; i++){
    for(j=0; j < arr[i].length; j++){
      product *= arr[i][j];
    }
  }
  
  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 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36.

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

The example code in the challenge looks like this:

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

Notice the word ‘var’ there? Try it and see if that helps.

1 Like

Thanks that worked. Looks like I could have technically declared “i” without using “var” but it looks like thats not best practice. Risks making i a global variable.

1 Like