Array Out of Bounds: Comparison with undefined, or length check?
You can also write:
if (index in array) {
which will return true even if array[index]
is set to undefined
.
Do not test for undefined. You should use the length of the array. There are cases where it simply does not work to test for undefined because undefined is a legal value for legitimate array entry. Here's a legal JS array:
var legalArray = [4, undefined, "foo"];
And you can access it like this:
var legalArray = [4, undefined, "foo"];
var result = "";
for (var i = 0; i < legalArray.length; i++) {
result += legalArray[i] + "<br>";
}
$("#result").html(result);
Generates this output:
4
undefined
foo
As seen in this jsFiddle: http://jsfiddle.net/jfriend00/J5PPe/
The only correct way is to check the index vs. the length.
An element may be assigned the value undefined
. It is just silly to use it for a sentinel here. (There may be other, valid and possibly overlapping, reasons for checking for undefined, but not "for an out of bound check" -- the code in the other question will present arguably wrong results when the value of the given arg is really undefined
.)
Happy coding.