I have tweaked a Javascript Ninja book's code example (listing 6.9) a bit to make it even shorter. This code snippet is about adding a forEach method to Array.prototype (I renamed it fooEach to avoid confusion). Now the question: Why do we need to pass (context || null) as the first parameter (null in the code example)? Function.call method has its first argument -- the context -- optional, so why is it a must to pass the context as the first parameter in this case?
if (!Array.prototype.fooEach) {
Array.prototype.fooEach = function(callback, context) {
for (var i = 0; i < this.length; i++) {
callback.call(context || null, this[i], i, this);
}
};
}
["a", "b", "c"].fooEach(function(value, index, array) {
console.log(value + " is in position " + index + " out of " + (array.length - 1));
});