In chapter 6, on page 230, it is said that when you, intentionally, want to create a sparsely populated arrays it is best to be explicit about it in the following way:
var myList = [1, undefined, 3, undefined, 5];
However, this leads to a problem when using an if in condition in a for loop, like so:
for (var i = 0, count = myList.length; i < count; i++) {
if (i in myList) {
console.log(myList[i]);
}
}
Under normal circumstances, in a sparsely populated array, this would lead to only the defined elements (1, 3 and 5) outputting to the console. But when explicitely using undefined to create these "holes", it leads to the entire list, including undefined elements being outputted.
Full example:
var myList = [1, undefined, 3, undefined, 5];
for (var i = 0, count = myList.length; i < count; i++) {
if (i in myList) {
console.log(myList[i]);
}
}
1
undefined
3
undefined
5
This, however, does work:
var myList = [1, , 3, , 5];
for (var i = 0, count = myList.length; i < count; i++) {
if (i in myList) {
console.log(myList[i]);
}
}
1
3
5