When/why to use map/reduce over for loops

后端 未结 6 1177
情深已故
情深已故 2020-12-09 17:03

So I am getting into a bit of object manipulation in JavaScript for the first time and I have a question I\'m wondering if anyone could answer.

When I have an object

6条回答
  •  情深已故
    2020-12-09 17:53

    I know I'm replying to an old answer but just wanted to point out for future readers.

    Map reduce and filter functions come from the functional programming world.

    These are first class built-in operators in languages like Lisp, Haskell, and others(ml?). Functional languages tend to prefer to run operators over immutable data than make the code run over the data to operate on it (say loops). So they provide simpler but powerful interfaces like map, filter and reduce when compared to providing for and while loops.

    It also helps them satisfy other requirements like immutability etc. That's why maps give u back a new map instead of mutating the old one. These are very good from a concurrency point of view, though they may be slower in certain contexts.

    This approach usually leads to fewer errors in code in multi-threaded or high concurrency apps. When multiple actors act on the same piece of data, immutability helps keep code from stepping on each other's toes.

    Since javascript tries to be partially functional by providing some functionalities of functional programming languages, it might have made sense to implement map, filter and reduce functions in it too.

    YMMV depending on what you are doing with the tools you are given.

    If your code works better with a for loop, go for it.

    But if you ever find asynchronous code munching on common data and you end up splitting your hairs trying to debug a loop. Say hi, to map, reduce and filter.

提交回复
热议问题