Monthly Archives: November 2015


By Axel Rauschmayer

Babel 6 is much more configurable than Babel 5, but also more difficult to configure. This blog post gives tips.

Installing Babel 6

Babel 6 is much more modular than Babel 5. The following are a few important npm packages:

  • babel-core: the core compilation machinery and plugin infrastructure for Babel.
  • babel-runtime: helper functions that can be called from compiled code, to make it more compact.
  • babel-polyfill: the ES6 standard library.
  • babel-register: hooks into Node.js, so that modules that are required are automatically transpiled via Babel (minus code you want to ignore, e.g. packages installed via npm).
  • babel-cli: a command line interface to Babel, via babel (which compiles files), babel-node (which is a babel-ified version of the node executable), etc.

If you install babel-register or babel-cli, everything those packages need is automatically installed, too.

All available packages reside in a single repository on GitHub. Browsing their source code and their package.json files is instructive.

Configuration data

Babel is often about compiling an input file, e.g. in the following two scenarios:

  • Compiling a file via the command line tool babel:

        babel input-es6.js --out-file output-es5.js
  • Running a Node.js script written in ES6:

        babel-node input-es6.js

The configuration data is an object of JSON data that is assembled from various sources (which are described later). Two configuration options have much influence on how the output is produced: plugins and presets.


Roughly, plugins are functions that are applied to the input during compilation. Two important categories of plugins are:

If you want to compile something that isn’t part of the base syntax, you need both a syntax plugin and a corresponding transform plugin. However, each transform plugin that depends on a syntax plugin automatically activates that plugin.

Plugins are installed via npm. Their package names are their names plus the prefix babel-plugin-:

  • Plugin syntax-jsx: npm install babel-plugin-syntax-jsx
  • Plugin transform-react-jsx: npm install babel-plugin-transform-react-jsx


In order to configure Babel’s output to your liking, you need to specify what plugins it should use. You can specify:

  • Individual plugins
  • Presets, sets of plugins that support various compilation scenarios.

The following are useful presets:

  • es2015: compiles ES6 (as described by the ECMAScript spec) to ES5
  • stage-3: compiles stage 3 ECMAScript proposals to ES5
  • react: compiles JSX to JavaScript and removes Flow type annotations
  • es2015-node5: Contains just those transform plugins that are need to upgrade Node.js 5 to full ES6. Therefore, a lot less is transpiled than with the es2015 preset. Especially generators not being transpiled helps with debugging.

Presets are installed via npm. Their package names are their names plus the prefix babel-preset-. For example, this is how to install the preset es2015:

    npm install babel-preset-es2015

Sources of configuration data

The configuration data is always located relative to the input file:

  • When ascending through parent directories, whichever of the following two files is found first is used. If they are both in the same directory then .babelrc is used.
    • .babelrc: The file’s contents are interpreted as JSON and used as Babel options.
    • package.json: Property babel of the file’s JSON content is used as Babel options. This file only counts if it has the property babel.
  • .babelignore: The “first” file in the parent directories is used. Its lines are turned into an Array and interpreted as the option ignore.

Two properties in configuration data specify additional configuration data:

  • Property env of maps the names of environments ('development', 'production', etc.) to objects with more configuration data. If env exists, the object corresponding to the current environment is merged with the configuration data that has already been assembled. Consult the Babel documentation for more information on environments.
  • Property extends contains a path pointing to a file with more configuration data.


If you are using babel-node, you can also specify the following options (and a few others) via the command line:

  • --presets
  • --plugins
  • --ignore: by default, any file that has the segment 'node_modules' in its path is not transpiled.

The following command runs my-script.js via babel-node, with the presets es2015-node5 and react, and the plugin transform-async-to-generator enabled.

    babel-node --presets es2015-node5,react --plugins transform-async-to-generator my-script.js

On Unix, if a file is executable and contains the following first line then you can directly execute it, via babel-node:

    #!/usr/bin/env babel-node

You could specify presets etc. as options at the end of this line, but doing so via package.json seems cleaner. This is a minimal package.json for a project with an executable:

      "name": "tools",
      "dependencies": {
        "babel-cli": "^6.1.2",
        "babel-preset-es2015-node5": "^1.1.0",
      "bin": {
        "foo" : "./bin/foo.js"
      "scripts": {
        "foo": "./bin/foo.js"
      "babel": {
        "presets": [

There are several ways of running foo.js:

  • You can execute foo.js directly (if it is executable and starts with the right prolog):

        cd tools/
  • You can execute foo.js via npm run (as configured in scripts):

        cd tools/
        npm run foo arg1 arg2
  • If you install package tools globally, you get a command line command foo (as specified via bin).

  • If you install package tools locally, as a dependency of another package, you can execute foo via the scripts of that package, as if it was a globally installed command. That’s because npm adds the bin entries of all dependencies to the shell path before executing scripts (alas, not the bin entries in the same package.json).


The following is an excerpt of webpack.config.js in the repo react-starter-project.

    var path = require('path');
    module.exports = {
        module: {
            loaders: [
                    loader: 'babel-loader',
                    test: path.resolve(__dirname, 'js'),
                    query: {
                        presets: ['es2015'],

As you can see, babel-loader supports the property query for specifying Babel options.

More information

Source:: 2ality

ES.stage3: Trailing commas in function parameter lists and calls

By Axel Rauschmayer

The following ECMAScript proposal is at stage 3: “Trailing commas in function parameter lists and calls” by Jeff Morrison. This blog post explains it.

For information on stages and ECMAScript 2016, consult the post “What’s in ECMAScript 2016 (ES7)?”.

Trailing commas in object literals and Array literals

Trailing commas are ignored in object literals:

    let obj = {
        first: 'Jane',
        last: 'Doe',

And they are also ignored in Array literals:

    let arr = [
    console.log(arr.length); // 3

Why is that useful? There are two benefits.

First, rearranging items is simpler, because you don’t have to add and remove commas if the last item changes its position.

Second, it helps version control systems with tracking what actually changed. For example, going from:




leads to both the line with 'foo' and the line with 'bar' being marked as changed, even though the only real change is the latter line being added.

Proposal: allow trailing commas in parameter definitions and function calls

Given the benefits of optional and ignored trailing commas, the proposed feature is to bring them to parameter definitions and function calls.

For example, the following function declaration causes a SyntaxError in ECMAScript 6, but would be legal with the proposal:

    function foo(
    ) {}

Similarly, the proposal would make this invocation of foo() syntactically legal:


Source:: 2ality

Think You Know ES6? Prove it!

By Danny Markov


Your favorite web scripting language just got even better! The 2015 edition of ECMAScript comes with a ton of cool new techniques and programming concepts, much anticipated by the JavaScript community. Most of the new features are already available out of the box with modern browsers and Node.js, and are expected to receive wide support soon.

We’ve prepared a fun quiz which you can take to see how much you know about ES6 (aka ES2015), and maybe learn a few new things as well!

(See this quiz on


ES.stage3: string padding

By Axel Rauschmayer

The following ECMAScript proposal is at stage 3: “String padding” by Jordan Harband & Rick Waldron. This blog post explains it.

For information on stages and ECMAScript 2016, consult the post “What’s in ECMAScript 2016 (ES7)?”.

Padding strings

The main use case for padding strings is displaying tabular data in a monospaced font. With padding, you can left-justify or right-justify the contents of a “cell”.

String.prototype.padStart(maxLength, fillString=' ')

This method (possibly repeatedly) prefixes the receiver with fillString, until its length is maxLength:

    > 'x'.padStart(5, 'ab')

If necessary, a fragment of fillString is used so that the result’s length is exactly maxLength:

    > 'x'.padStart(4, 'ab')

If the receiver is as long as, or longer than, maxLength, it is returned unchanged:

    > 'abcd'.padStart(2, '#')

If maxLength and fillString.length are the same, fillString becomes a mask into which the receiver is inserted, at the end:

    > 'abc'.padStart(10, '0123456789')

If you omit fillString, a string with a single space in it is used (' '):

    > 'x'.padStart(3)
    '  x'

A simple implementation of padStart()

The following implementation gives you a rough idea of how padStart() works, but isn’t completely spec-compliant (for a few edge cases).

    String.prototype.padStart =
    function (maxLength, fillString=' ') {
        let str = String(this);
        if (str.length >= maxLength) {
            return str;
        fillString = String(fillString);
        if (fillString.length === 0) {
            fillString = ' ';
        let fillLen = maxLength - str.length;
        let timesToRepeat = Math.ceil(fillLen / fillString.length);
        let truncatedStringFiller = fillString
            .slice(0, fillLen);
        return truncatedStringFiller + str;

String.prototype.padEnd(maxLength, fillString=' ')

padEnd() works similarly to padStart(), but instead of inserting the repeated fillString at the start, it inserts it at the end:

    > 'x'.padEnd(5, 'ab')
    > 'x'.padEnd(4, 'ab')
    > 'abcd'.padEnd(2, '#')
    > 'abc'.padEnd(10, '0123456789')
    > 'x'.padEnd(3)
    'x  '

Only the last line of an implementation of padEnd() is different, compared to the implementation of padStart():

    return str + truncatedStringFiller;

FAQ: string padding

Why aren’t the padding methods called padLeft and padRight?

There will be trimLeft and trimRight, but only for reasons of backward compatibility:

In this discussion it was noted that the words left and right don’t make sense for bidirectional and right-to-left languages. A more appropriately name for these functions would be trimStart and trimEnd which corresponds to the existing startsWith and endsWith.

Unfortunately, all engines already implement them and removing them would likely break the web.

Source:: 2ality


By Axel Rauschmayer

Quick recap – all ECMAScript proposals go though stages (more information on stages):

  • At stage 3, a feature is likely to be part of a release soon.
  • At stage 4, a feature is probably part of the next release.

The following proposal has reached stage 3: “Object.values/Object.entries” by Jordan Harband. This blog post explains that proposal.


This method has the following signature:

    Object.entries(value : any) : Array<[string,any]>

If a JavaScript data structure has keys and values then an entry is a key-value pair, encoded as a 2-element Array. Object.entries(x) coerces x to an Object and returns the entries of its enumerable own string-keyed properties, in an Array:

    > Object.entries({ one: 1, two: 2 })
    [ [ 'one', 1 ], [ 'two', 2 ] ]

Properties whose keys are symbols, are ignored:

    > Object.entries({ [Symbol()]: 123, foo: 'abc' });
    [ [ 'foo', 'abc' ] ]

Object.entries() finally gives us a way to iterate over the properties of an object (read here why objects aren’t iterable by default):

    let obj = { one: 1, two: 2 };
    for (let [k,v] of Object.entries(obj)) {
        console.log(`${JSON.stringify(k)}: ${JSON.stringify(v)}`);
    // Output:
    // "one": 1
    // "two": 2

Setting up Maps via Object.entries()

Object.entries() also lets you set up a Map via an object. This is more concise than using an Array of 2-element Arrays, but it only works if the keys are strings.

    let map = new Map(Object.entries({
        one: 1,
        two: 2,
    // Output:
    // [["one",1],["two",2]]

FAQ: Object.entries()

  • Why is the return value of Object.entries() an Array and not an iterator?
    The relevant precedent in this case is Object.keys(), not, e.g., Map.prototype.entries().

  • Why does Object.entries() only return the enumerable own string-keyed properties?
    Again, this is done to be consistent with Object.keys(). That method also ignores properties whose keys are symbols. Eventually, there may be a method Reflect.ownEntries() that returns all own properties.


Object.values() has the following signature:

    Object.values(value : any) : Array<any>

It works much like Object.entries(), but, as its name suggests, it only returns the values of the own enumerable string-keyed properties:

    > Object.values({ one: 1, two: 2 })
    [ 1, 2 ]

Upcoming blog posts

The following two features have also reached stage 3 and will be explained on 2ality soon:

Additionally, “Array.prototype.includes” is now at stage 4.

Source:: 2ality

Using Flexbox to Create a Responsive Comment Section

By Danny Markov


Flexbox is a powerful new way for building layouts that makes some of the most challenging aspects of web development trivial. Nearly all browsers that are used today support it, so it is a good time to see how it can fit in your typical day-to-day frontend work.

This is why in this quick tutorial we’re going to build a comment section using flexbox. We’ll take a look at some of the more interesting properties that the flexbox layout mode has to offer and show you how to take full advantage of it.

What We’re Going to Use

Flexbox consists of a number of CSS properties, some of which we are going to use today:

  • display: flex – This activates the flex layout mode and makes the element’s children follow flexbox rules.
  • justify-content – This property defines where the children of a flexbox element will align to (this is similar to text-align, read more here).
  • order – Flexbox gives us control on the exact position elements are displayed at. We use this powerful tool in our comment section to switch the text and photo around (find out more here).
  • flex-wrap – Controls the wrapping of the elements within the flex element. We use this to force the avatars to show beneath the comment text on small screens (flex-wrap on MDN).

The Layout

We want our comment section to meet the following requirements:

  • Each comment should have an avatar, name, time and comment body.
  • There should be two comment types – those written by the author (colored in blue and having the avatar on the right) and those written by everyone else.
  • The HTML markup for both types of comments has to be as similar as possible, so it is easy to generate comments through code.
  • The whole thing has to be fully responsive.

Comment Section Layout

All of this can be made with a few lines of CSS with flexbox. Let’s move on the the code!


Our HTML is pretty straightforward. We’ll have a list of comments with a basic form for writing new comments at the end.

<ul class="comment-section">

    <li class="comment user-comment">
        <div class="info">
            <a href="#">Anie Silverston</a>
            <span>4 hours ago</span>
        <a class="avatar" href="#">
            <img src="images/avatar_user_1.jpg" width="35" alt="Profile Avatar" title="Anie Silverston" />
        <p>Suspendisse gravida sem?</p>

    <li class="comment author-comment">
        <div class="info">
            <a href="#">Jack Smith</a>
            <span>3 hours ago</span>
        <a class="avatar" href="#">
            <img src="images/avatar_author.jpg" width="35" alt="Profile Avatar" title="Jack Smith" />
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse gravida sem sit amet molestie portitor.</p>


    <!-- More comments -->

    <li class="write-new">

        <form action="#" method="post">
            <textarea placeholder="Write your comment here" name="comment"></textarea>
                <img src="images/avatar_user_2.jpg" width="35" alt="Profile of Bradley Jones" title="Bradley Jones" />
                <button type="submit">Submit</button>



If you look closely at the above code, you’ll notice that apart from having different classes, the HTML for the user comments and the author comments are practically the same. All of the stylistic and layout differences between the two, will be handled solely by CSS applied to the .user-comment and .author-comment classes.


Here we’re going to look at flexbox-related techniques we’ve used when building the layout. If you want to examine the stylesheet in full detail, download the whole CSS file from the button near the top of the article.

First off, we are going to give all comments display: flex, which will enable us to use the flexbox properties on the comments and their child elements.

    display: flex;

These flex containers span the full width of our comment section and hold the user info, avatar and message. Since we want the comments written by the author to be aligned to the right, we can use the following flex property and align everything towards the end of our container.{
    justify-content: flex-end;

This will leave the comments looking like this:

justify-content: flex-end

justify-content: flex-end

Now we have the author comment aligned on the right, but we also want to have the elements inside the container in reverse order, so that the message comes first, then the avatar and the info on the far right. To do this we will take advantage of the order property. .info{
    order: 3;
} .avatar{
    order: 2;
} p{
    order: 1;

As you can see, with the help of flexbox, the whole thing couldn’t be any easier.

Reordering Elements

Reordering Elements

Our comment section looks just like we wanted it to. The only thing left to do is make sure that it looks good on smaller devices as well. Since there won’t be as much available space on a narrower screen, we’ll have to do some rearrangements to the layout and make our content more easily readable.

We set up a media query that makes the comment paragraphs expand, taking up the whole width of the container. This will lead to the avatar and user info moving to the next line, since the comments have their flex-wrap property set to wrap.

@media (max-width: 800px){
    /* Reverse the order of elements in the user comments,
    so that the avatar and info appear after the text. */
    .comment.user-comment .info{
        order: 3;

    .comment.user-comment .avatar{
        order: 2;

    .comment.user-comment p{
        order: 1;

    /* Make the paragraph in the comments take up the whole width,
    forcing the avatar and user info to wrap to the next line*/
    .comment p{
        width: 100%;

    /* Align toward the beginning of the container (to the left)
    all the elements inside the author comments. */{
        justify-content: flex-start;

The difference can be spotted right away by comparing this screen capture with the one above. You can also try opening the demo and resizing your browser to watch the comment section adapt accordingly to the size of the window.

Our comment section on smaller screens

Our comment section on smaller screens


This sums up our tutorial. We hope that this gave you a practical example on how to use flexbox when building real layouts. If you’re curious what else is possible, here are a few great resources that you’ll like:

  • CSS-Tricks’ guide to flexbox – here.
  • An in-depth MDN article – here.
  • A website with easy flexbox solutions for classic CSS problems – here.


What’s in ECMAScript 2016 (ES7)?

By Axel Rauschmayer

The most recent release of ECMAScript, ES6, is large and was standardized almost 6 years after ES5 (December 2009 vs. June 2015). There are two main problems with so much time passing between releases:

  • Features that are ready sooner than the release have to wait until the release is finished.
  • Features that take long are under pressure to be wrapped up, because postponing them until the next release would mean a long wait. Such features may also delay a release.

Therefore, starting with ECMAScript 2016 (ES7), releases will happen more frequently and be much smaller as a consequence. There will be one release per year and it will contain all features that are finished by a yearly deadline.

This blog post describes the details of this new release process, along with four features that will probably be in ECMAScript 2016.

Before we get started, let’s refresh our memories: who or what is TC39?

Technical Committee 39 (TC39)

TC39 (Ecma Technical Committee 39) is the committe that evolves JavaScript. Its members are companies (among others, all major browser vendors). TC39 meets regularly, its meetings are attended by delegates that members send and by invited experts. Minutes of the meetings are available online and give you a good idea of how TC39 works.

Occasionally (even in this blog post), you’ll see the term TC39 member referring to a human. Then it means: a delegate sent by a TC39 member company.

It is interesting to note that TC39 operates by consensus: Decisions are only made if every member (as represented by its delegates) agrees.

The TC39 process

Each proposal for an ECMAScript feature goes through the following maturity stages, starting with stage 0. The progression from one stage to the next one must be approved by TC39.

Stage 0: strawman

What is it? A free-form way of submitting ideas for evolving ECMAScript. Submissions must come either from a TC39 member or a non-member who has registered as a TC39 contributor.

What’s required? The document must be reviewed at a TC39 meeting (source) and is then added to the page with stage 0 proposals.

Stage 1: proposal

What is it? A formal proposal for the feature.

What’s required? A so-called champion must be identified who is responsible for the proposal. Either the champion or a co-champion must be a member of TC39 (source). The problem solved by the proposal must be described in prose. The solution must be described via examples, an API and a discussion of semantics and algorithms. Lastly, potential obstacles for the proposal must be identified, such as interactions with other features and implementation challenges. Implementation-wise, polyfills and demos are needed.

What’s next? By accepting a proposal for stage 1, TC39 declares its willingness to examine, discuss and contribute to the proposal. Going forward, major changes to the proposal are expected.

Stage 2: draft

What is it? A first version of what will be in the specification. At this point, an eventual inclusion of the feature in the standard is likely.

What’s required? The proposal must now additionally have a formal description of the syntax and semantics of the feature (using the formal language of the ECMAScript specification). The description should be as complete as possible, but can contain todos and placeholders. Two experimental implementations of the feature are needed, but one of them can be in a transpiler such as Babel.

What’s next? Only incremental changes are expected from now on.

Stage 3: candidate

What is it? The proposal is mostly finished and now needs feedback from implementations and users to progress further.

What’s required? The spec text must be complete. Designated reviewers (appointed by TC39, not by the champion) and the ECMAScript spec editor must sign off on the spec text. There must be at least two spec-compliant implementations (which don’t have to be enabled by default).

What’s next? Henceforth, changes should only be made in response to critical issues raised by the implementations and their use.

Stage 4: finished

What is it? The proposal is ready to be included in the standard.

What’s required? The following things are needed before a proposal can reach this stage:

  • Test 262 acceptance tests (roughly, unit tests for the language feature, written in JavaScript).
  • Two spec-compliant shipping implementations that pass the tests.
  • Significant practical experience with the implementations.
  • The ECMAScript spec editor must sign off on the spec text.

What’s next? The proposal will be included in the ECMAScript specification as soon as possible. When the spec goes through its yearly ratification as a standard, the proposal is ratified as part of it.

Don’t call them ECMAScript features

As you can see, you can only be sure that a feature will be included in the standard once its proposal has reached stage 4. Then its inclusion in the next ECMAScript release is probable, but not 100% sure, either (it may take longer). Therefore, you can’t call proposals (e.g.) “ES7 features” or “ES2016 features”, anymore. My two favorite ways of writing headings for articles and blog posts are therefore:

  • “ECMAScript proposal: the foo feature”. The stage of the proposal is mentioned at the beginning of the article.
  • “ES.stage2: the foo feature”

If a proposal is at stage 4, I’d be OK with calling it an ES20xx feature, but it’s safest to wait until the spec editor confirms what release it will be included in. Object.observe is an example of an ECMAScript proposal that had progressed until stage 2, but was ultimately withdrawn.

ECMAScript stage 3 proposals

Chances are good that the following features will be in ECMAScript 2016.

Exponentiation Operator (Rick Waldron)

The proposed feature is ** as an infix operator for exponentiation:

    x ** y

is produces the same result as

    Math.pow(x, y)


    let squared = 3 ** 2; // 9
    let num = 3;
    num **= 2;
    console.log(num); // 9

Further reading:

Array.prototype.includes (Domenic Denicola, Rick Waldron)

The Array method includes has the following signature:

    Array.prototype.includes(value : any) : boolean

It returns true if value is an element of its receiver (this) and false, otherwise:

    > ['a', 'b', 'c'].includes('a')
    > ['a', 'b', 'c'].includes('d')

includes is similar to indexOf – the following two expressions are mostly equivalent:

    arr.indexOf(x) >= 0

The only exception is that includes() finds NaN, whereas indexOf() doesn’t:

    > [NaN].includes(NaN)
    > [NaN].indexOf(NaN)

includes does not distinguish between +0 and -0 (which is how almost all of JavaScript works):

    > [-0].includes(+0)

Typed Arrays will also have a method includes():

    let tarr = Uint8Array.of(12, 5, 3);
    console.log(tarr.includes(5)); // true
Frequently asked questions
  • Why is the method called includes and not contains?
    The latter was the initial choice, but that broke code on the web (MooTools adds this method to Array.prototype).

  • Why is the method called includes and not has?
    has is used for keys (Map.prototype.has), includes is used for elements (String.prototype.includes). The elements of a Set can be viewed as being both keys and values, which is why there is a Set.prototype.has (and no includes).

  • The ES6 method String.prototype.includes works with strings, not characters. Isn’t that inconsistent w.r.t. Array.prototype.includes?
    If Array includes worked exactly like string includes, it would accept arrays, not single elements. But the two includes follow the example of indexOf; characters are seen as a special case and strings with arbitrary lengths as the general case.
Further reading

SIMD.JS – SIMD APIs + polyfill (John McCutchan, Peter Jensen, Dan Gohman, Daniel Ehrenberg)

SIMD stands for “single instruction, multiple data”, the ability of a CPU to apply an operand to vectors of values (instead of single values). One popular example of a SIMD instruction set is SSE (Streaming SIMD Extensions), as supported by Intel processors.

This is a short code example, consult the sources below for more information.

    var a = SIMD.float32x4(1.0, 2.0, 3.0, 4.0);
    var b = SIMD.float32x4(5.0, 6.0, 7.0, 8.0);
    var c = SIMD.float32x4.add(a,b);

Further reading:

Async Functions (Brian Terlson)

Before I can explain async functions, I need to explain how Promises and generators can be combined to perform asynchronous operations via synchronous-looking code.

Writing async code via Promises and generators

For functions that compute their one-off results asynchronously, Promises, which are part of ES6, are becoming increasingly popular. One example is the client-side fetch API, which is an alternative to XMLHttpRequest for retrieving files. Using it looks as follows:

    function fetchJson(url) {
        return fetch(url)
        .then(request => request.text())
        .then(text => {
            return JSON.parse(text);
        .catch(error => {
            console.log(`ERROR: ${error.stack}`);
    .then(obj => console.log(obj));

co is a library that uses Promises and generators to enable a coding style that looks more synchronous, but works the same as the style used in the previous example:

    const fetchJson = co(function* () {
        try {
            let request = yield fetch(url);
            let text = yield request.text();
            return JSON.parse(text);
        catch (error) {
            console.log(`ERROR: ${error.stack}`);

Every time the callback (a generator function!) yields a Promise to co, the callback gets suspended. Once the Promise is settled, co resumes the callback: if the Promise was fulfilled, yield returns the fulfillment value, if it was rejected, yield throws the rejection error. Additionally, co promisifies the result returned by the callback (similarly to how then() does it).

Async functions

Async functions are basically dedicated syntax for what co does:

    async function fetchJson(url) {
        try {
            let request = await fetch(url);
            let text = await request.text();
            return JSON.parse(text);
        catch (error) {
            console.log(`ERROR: ${error.stack}`);

Internally, async functions work much like generators, but they are not translated to generator functions.


The following variants of async functions exist:

  • Async function declarations: async function foo() {}
  • Async function expressions: const foo = async function () {};
  • Async method definitions: let obj = { async foo() {} }
  • Async arrow functions: const foo = async () => {};
Further reading

Further reading

The following were important sources of this blog post:

More information on the ES6 design process: section “How ECMAScript 6 was designed” in “Exploring ES6”.

Source:: 2ality

Freebie: 4 Wonderful JavaScript Option Menus

By Danny Markov


In this iteration of your freebie giveaway, we’ve prepared for you 4 awesome option menus! They are made entirely our of vanilla HTML, CSS and JavaScript, and don’t require any libraries or frameworks (except for some jQuery).

The Menus

These menus are designed in such a way, that they can quickly show all the needed options for your app. They are hidden offscreen and only appear when a user requests them with the push of a button. Once open, the menus can easily be hidden away again via a close button.

All you have to do, to include any of these menus in your project, is to copy the HTML from the demo examples and place the code anywhere on your page. There are also a few lines of JavaScript, and a specific CSS file for each menu. Both the JavaScript and CSS are self contained and shouldn’t cause any side effects to your existing content.

We’ve also added event handlers that call alerts when a option in the menus is selected. You can use this to effortlessly add your own functionality to all the links and buttons.

Side Option Menu

Free for Commercial Use

The menus can be downloaded from the button on the top of the page. You have all rights to customize them and use them however you want, in both personal and commercial projects (our license page). Enjoy!


Synchronous and asynchronous sequential execution of functions

By Axel Rauschmayer

This blog post examines three ways of executing function sequentially:

  • Synchronously
  • Asynchronously, via Promises
  • Asynchronously, via the library co


Synchronous sequential execution is built into JavaScript and looks like this:

    function func() {

Asynchronously, via Promises

To execute Promise-based functions sequentially, you need to chain function calls via then(), which is the Promise equivalent of the semicolon:

     * Returns a Promise that resolves to `undefined`.
    function func() {
        return foo()
        .then(() => bar())
        .then(() => baz());

If you are OK with executing the functions in an arbitrary order (the single-threaded version of “in parallel”), you can use Promise.all():

     * Returns a Promise that resolves to
     * [undefined, undefined, undefined].
    function func() {
        return Promise.all([foo(), bar(), baz()]);

Asynchronously, via the library co

The library co also works with Promise based functions. Its main function, co(), takes a generator as a callback and suspends and resumes it as the results arrive. co() returns a Promise-based function that returns a promisified version of whatever the callback returns.

     * The callback implicitly returns `undefined`.
     * Therefore, `func` returns a Promise that resolves to
     * `undefined`.
    const func = co(function* () {
        yield foo();
        yield bar();
        yield baz();

co works very much like async functions, a proposed ECMAScript feature (to appear in ES2016 or later), without being much more verbose. I prefer it to transpiling async functions via Babel, because their syntax may still change.

Further reading

Source:: 2ality