-1

I'm trying to make the simple code below works, but always got the following error: TypeError: cannot read property 'length' of undefined.

function multiplyAll(arr) {


     var product = 1;

      if (arr === undefined) {
        return "Undefined Array!";
      } else {


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


     }
    }


    multiplyAll([[7,2],[6,4],[5,8,9]]);

What is the problem?

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272

1 Answers1

4

This appears to be a copy&paste/typo error:

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

In the inner for loop, you're incrementing i instead of j. You're going off the end of the array, making arr[i] undefined.

You could have solved this by monitoring the values of i and j using a debugger or calls to console.log. You would have noticed that i was incrementing too fast, while j remained at 0.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117