wingolog

es6 generator and array comprehensions in spidermonkey

7 March 2014 9:11 PM (es6 | igalia | spidermonkey | firefox | bloomberg | compilers | javascript | generators)

Good news, everyone: ES6 generator and array comprehensions just landed in SpiderMonkey!

Let's take a quick look at what comprehensions are, then talk about what just landed in SpiderMonkey and when you'll see it in a Firefox release. Thanks to Bloomberg for sponsoring this work.

comprendes, mendes

Comprehensions are syntactic sugar for iteration. Unlike for-of, which processes its body for side effects, an array comprehension processes its body for its values, collecting them into a new array. Like this:

// Before (by hand)
var foo = (function(){
             var result = [];
             for (var x of y)
               result.push(x*x);
             return result;
           })();

// Before (assuming y has a map() method)
var foo = y.map(function(x) { return x*x });

// After
var foo = [for (x of y) x*x];

As you can see, array comprehensions are quite handy. They're expressions, not statements, and so their result can be passed directly to whatever code needs it. This can make your program more clear, because you aren't forced to give names to intermediate values, like result. At the same time, they work on any iterable, so you can use them on more kinds of data than just arrays. Because array comprehensions don't make a new closure, you can access arguments and this and even yield from within the comprehension tail.

Generator comprehensions are also nifty, but for a different reason. Let's look at an example first:

// Before
var bar = (function*(){ for (var x of y) yield x })();

// After
var bar = (for (x of y) x);

As you can see the syntactic win here isn't that much, compared to just writing out the function* and invoking it. The real advantage of generator comprehensions is their similarity to array comprehensions, and that often you can replace an array comprehension by a generator comprehension. That way you never need to build the complete list of values in memory -- you get laziness for free, just by swapping out those square brackets for the comforting warmth of parentheses.

Both kinds of comprehension can contain multiple levels of iteration, with embedded conditionals as you like. You can do [for (x of y) for (z of x) if (z % 2) z + 1] and all kinds of related niftiness. Comprehensions are almost always more concise than map and filter, with the added advantage that they are usually more efficient.

what happened

SpiderMonkey has had comprehensions for a while now, but only as a non-standard language extension you have to opt into. Now that comprehensions are in the draft ES6 specification, we can expose them to the web as a whole, by default.

Of course, the comprehensions that ES6 specified aren't quite the same as the ones that were in SM. The obvious difference is that SM's legacy comprehensions were written the other way around: [x for (x of y)] instead of the new [for (x of y) x]. There were also a number of other minor differences, which I'll list here for posterity:

  • ES6 comprehensions create one scope per "for" node -- not one for the comprehension as a whole.

  • ES6 comprehensions can have multiple "if" components, which may be followed by other "for" or "if" components.

  • ES6 comprehensions should make a fresh binding on each iteration of a "for", although Firefox currently doesn't do this (bug 449811). Incidentally, for-of in Firefox has this same problem.

  • ES6 comprehensions only do for-of iteration, not for-in iteration.

  • ES6 generator comprehensions always need parentheses around them. (The parentheses were optional in some cases for SM's old generator comprehensions.

  • ES6 generator comprehensions are ES6 generators (returning {value, done} objects), not legacy generators (StopIteration).

I should note in particular that the harmony wiki is out of date, as the feature has moved into the spec proper: array comprehensions, generator comprehensions.

For another fine article on ES6 generators, check out Ariya Hidayat's piece on comprehensions from about a year ago.

So, ES6 comprehensions just landed in SpiderMonkey today, which means it should be part of Firefox 30, which should reach "beta" in April and become a stable release in June. You can try it out tomorrow if you use a nightly build, provided it doesn't cause some crazy breakage tonight. As of this writing, Firefox will be the first browser to ship ES6 array and generator comprehensions.

colophon

I had a Monday of despair: hacking at random on something that didn't solve my problem. But I had a Tuesday morning of pleasure, when I realized that my Monday's flounderings could be cooked into a delicious mid-week bisque; the hack was obvious and small and would benefit the web as a whole. (Wednesday was for polish and Thursday on another bug, and Friday on a wild parser-to-OSR-to-assembly-and-back nailbiter; but in the end all is swell.)

Thanks again to Bloomberg for this opportunity to build out the web platform, and to Mozilla for their quality browser wares (and even better community of hackers).

This has been an Igalia joint. Until next time!

34 responses

  1. Arne Babenhauserheide says:

    The generators are actually nice to read - I did not expect that.

    It looks like Javascript is actually growing up to become a somewhat readable language. Thanks for your work on this!

  2. Brendan Eich says:

    Hi Andy, thanks for all the great work.

    Quick note to say that the "legacy" in SpiderMonkey was all proposed for ES4, so standards track, back in the day. It was in turn based on Python 2.5 (but we avoided GeneratorExit).

    Lots of water under the bridge, but I do not believe we would have this stuff in ES6 without a bunch of us old-timers carrying water in those days.

    Maybe via some other path? Who knows. What's certain is that you did the essential ES6 implementation work, so thanks again!

    /be

  3. Brendan Eich says:

    Forgot to credit Dave Herman for turning the Pythonic RTL

    x for x in y

    around to read LTR:

    for (x of y) x

    in ES6. Good change!

    /be

  4. tomás zerolo says:

    Hi, Andy

    thanks for your blog. Here's one tentative nitpick in return. Shouldn't

    // Before
    var bar = (function*(){ for (var x of y) yield y })();
    
    // After
    var bar = (for (x of y) y);
    

    rather be

    ... yield x ...

    respectively?

    As someone not much accustomed to Javascript syntax, this tripped me up at first.

  5. Brandon says:

    Thanks, Andy: "comforting warmth of parenthesis" is now my phrase for the week. I enjoyed a hearty chuckle over that -- good-naturedly, I assure you.

  6. wingo says:

    Thanks for the note, tomás; fixed.

  7. Taxation Case Solution says:

    Taxation Case Studies Solution and Analysis, Taxation Case Studies Solutions, Custom solved according to your need.

  8. Comcast Corporation Case Solution says:

    I am profoundly pulled in by your post. It is truly a decent and useful one. I will prescribe it to my companions.

  9. Jack Fernando says:

    Very nice post. Thanks for sharing it.

    If you are facing problems with your Email, contact us anytime for getting immediate resolution for their Ymail issues at our Yahoo contact support phone number UK. On getting trapped with any unexpected error that creates issue in smooth login into gmail account, a customer can get help on just a quick call at Gmail customer support contact helpline number UK. All sort of mailing issues are fixed in the minimum possible time.

  10. write my essay today says:

    ES6 generator understandings dependably require enclosures around them. The brackets were discretionary sometimes for SM's old generator understandings.

  11. Mark Steve says:

    Very nice post. Thanks for sharing it.

  12. merry christmas 2016 images says:
  13. raees says:

    Eager to know about upcoming movie raees

    click
    Raees Release Date
    raees Story
    Raees Cast
    Raees Actress

  14. Indian Flag Picturers Download says:

    It is a horizontal tricolour in equal proportion of deep saffron at the top, white in the middle and green at the bottom. The ratio of the width to the length of the flag is 2:3. At the centre of the white band is a wheel with 24 spokes in navy blue colour that indicates the Dharma ChakraIndian FlagIndian FlagsIndian Flag Images

  15. new year wishes says:

    thanks for sharing with us

  16. www.gmail.com says:
  17. Consultant seo says:

    Very very good job this article is great

  18. YO YO says:
  19. showbox app download says:
  20. ADIL says:

    best printable 2017 Calendarbest printable 2017 Calendarbest printable 2017 Calendarbest printable 2017 Calendarbest printable Calendar 2017best printable Calendar 2007best printable Calendar 2017best printable Calendar 2017best printable Calendar 2007best printable Calendar 2017best printable Calendar 2017best printable Calendar 2017Us River map 2017Us River map 2017Us River map 2017Us River map 2017Us River map 2017Us River map 2017Us River map 2017Us River map 2007USA River map 2007USA River map 2007USA River map 2007USA River map 2007USA River map 2007USA River map 2007Map of united statesMap of united statesMap of united states

    In Rome, where winters were not as harsh as those in the far north, Saturnalia—a holiday in honor of Saturn, the god of agriculture—was celebrated.
    Beginning in the week leading up to the winter solstice and continuing for a full month, Saturnalia was a hedonistic time,
    when food and drink were plentiful and the normal Roman social order was turned upside down. For a month, slaves would become masters.
    Peasants were in command of the city. Business and schools were closed so that everyone could join in the fun.

  21. Spunky says:

    swasta tingkat SD, SMP, SMA dan SMK ironsteelcenter.com ironsteelcenter.comHarga besi beton Sni Ulir Polos Harga besi beton Sni Ulir PolosHarga besi hollow Harga besi hollowHarga besi cnp Harga besi cnpHarga besi unp Harga besi unpHarga wiremesh Harga wiremeshHarga besi wf Harga besi wfHarga besi h beam Harga besi h beamHarga Plat besi Harga Plat besiHarga pipa besi baja sch 40 sch 80 Harga pipa besi baja sch 40 sch 80Harga besi siku Harga besi sikuHarga Plat kapal besi baja bki krakatau steel Harga Plat kapal besi baja bki krakatau steelHarga bondek Harga bondekHarga baja ringan Harga baja ringanHarga Atap spandek Harga atap spandekHarga stainless steel Harga stainless steeljasa konstruksi jasa konstruksi besi baja jasa konstruksi gudang jasa konstruksi gedung jasa konstruksi undangan pernikahan undangan pernikahan simpleundangan pernikahan online udangan pernikahan pinkundangan pernikahan unik undangan pernikahan onlineundangan pernikahan murah undangan pernikahan islamiundangan pernikahan islami undangan pernikahan murahundangan pernikahan elegan undangan pernikahan artisundangan pernikahan unik dan murah contoh undangan pernikahan
    www.gudangbesibaja.com www.gudangbesibaja.comHarga besi cnp Harga besi cnpHarga besi h beam baja Harga besi h beam bajaHarga Plat besi plat kapal Harga Plat besi plat kapalHarga besi siku Harga besi sikuHarga besi unp Harga besi unpHarga besi wf baja Harga besi wf bajaHarga besi beton Sni Ulir Polos Harga besi beton Sni Ulir PolosHarga besi hollow Harga besi hollowHarga pipa besi baja sch 40 sch 80 Harga pipa besi baja sch 40 sch 80Harga wiremesh Harga wiremeshHarga bondek Harga bondekHarga besi Wf Baja Harga besi Wf Bajajasa konstruksi baja wf jasa konstruksi jembatan jasa konstruksi bangunan jasa konstruksi undangan pernikahan elegan dan murah undangan pernikahan eleganundangan pernikahan simple undangan pernikahan elegan dan murahundangan pernikahan artis undangan pernikahan putihudangan pernikahan pink undangan pernikahan unik dan murahundangan pernikahan putih undangan pernikahan unikContoh undangan pernikahan undangan pernikahan

    harga besi beton sni toko besi baja harga besi bahan bangunanharga pipa stainless steel pipa galvanis medium a besi bjkujual baja wf tabel baja krakatau steel harga besi ulir 16 mmharga stainless steel harga baja profil per kg harga besi 12 sniharga besi ulir harga besi wire mesh harga besi 8 mmdaftar harga pipa galvanis harga besi hollow stainless harga besi beton 10harga besi wf 200 harga baja hollow harga besi 13 ulirbesi kanal c galvanis steel rangka besi betondaftar harga besi beton harga pipa hollow harga besi kgjual wiremesh besi beam sni besi betonsupplier besi profil baja iwf harga besi behel 8mmbesi baja pipa galvanized harga besi beton 10mm snikonstruksi baja wf jual expanded metal harga besi ulir 10daftar harga besi hollow besi wire mesh harga sikuharga wiremesh profil baja h beam harga besi siku 4x4Supplier besi harga beam 200 besi siku hargaharga besi baja harga besi cnp 100 harga pipa besi hitamharga pipa baja jual besi cnp pipa seamlessbesi beton murah harga besi unp 100 daftar harga pipa stainless steelharga kanal c besi kanal c harga harga pipaharga besi stainless harga besi cnp 125 pipa stainlessharga besi per kg besi u galvanisharga plat stainless steel besi c pipa besi galvanisbesi unp harga besi cnp 150 harga besi hollow untuk pagarjual besi wf kanal c pipa besi hitamharga baja h beam daftar harga besi kanal c harga besi hollow 40x40

  22. india flag image says:


    indianflagimages

    indian flag images

    indian flag

    The National Flag of India is a horizontal rectangular tricolour of deep saffron, white and India green; with the Ashoka Chakra, a 24-spoke wheel, in navy blue at its centre
    indian national flag

    indian national flag images
    The National Flag of India is a horizontal rectangular tricolour of deep saffron, white and India green; with the Ashoka Chakra, a 24-spoke wheel, in navy blue at its centre
    india flag images

  23. Manchun says:

    Nice Article Thank you. JanBask Training as a Trainer, we offering Salesforce, Hadoop, Dot Net, SQL, PMP, Business Analyst and QA Testing.

  24. de says:
  25. ddiudf says:
  26. james clark says:

    Valentine's Day, also called Saint Valentine's Day or the Feast of Saint Valentine, valentines day is an annual holiday celebrated on February 14. valentines day wishes It originated as a Western Christian liturgical feast day honoring one or more early saints named Valentinus, and is recognized as a significant cultural and commercial celebration in many regions around the world, although it is not a public holiday in any country. Valentine's Day is celebrated on February 14 Valentine's Day is also a very popular date for weddings..It is a festival of romantic love and many people give cards, letters, flowers or presents to their spouse or partner. They may also arrange a romantic meal in a restaurant or night in a hotel. valentines day quotes Common symbols of Valentine's Day are hearts, red roses and Cupid.The most common Valentine's Day symbols are the heart, particularly in reds and pinks, and pictures or models of Cupid. Cupid is usually portrayed as a small winged figure with a bow and arrow.Many people celebrate their love for their partner by sending cards or letters, giving gifts or flowers and arranging meals in restaurants or romantic nights in hotels. valentines day images People who would like to have a romantic relationship with somebody may use the occasion to make this known, often anonymously. Valentine's cards are often decorated with images of hearts, red roses or Cupid. Common Valentine's Day gifts are flowers chocolates, candy, lingerie and champagne or sparkling wine

  27. Gomez says:
  28. Genelia says:
  29. Shubham Verma says:
  30. geometry dash 2.0 says:

    I really loved reading your blog. I also found your posts very interesting. In fact after reading, I had to go show it to my friend and he ejoyed it as well!

  31. happy wheels says:

    I have read your article. it is very informative and helpful for me.I admire the valuable information you offer in your articles. Thanks for posting it, again!

  32. happy wheels demo says:

    I think this is an informative post and it is very useful and knowledgeable. I really enjoyed reading this post. big fan, thank you!

  33. five nights at freddy's says:

    I think this is one of the most significant information for me. And i’m glad reading your article. Thank for sharing!

  34. 10th Board result says:

Leave a Reply