I was playing around with this array reduce polyfill and I'm just confused why is he/she using apply. I know that apply adds this context in the execution. But I don't know why we need it here, I just tried without it, and it works fine too.
Array.prototype.reduce = function (cb, initialValue) {
console.log('inside my reducer');
if (!cb || typeof cb !== 'function') throw TypeError();
var len = this.length;
var i = 0;
console.log('this', this);
if (typeof initialValue === 'undefined' || initialValue === null) {
initialValue = this[0];
++i;
}
for (; i < len; i++) {
initialValue = cb.apply(this, [initialValue, this[i], i, this]);
//comment the line above and uncomment this line and it will work fine
//initialValue = cb(initialValue, this[i]);
}
return initialValue;
};
[1, 2, 1, 1].reduce((a, b) => a + b, 0); => 5
So, I'm a little confused, if anyone could share some insights it'll be apreciated. Thanks!
Wherever you got that polyfill, it's incorrect, in a couple of ways but in particular that initialValue = cb.apply(this, [initialValue, this[i], i, this]); should be using undefined, not this, in the first argument. reduce always calls its callback with this set to undefined (it'll end up being the global object if the callback is in loose mode rather than strict mode). So either initialValue = cb.apply(undefined, [initialValue, this[i], i, this]); or (more directly) initialValue = cb(initialValue, this[i], i, this);
Separately, it makes no sense to use apply and create an array to provide to it rather than using call with the discrete values it already has. Also, continuing to use something called initialValue for the accumulator is, at best, misleading. And it doesn't handle it correctly if you do [].reduce(x => x) (it should throw an error, not return undefined [note no seed value]).
So basically, I wouldn't put much faith in that polyfill, since it's providing the array, rather than undefined, as this during callbacks.