Home > Programming > Easy functional programming in JavaScript with Underscore.js — part 2

Easy functional programming in JavaScript with Underscore.js — part 2

In the previous post I showed how good use of Underscore.js‘s map function can substantially increase the quality of your code. This time I’ll explore some other functional collection favourites: reduce, select and all.

Reduce that array over a low heat until thick and creamy

Have you ever had to do something like this?

Basically, this is going through some kind of list of values, calculating a new value from each one and accumulating some kind of answer. It’s a common pattern, and there’s an Underscore function for it! This is exactly what _.reduce was built for:

_.reduce takes a collection of values, a function, and a starting value. In this case, the starting value is 0 because we’re building up a running total of numbers. The function is passed the running total (which starts at 0) and each element of the collection. The return value of the function becomes the next value for the running total. _.reduce doesn’t just need to be used on numbers:

In this case, I’m reducing an array of animal objects into a single string. Of course there are plenty of ways to do the above, but this shows you the flexibility of _.reduce.

Bo Selecta!

Imagine you have an array of strings, but you want a new array of strings that start with a capital letter. You might do that like this:

Now, you won’t be surprised to learn that there’s an Underscore function for doing just that: introducing _.select!

Isn’t that much cleaner? Again, we’re abstracting away the minutiae of selecting elements from a list, and just declaring that we want the elements that start with a capital letter. Simples!

All the single ladies

Sometimes you just want to know a yes or no answer about a collection. For example, are all my ladies single?

Hell yes they are. You can read _.all as “is this statement true about all the elements in my collection?” In the same way, _.any can be read as “is this statement true about any of the elements in my collection?”

What about this?

Here’s a useful little tip. When you’re working with nested functions in an object context, you’ll find that this in the nested function doesn’t refer to the object’s context, but the global context. The standard way to deal with this is a line like that = this; or self = this;. There’s a nicer way to do this with Underscore. Nearly all the functions for working on collections take an optional context argument, which specifies what this will be inside the function. Here’s an example:

Because we’re passing the value of this to _.select, the function passed to _.select is working with the correct this. Otherwise, this.maxAge would be undefined.

Learning more

I’ve only gone into some of the functionality that Underscore offers. The docs are very approachable and clear – I urge you to go and read them.

@SamirTalwar on Twitter recommended that I show the alternative syntax for Underscore, as described in the docs. Basically, instead of doing:

_.map(collection, func);

you can do:

_(collection).map(func);

And, coupled with .chain() you can do awesome chaining things like this:

Pretty cool. Anyway, use whichever feels right to you. Enjoy!

Categories: Programming Tags: ,
  1. Rob R
    September 10th, 2012 at 14:19 | #1

    This is a great referential. Thanks for this article.

  2. June 7th, 2013 at 16:22 | #2

    Hi, just wanted to tell you, I loved this blog post. It was inspiring. Keep on posting!

  3. August 4th, 2013 at 22:11 | #3

    Hello there I am so delighted I found your blog, I really found you by error, while I was searching on Digg for something else, Anyhow I am here now and would just like to say many thanks for a incredible post and a all round exciting blog (I also love the theme/design), I don’t have time to go through it all at the moment but I have saved it and also added your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the superb work.

  4. April 19th, 2014 at 08:07 | #4

    Great article.

  5. May 14th, 2014 at 16:32 | #5

    Tom Attea, humorist and creator of has already established six shows produced Off-Broadway. There is room for several opinions, many judgements, and many insights into exactly the same piece of news.

    When performing a big project you need to have detailed discussions together with your writer either on email, telephone (Skype is great for this and freee) and see what input they have. It’s belief that about 90% with the content over a website is a bundle of articles. article hopefully ([http://tiny.cc](http://tiny.cc/c758cx “http://tiny.cc”)) Article writing jobs at home facilitates people to write articles and web contents with respect to any organization. As the outline continues, check the relevant materials available once again to make sure of the availability and sufficiency.

  6. May 14th, 2014 at 18:12 | #6

    Or it might be that your herpes diagnostic visit was below ideal. So Murdoch and his third wife, Wendi Deng’s marital status, as well as their two young daughters living conditions, had rarely seen in media reports.

    This support group can provide you with the benefit of these experience, what works well to produce quitting simpler. Don’t write what you don’t wish to happen, like *I don’t need to mess up at the office. [link](http://bit.ly/1nVvQwj9 “link”) report s not necessary should your child or you do must use these types of services because you aren. When you are looking at discussing your disability in personal statements, be cautious about listing down every one of the obstacles you might have come to face because of your respective disability.

  7. May 16th, 2014 at 06:17 | #7

    No appear your needs are, baby supply rentals on Anna Maria; offer you a wide range of things you need for your baby while vacationing. Determine the Metal Type – As mentioned, most truck bed rails are created using tubular steel.

    No appear your needs are, baby supply rentals on Anna Maria; offer you a wide range of things you need for your baby while vacationing. Determine the Metal Type – As mentioned, most truck bed rails are created using tubular steel.

    Make every make an effort to provide correct citations inside the body of your assignment whenever you employ the ideas of others.

    The main difference is always that during IELTS Writing Task 1 in General training you’ll not need to analyze diagram or table and a lot of figures. [regalo hideaway bed rail instructions](http://Larryrxd.buzznet.com/user/journal/17553635/terrific-potency-super-mantra-gayatri/ “regalo hideaway bed rail instructions”) bed rails for seniors walgreens One the opposite hand you use present tense for your generally assent facts as well as regular events.

    Copyscape, Dupecop, Viper, Duplichecker, Google Alerts, Tineye, Article Checker are some with the most vividly used tools for checking plagiarism for any form of content.

  8. May 17th, 2014 at 16:47 | #8

    I’ve been working with the examples in Functional Javascript, and this post and the previous one (“Part 1″) were helpful as well. Thanks!

  9. May 19th, 2014 at 01:32 | #9

    Consider limiting these to essentially the most important and valuable sites or else you’ll start drowning in emails. One thing you could do to boost your life is pay off your debts.

    There are many ways to access your natural wellbeing which are far more efficient than attempting to ignore your problems and convince yourself you might be happy, ‘No, really’ I AM happy’. Liddell hopes to penetrate the 2016 Summer Olympics and rise above being forced to drop out with the 2009 games due to a very painful hernia. least ([http://tiny.cc/](http://tiny.cc/ef68cx “http://tiny.cc/”)) source Focus about what you need to offer a prospective employer; don’t focus on you.

    When you are doing this back it again by your 100% guarantee showing them they have nothing to loose by buying your products and everything to get.

  10. May 19th, 2014 at 01:35 | #10

    t any serious side effects associated while using vaccine, which ought to be encouraging for men who are worried about adverse reactions. The publisher may limit what might be viewed for free and could charge a membership fee for that reader to look in the entire article.

    This is caused by the fact that in many instances it is not your thinking and ideas that you simply are wanting to convey via your writing.

    If I am portion of a minority on this aspect, why did so many people buy ‘Eats, Shoots & Leaves’ it became Book with the Year. [report](http://tiny.cc/s458cx “report”) here When guests at the hotel check out over a happy note, make certain to offer them a card which has a link for the review page of the site or Tripadvisor profile. These mistakes tend to be spelling mistakes, grammatical mistakes, typographical mistakes or semantic errors.

  11. May 19th, 2014 at 16:44 | #11

    Adipex is one such brand broadly renowned for offering good results. Also there some side effects of this drug and one needs to be cautious about the side effects.

    You alone include the authority for what’s true about your projects, however, you’d like feedback on clarity, tone, etc technical matters as spelling and punctuation. Write about topics which make reference to the present demands and needs of one’s readers. While ([Tr.Im](http://tr.im/59cx7 “Tr.Im”)) gnc ripped vitapak Remember ‘ your online presence must speak in your ‘onlyness. We know that for past 5 years use of Internet & its related resources have become up a lot more than 5 times.

  12. June 7th, 2014 at 13:31 | #12

    Wow, marvelous blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your site is magnificent, as well as the content!

  13. June 12th, 2014 at 09:02 | #13

    motorola cordless phone batteries

  14. June 12th, 2014 at 10:57 | #14

    in cream pie

  15. July 16th, 2014 at 15:16 | #15

    Our recommendation is to restaurant chairs miami florida purchase. This would allow the people interested, and family. So we got to try many new things that you want me to another.

  1. July 31st, 2011 at 03:01 | #1
  2. August 18th, 2011 at 14:29 | #2
  3. May 11th, 2014 at 12:57 | #3
  4. May 12th, 2014 at 03:05 | #4
  5. May 12th, 2014 at 03:22 | #5
  6. May 13th, 2014 at 05:15 | #6
  7. May 15th, 2014 at 04:56 | #7
  8. May 16th, 2014 at 06:32 | #8
  9. May 19th, 2014 at 03:30 | #9
  10. May 27th, 2014 at 08:07 | #10
  11. September 23rd, 2014 at 07:59 | #11

Comments parsed as Markdown.