Why is my "<=" in a for loop throwing an exception?

Why is my "<=" in a for loop throwing an exception?
0.0 0


I just finished the Return Largest Numbers in Arrays challenge in the Basic Algorithm Scripting, but I was stuck on it for a long time. My code seemed right, but I kept getting this error: “TypeError: Cannot read property ‘0’ of undefined.” Turns out I mistakenly used a “<=” instead of a “<” in my first for loop. Once I changed that, the code executed perfectly. But I’m left wondering why it was a problem at all. Sure, it was a logical error, but why was the code getting hung up there? Can someone clear this up for me? I’ve attached my (incorrect) code below.

function largestOfFour(arr) {
// You can do this!
var newArr = [];
for(var i = 0; i<= arr.length; i++) { //this is the offending line
var biggest = arr[i][0];
for(var j = 1; j<=arr.length; j++){
if (arr[i][j] > biggest){
biggest = arr[i][j];
newArr[i] = biggest;
return newArr;


Because in the last iteration i = 4, so arr[4] is undefined, because there is not a 5th element in arr. undefined does not have any properties or methods, so when you write [0], JavaScript looks for a property on undefined and since undefined does not have a property named “0”, you get this Type error. The [] notation is used on arrays and objects and since undefined is neither of these, the error is thrown.