While reading a tutorial, I came across a code snippet for a forEach
function that all made sense except for the part where it checks if i
is in the array:
if (i in this) {
I'm confused as to why this check is necessary since we already have a stop condition in the for loop.
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(fun /*, thisp*/) {
var len = this.length >>> 0;
if (typeof fun != "function") {
throw new TypeError();
}
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this) {
fun.call(thisp, this[i], i, this);
}
}
};
}