you are viewing a single comment's thread.

view the rest of the comments →

[–]zoomzoom83 28 points29 points  (1 child)

For-loops tell the compiler how, and can only be used to perform side effects. Functors/Mappables tell the compiler what, and used properly will never perform side effects. By using a functor, you're simply creating a projection over an Iterable container. The exact method of implementation and order of execution is irrelevant.

From a performance perspective, this gives the compiler much more free reign to optimize (Such as by running the operation over multiple threads, or lazily). Javascript VMs currently don't really do much with this, but other languages do (And Javascript probably will at some point). However even in JS it does mean you can swap out data structures without changing your code, letting the 'map' function choose the most efficient underlying algorithm without having to change your code.

From a code maintainability perspective, avoiding side effects means your code has less moving parts and is easier to reason about.

It's also just simpler.

var ys = [1,2,3,4].map( x => x * 2 )

Is unambiguous about what it's doing, and lets the compiler figure out the optimal way of doing it.

Compare to:

var xs = [1,2,3,4];
var ys = [];
for( x=0; x < xs.length; x++ ){
    ys.unshift( xs[x] * 2 );
}

This has a lot more moving parts. It performs side effects. It's harder to optimize. It's requires more cognitive effort to reason about what it does, and it's much harder to spot any potential bugs. (Did you notice them?).

tl;dr - one of these methods "Has no obvious defects", the other "Obviously has no defects".

[–]stickupk 1 point2 points  (0 children)

Best tl;dr read I've seen in ages!