DEV Community

Discussion on: Polyfill for Array.reduce() Javascript

Collapse
 
melvdouc profile image
Melvin DOUCET • Edited

I'm sorry but it doesn't make any sense to use forEach in a polyfill as a browser that doesn't support reduce is unlikely to support forEach as well. Same thing goes for the let keyword.

if (!Array.prototype.reduce) {
Array.prototype.reduce = function(cb, acc) {
var i = 0;
if (acc === void 0) {
acc = this[0];
i = 1;

}
for (; i < this.length; i++) {
var newAcc = cb(acc, this[i], i, this);
if (newAcc === undefined)
continue;
acc = newAcc;
}
return acc;
}
};

Collapse
 
ad99526 profile image
Abhishek Dubey

Would not work for undefined acc