When working with JavaScript arrays, it's important to note that arrays can have gaps in their indices, which should not be confused with elements that are simply undefined
:
var a = new Array(1), i;
a.push(1, undefined);
for (i = 0; i < a.length; i++) {
if (i in a) {
console.log("set with " + a[i]);
} else {
console.log("not set");
}
}
// logs:
// not set
// set with 1
// set with undefined
Since these gaps can affect the length property of the array, some may argue that they should be avoided whenever possible. However, I believe they can be treated as edge cases and only handled when necessary:
// default:
function head(xs) {
return xs[0];
}
// only when necessary:
function gapSafeHead(xs) {
var i;
for (i = 0; i < xs.length; i++) {
if (i in xs) {
return xs[i];
}
}
}
One advantage of using the concise head
function is that it can be applied to all array-like data types. While head
is just one simple example, if dealing with these gaps becomes a common occurrence in the code, the overhead should be minimal.