What is TypeError?

Why does this give me a " TypeError: Cannot read properties of undefined (reading ‘length’) " error?

function multiplyAll(arr) {

  var product = 1;

  // Only change code below this line

  for(var i=arr.length;i>=0;i--){

    for(var j=arr[i].length;j>=0;j--){

      product=product*arr[i][j];

    }

  }

  // Only change code above this line

  return product;

}

but not this one?

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;j++){

      product=product*arr[i][j];

    }

  }

  // Only change code above this line

  return product;

}

Zero based indexing means there is never an arr[arr.length] element.

Could you please elaborate further? since the second code still uses arr[arr.length]

You never actually use arr.length as an index here though.

const arr = [0, 1, 2, 3, 4, 5];

This array has length 6, but there is no arr[6].

2 Likes

Thank you! i replaced arr.length with (arr.length-1) and it worked.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.