It seems a little weird at first, and I still hit the docs for methods like reduce above. Knowing they exist, and a flat refusal to use for loops is my primary weapon. The above methods are really just scratching the surface. The underscorejs library is filled with awesome utilities like this that can be combined together to create new and wonderful things.

The 30 day no-loop challenge

Stop.

For the next 30 days, don’t write any for loops. If you see a nasty pile of those gnarly things, replace them with an each or a map. Do a little reducing. And let me know how it goes!

Beware. Underscore is the gateway to functional programming. What has been seen, can’t be unseen. In a good way!

If you’re wanting to dig a little deeper, you should jump over to this tutorial on functional programming in javascript. It’s great and only takes about ½ hour to work through. It is “how the sausage is made” fundamentals for the underscore functions I used above. Lot’s of wholesome nerd fun!

note: As a more performant alternative to underscore, you might check out lodash

note: it should also be noted that modern browsers support the above methods natively. Array.forEach, Array.reduce, and Array.map exist, but to use them you likely need to create shims to fallback for cases when they don’t exist. For me, having the consistent underscore (lodash) API is much more convenient. YMMV

note: Yes, for loops are faster. I optimize for readability and ease of use for my team before squeezing performance out of CPUs. I don’t write games, or rich animated consumer experiences. Big projects, 10s of developers, code that already trends towards sprawling and messy.

The “clean readable code” optimization pays huge dividends, even if it comes at the cost of (very) marginal performance hits.

Now, if we are doing a big list of items in Angular, we focus on performance in terms of CPU, but even then, the only time we hit a wall with an unoptimized datagrid was on last-gen Android phones.