Friday, July 10, 2009

JavaScript Expression Closures and Why They Rock

JavaScript expression closures (new for JS 1.7 but syntactically even cleaner in 1.8) are one of those things that seem very so-what the first time you hear about it, but leaves you slapping your forehead and saying "OMG this is so darn freakin' cool" repeatedly after you start using it. Why? Because OMG. It's so darn freakin' cool.

The basic notion is that instead of writing short utility functions (which I have a million of) as, for example
function square( x ) {
return x * x;
you just write
function square( x ) x * x
which (yes yes, I know) looks very so-what, but bear with me for a moment. The short syntax starts to become more compelling when you begin using it in anonymous functions, particularly callback functions (which, as you know, tend to be anonymous a great deal of the time). For example, suppose you have a custom comparator for the sort() method of Array:

function descending( a,b) {
return b > a;

[5,1,3,2,4].sort(descending); // [5,4,3,2,1]

You can instead write it as:
[5,1,3,2,4].sort( function(a,b) b > a );
Another fairly trivial example: Suppose you want a function that will constrain strings to a certain length. You can do something like:
function limit(s, n) s.length > n ? s.substring(0,n): s
As a more elaborate example, suppose you have the following code, designed to convert a "camelCase" string to underscore_format.
function underscore( str ) {

function toUnderscore( s ) {
return '_' + s.toLowerCase();

return str.replace(/[A-Z]/g, toUnderscore );

// underscore( "aName") --> "a_name"

With the new closure syntax, you can do:
function underscore( str )
str.replace( /[A-Z]/g,
function(s) '_' + s.toLowerCase() );
Here I've converted not only the outer function, but also the callback to replace(), to expression-closure form. (I split it into 3 lines for readability, but it will still execute correctly as a 3-liner. You don't have to write these things as one-liners.)

Still not convinced? Try using this syntax (supported in Firefox 3+, and anywhere else JS 1.7 or 1.8 are implemented) in some functions yourself, and see if your code doesn't become easier to write, shorter, and (in most cases) more readable. It may be only a small improvement on the more verbose older syntax, but an improvement is an improvement. I'll take it.


  1. I might be confused, but it seems that the only difference between the lambda functions and the expression closures is the lack of brackets and an implied return() statement. Is there something else that I am missing?

    I find the expression closure to be less readable as it lacks the visual delimiters of the anonymous functions.

    1. Great Article android based projects

      Java Training in Chennai Project Center in Chennai Java Training in Chennai projects for cse The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training Project Centers in Chennai

  2. @Ben
    I'm tired of people making readability arguments about any reduction/change in syntax. What they really mean is, "that's different and unfamilliar, I'm scared."

    It's like complaining that Spanish is a less readable language because of verb conjugation. If you don't know Spanish well, that might be true, but if you do know Spanish, you realize that it is both shorter and more efficient, as well as less ambiguous than English.

    Give yourself a chance to get used to the new syntax and you'll realize that the delimiters and return statement are unnecessary cruft. Your eyes will learn to recognize expression closures by the rules: function (without a {) and a single line. Easy.

    @Kas, if you indented that last code snippet a little better, it might seem more readable.

  3. To Ben: Well, in spite of the apparent lack of readability (which is true, but honestly depends on the way you write and indent your code) closures are very useful to define value of callback parameter. No the only purpose but one on the main interest to me.

  4. Nice. But you're exaggerating the benefit somewhat. In the old syntax you don't need a separate named function, you can just do this:

    [5,1,3,2,4].sort(function(a,b){return b > a;});

    Which is basically the same thing, but in my opinion actually less readable.

  5. Anonymous8:16 PM

    to me it looks like lazy programming, if your 100% you'll never need that function again your probably wrong. Then what refactoring later.

  6. I think the term "expression closure" will just make it confusing for something that's just a lambda, people have a hard time understanding these concepts, and if we start mixing up names we have no hope

  7. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. JavaScript Training in Chennai

  8. Our Web Designing Course and other IT Training Programs give professionals the opportunity to attend our open- sourced academic courses on the go which ultimately helps them build the skills and knowledge they need to reach their professional goals.

    WordPress Training
    Web Designing Course in Delhi
    SEO Course
    Digital Marketing Training in Delhi
    SMO Training
    PPC Institute in Delhi
    Joomla Course in Delhi
    JQuery Institute in Delhi
    JavaScript Course

  9. Its a wonderful post and very helpful, thanks for all this information.
    Javascript Training in Delhi

  10. Its a wonderful post and very helpful, thanks for all this information.
    Javascript Training institute in Noida

  11. nice post...
    visit here:

  12. Really Nice Post & thanks for sharing. Please keep up the good work.
    Oflox Is The Best Digital Marketing Company In Dehradun Or Website Design Company In Dehradun

  13. This is also a very good post which un careers I really enjoyed reading. evden eve taşımacılık It is not everyday that I have the possibility to see something like this jobs in usa

  14. Thanks for all the tips mentioned in this article! it’s always good to read things you have heard before and are implementing, but from a different perspective, always pick up some extra bits of information very nice… i really like your blog…CheapWays Digital Marketing Company in Nagpur

  15. Awesome article with excellent information found very useful waiting for next blog thank you.
    typeerror nonetype object is not subscriptable

  16. We provide valuable & economical digital solutions for the customers in areas such as website designing, development & maintenance, graphic designing, digital marketing and mobile applications development. Codeaxia provides best solutions for -
    Ecommerce Web Development
    SEO Services
    Social Media Marketing

  17. Nice Information Your first-class knowledge of this great job can become a suitable foundation for these people. I did some research on the subject and found that almost everyone will agree with your blog.
    Cyber Security Course in Bangalore

  18. Writing in style and getting good compliments on the article is hard enough, to be honest, but you did it so calmly and with such a great feeling and got the job done. This item is owned with style and I give it a nice compliment. Better!
    Cyber Security Training in Bangalore

  19. I will very much appreciate the writer's choice for choosing this excellent article suitable for my topic. Here is a detailed description of the topic of the article that helped me the most.
    unindent does not match any outer indentation level

  20. I'm glad I found this blog! Occasionally, students want to know the keys to writing productive literary essays. Your first-class knowledge of this great job can become a suitable foundation for these people. Good
    unindent does not match any outer indentation level python

  21. We have a wide range of Warehouse Space, Logistic Centers, warehouse, Godown, Cold Storage for sale/rent in Delhi, Mumbai, Bhiwandi, Chennai, Hyderabad and all other major cities in India.
    warehouse in india
    warehouse in mumbai
    warehouse in delhi

  22. Top quality blog with unique content and information shared was valuable looking forward for next updated thank you
    Ethical Hacking Course in Bangalore

  23. I was very happy to find this site. I really enjoyed reading this article today and think it might be one of the best articles I have read so far. I wanted to thank you for this excellent reading !! I really enjoy every part and have bookmarked you to see the new things you post. Well done for this excellent article. Please keep this work of the same quality.
    Data Science Course in Bangalore

  24. This post is really one of the impressive posts, thanks for providing this useful information to us. Wishing you good luck with upcoming posts.

    Digital Marketing Services

  25. I really enjoy every part and have bookmarked you to see the new things you post. Well done for this excellent article. Please keep this work of the same quality.
    Artificial Intelligence course in Chennai

  26. So you can save your lot of time by hiring SEO Freelancer or if you want to learn full SEO Course Delhi

  27. Thank a lot. You have done excellent job. I enjoyed your blog . Nice efforts
    Cyber Security Course in Bangalore

  28. Nice Blog and i would like to thank for the efforts you have made in writing this post, hoping the same best work from you in the future as well. Thanks for sharing. Great websites!
    Tableau Training in Bangalore

  29. Such a very useful article and very interesting to read this article, i would like to thank you for the efforts you had made for writing this awesome article. Thank you!
    Python Training in Bangalore

  30. digital marketing agency that knows the art of creating your digital presence hub kreatives is a new-age digital marketing services in delhi.

  31. Post writing is also a fun, if you be familiar with afterward you can write or else it is difficult to write.

    SEO company in Pune

  32. Thank you for the useful information which you shared throughout your blog. I appreciate the way you shared the relevant, precious, and perfect information. Furthermore, I would like to share some information about Peergrowth. Peergrowth is one of the top recruitment firms in Uae, to know more about the services, just visit the website and take complete information about Peergrowth. I hope, you will get immediate assistance and the right information through the website.

  33. Hey There. I discovered your weblog using
    msn. This is a really neatly written article. I’ll make sure to bookmark
    it and return to read extra of your useful info. Thank
    you for the post. I’ll definitely comeback.
    best skin doctor in east delhi
    skin specialists in east delhi

  34. This is a great article with lots of informative resources.Very Nice written.all the points should be noted. it is worth reading.also UpSurge Services is one of those unique digital marketing providers in Pune which blends creativity with feasibility.We understand your needs like ours, & our digital experts are dedicated to developing the most effective marketing strategy & its execution to get your marketing and business goals. We are offering a plenty of services like SEO, SEM, SMM, Complete Digital Marketing, Website Design and Development, Domain Registration, Web Hosting, E – Commerce Solutions, Logo,Broucher Design, and other IT related projects.

    Website development Company in Pune
    social media marketing company in Pune
    Digital marketing company in Pune

  35. For mounting your light strips, you can cover them with aluminum extrusions. These extrusions can be used to create various light effects.
    Use LED light strip controllers to control the color temperature and brightness or make a light show using the LED light-strip controllers

  36. The most common led diy project for many hudsbands is lighting a staircase. It doesn't matter if your staircase is made of glass or metal. A well-lit staircase will make it look more grand. The LED light strips are compact, safe, and very flexible. These light strips are easy to install, so you don't need professional help to place lighting in your staircase.

  37. Recessed wall lighting

    The LED light strips can be seen through a wall hollow with recessed lighting. This type of lighting can give your space a soft and diffused feel. Recessed lighting can be used in offices, homes, and commercial spaces to give your space an elegant look.

    Recessed wall lighting in modern living rooms
    Warm lighting from LED strip with base for kitchen
    Surface Mounted Wall Lighting
    More info

  38. The #1 online furniture shopping in North East. Discover a large selection of products by top brands ✔ Low Prices ✔ Big Discounts ✔ Fast Shipping ✔ Genuine Brand, beds, sofas, bed room, lighting, accessories, living room, mirrors, dining, seatings and pictures. For more information's and details to visit us:


Add a comment. Registration required because trolls.