Return Largest Numbers in Arrays - Cannot read property 'length' of undefined

Tell us what’s happening:
Receive an error: “Cannot read property ‘length’ of undefined” when I try to run.

Your code so far


function largestOfFour(arr) {
  var hiarr = []
 for (var i = 0; i <= arr.length; i++ ){
      var high = 1
    for(var a = 0; a <= arr[i].length; a++){
        
        if(arr[i][a] > high){
          high = arr[i][a];

        }
        if(a == arr[i].length){
          hiarr.push(high);
        } 
    }
 }
return hiarr;
 // return arr;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) 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-algorithm-scripting/return-largest-numbers-in-arrays

Hi.
The error is in the first for loop.

the issue is that when you go to do arr[arr.length].length, arr[arr.length] is undefined because arrays are 0-indexed and so first item is at 0, so last item is at one less than arr.length

and undefined doesn’t have a length

1 Like

As @BalintTiborHun points out, there is a logic error in first for loop declaration but even if you fix that, there is another logic error in the second for loop declaration. Also, there is the error that I pointed out, plus there is another error in the following, because if you fix the first two errors, a will never be equal to arr[i].length, plus you need to think about where/when in your code you should be pushing high to hiarr. The current location (never mind the incorrect logic of the if statement) is not the right place.

2 Likes

@camperextraordinaire @ilenia @BalintTiborHun Managed to get it working now, thanks for all your help guys!