With due credit to @Matt who's comment points it out.
The commonest format for looping through an array is:
for(var i=0; i<array.length; i++) {
doSomethingWith(array[i];
}
Note that's a "less than" operator, not a "less than or equal to" operator.
This loop counts from 0 to array.length - 1
, because the second part of the for
statement: i < array.length
, means "keep repeating for as long as i is less than array.length.
... and that's what you want, because arrays are numbered from 0 to length-1. That is, an array of length 4 is numbered 0,1,2,3.
If you loop while i <= 4
, then the loop will execute for 0,1,2,3,4 -- and in Javascript, it will get undefined
when it references array[4]
.
Sometimes you do need "<=" in a for loop, but it's very much the exception. Any time you do use "<=", think about adding a comment to say why.