I’m trying to decide whether to use the reduce() method in Javascript for a function I need to write which is something like this
var x = [some array], y = {};
for (...) {
someOperation(x[i]);
y[x[i]] = "some other value";
}
Now this can obviously be written as a reduce() function in the following manner:
x.reduce(function(prev, current, index, arr) {
someOperation(current);
prev[current] = "some other value";
return prev;
}, {})
Or something like that. Is there any performance or other difference between the two? Or some other reason (like browser support, for instance) due to which one should be favoured over the other in a web programming environment? Thanks.
Even though I prefer these operations (reduce, map, filter, etc.), it’s still not feasible to use them because of certain browsers that do not support them in their implementations. Sure, you can “patch” it by extending the
Arrayprototype, but that’s opening a can of worms too.I don’t think there’s anything inherently wrong with these functions, and I think they make for better code, but for now it’s best not to use them. Once a higher percentage of the population uses a browser that supports these functions I think they’ll be fair game.
As far as performance, these will probably be slower than hand written for loops because of the overhead from function calls.