this seems to be a common javascript idiom:
function foo (array, index) {
if (typeof array[index] == \'undefined\')
alert (\'out of bounds baby\'
It's not common as far as I know, much more common is:
for (var i=0, iLen=array.length; i
You should not compare to undefined, since a member of the array may have been assigned a value of undefined
, or may not have been assigned any value.
e.g.
var a = [0,,,,];
alert(a.length); // 4 (or 5 in buggy IE);
a[1] === undefined; // true but not out of bounds
The main reason for using a for loop is that array properties may not be returned in numeric order if a for..in loop is used.
A for..in loop is much more efficient in sparse arrays but the possible out-of-order access must be dealt with if it matters (as must inherited and non-numeric enumerable properties if they should be avoided).