2

I see a lot of React devs (ab)using the array.map function in cases where a forEach would be more suitable (e.g. without assigning the result, and without return statements). What are your thoughts on this?

Comments
  • 1
    Wait, why would a foreach be better than a map function? Isn't it the same? (I know barely nothing about js)
  • 2
    Improper 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.
  • 2
    @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)
  • 1
    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.
  • 0
    @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.
Your Job Suck?
Get a Better Job
Add Comment