5 ms·
A for loop is an imperative construct and can be used to do literally anything. One has to read on into the body of the loop to understand what's going on. Wors
by globular-toast 6y ago
A for loop is an imperative construct and can be used to do literally anything. One has to read on into the body of the loop to understand what's going on. Worse, there could be a bug and now you have no idea what the programmer intended. Array.map, on the other hand, only does one thing: turns an array into another array. The intention is clear. It makes a program much easier to understand.
- jjnoakes 6y agoIn javascript, what prevents the body of the map function from doing arbitrary stuff? Don't you have to read that to know for sure, just like a for loop? In some languages the map function may be restricted to not have side effects, in which case I'd agree, but not javascript, correct?
- globular-toast 6y agoYou can't stop bad programmers doing bad stuff. It's not about that. It's about communicating intention. Code as documentation.
- lanstin 6y agoThere is nothing more clear than code as a way to communicate, at least for me. My writing in English obviously could be better but easier just to show what I mean.
- django77 6y agoThis is correct, but there are some guarantees such as the result will be an array of the same length, mapping function will be called for each element, function itself can be more easily tested in isolation and there are no imperative constructs (creating accumulator array outside of the scope, tracking the index, pushing to the accumulator array) This lends itself very nicely to functional programming (especially with typescript IMHO)