Do all the things like ++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatarSign Up
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple APILearn More
dmonkey18654yWait, why would a foreach be better than a map function? Isn't it the same? (I know barely nothing about js)
dirak1924yImproper usage of map, undescribable variable name i, mutating props when props is immutable, using delete instead of assigning to undefined.
So butt rustled by just one line of code. To me, this looks anti-code-golf, because there's just so many anti patterns stuffed into one line.
@dmonkey From MDN: The map() method creates a new array with the results of calling a provided function on every element in the calling array.
So basically, forEach will simply iterate over the array, whereas map will create a new array based on what is returned in each invocation (in the example the new array is not assigned, and the invocations all return undefined implicitly, so using map is kind of pointless)
Foreach is slower and map is more memory intensive. Decide which one is a bigger bottleneck, generally, in web stuff the memory is the smaller issue because slow load time bottlenecks the ux while memory consumption doesnt really.
@BindView This seems to tilt the argument in favor of map. However map did come out slower for me with this perftest: https://jsperf.com/map-vs-foreach-s... on Chromium.
So I guess if perf difference is marginal/variable, it semantically makes more sense to use forEach in cases where the expected result is not strictly a different representation of each of the array's entries.