# 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.

``````
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]]);

``````

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`.

Your mistake is you are assuming the minimum highest number will always be `1` with the following line:

``````var high = 1
``````

What if a sub array looks like below?

``````[-20, -30, -10, -15]
``````

The highest number is `-10`, but your function would return `1` for that particular sub array.

1 Like

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

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