Wednesday, February 18, 2015

Preparing for ECMAScript6

The Standard ECMAScript5 (referred to as ES5) was originally published late 2009 and has since moulded JavaScript to become one of the worlds most important languages.


ECMAScript6 is the upcoming version of the ECMAScript standard and expects ratification some time around June 2015. ES6 is a significant update to JavaScript, and the first update to the language since 2009. Implementation of these features in JavaScript engines is well underway as we speak. Let’s dive in and see what ES6 is all about.




The Better Parts


Doug Crockford lists out the following as some of the better parts to the ES6 specification with a few I find of great use – specifically template literals (think handlebars).



  • Proper Tail Calls : Improves performance and uses less memory. Also enables a whole new kind of programming.

    function factorial(n, acc = 1) {
    'use strict';
    if (n <= 1) return acc;
    return factorial(n - 1, n * acc);
    }

    // Stack overflow in most implementations today,
    // but safe on arbitrary inputs in eS6
    factorial(100000)


  • Ellipsis (a.k.a “rest” or “spread” operator) : A great way of writing functions that deal with a number of arguments.

    function f(x, y=12) {
    // y is 12 if not passed (or passed as undefined)
    return x + y;
    }
    f(3) == 15

    function f(x, ...y) {
    // y is an Array
    return x * y.length;
    }
    f(3, "hello", true) == 6

    function f(x, y, z) {
    return x + y + z;
    }
    // Pass each elem of array as argument
    f(...[1,2,3]) == 6


  • Modules : Helps remove us from real global variables that pollute the namespace (a really good thing btw) and does a better job at managing asynchronousity.

    // lib/math.js
    export function sum(x, y) {
    return x + y;
    }
    export var pi = 3.141593;

    // app.js
    import * as math from "lib/math";
    alert("2π = " + math.sum(math.pi, math.pi));

    // otherApp.js
    import {sum, pi} from "lib/math";
    alert("2π = " + sum(pi, pi));


  • Let : This new statement works like var, but respects block and scope.

    function f() {
    {
    let x;
    {
    // okay, block scoped name
    const x = "sneaky";
    // error, const
    x = "foo";
    }
    // error, already declared in block
    let x = "inner";
    }
    }


  • Destructuring : Syntactical sugar to make things a little easier to express.

    // list matching
    var [a, , b] = [1,2,3];

    // object matching
    var { op: a, lhs: { op: b }, rhs: c }
    = getASTNode()

    // object matching shorthand
    // binds `op`, `lhs` and `rhs` in scope
    var {op, lhs, rhs} = getASTNode()

    // Can be used in parameter position
    function g({name: x}) {
    console.log(x);
    }
    g({name: 5})

    // Fail-soft destructuring
    var [a] = [];
    a === undefined;

    // Fail-soft destructuring with defaults
    var [a = 1] = [];
    a === 1;


  • Weak Map – Adds new functionality but has a terrible name. Any object value can be a key. Currently ES5 does not allow that. If a key becomes unrooted the garbage collector can take it out of the map.

    // Sets
    var s = new Set();
    s.add("hello").add("goodbye").add("hello");
    s.size === 2;
    s.has("hello") === true;

    // Maps
    var m = new Map();
    m.set("hello", 42);
    m.set(s, 34);
    m.get(s) == 34;

    // Weak Maps
    var wm = new WeakMap();
    wm.set(s, { extra: 42 });
    wm.size === undefined

    // Weak Sets
    var ws = new WeakSet();
    ws.add({ data: 42 });
    // Because the added object has no other references, it will not be held in the set


  • Template Literals – Strings that can include embedded expressions. This is sometimes referred to as string interpolation.

    // Basic literal string creation
    `In JavaScript '\n' is a line-feed.`

    // Multiline strings
    `In JavaScript this is
    not legal.`

    // String interpolation
    var name = "Bob", time = "today";
    `Hello ${name}, how are you ${time}?`

    // Construct an HTTP request prefix is used to interpret the replacements and construction
    GET`http://ift.tt/1AmLS5V}
    Content-Type: application/json
    X-Credentials: ${credentials}
    { "foo": ${foo},
    "bar": ${bar}}`(myOnReadyStateChangeHandler);


  • Promises – Allows easier and cleaner asynchronous coding. Adds the Promise() constructor, along with the ‘all’ and ‘race’ utility methods to the language itself.

    function timeout(duration = 0) {
    return new Promise((resolve, reject) => {
    setTimeout(resolve, duration);
    })
    }

    var p = timeout(1000).then(() => {
    return timeout(2000);
    }).then(() => {
    throw new Error("hmm");
    }).catch(err => {
    return Promise.all([timeout(100), timeout(200)]);
    })



Note: Code examples based off Luke Hoban’s great great overview.




Why Write ES6 Today?


I’m guessing by now you’re still wondering why you should start writing ES6 right this very minute? The reason you should start writing ES6 today is because first and foremost it’s always good for developers to keep ahead of the game. Also ES6 really helps to improve the language in many aspects in terms of syntax, functionality and even performance.


There’s really no excuse not to get started immediately even if it’s using a small portion to start. Remember… baby steps.




Getting Started with ES6


If you’d like to start writing ES6 right this very minute the good news is you can. The bad news is you’ll need some extra tooling to help get you there until the standard has wider support.


Addy Osmani also has a great repo where he provides ES6 equivalent examples in ES5 that I definitely encourage you to take a look at later.


Features like modules in ES6 are not supported yet by any browser nor in Node.js. This means if you want to write modules you’ll need a transpiler using a grunt task like grunt-babel that turns ES6 code into vanilla ES5 (there’s also gulp-babel for you Grunt Hatahs.).


This Grunt task also supports AMD allowing developers to integrate ES6 modules into their current environment, independent of legacy/current modules style choice.




Words of Wisdom


Since we’re discussing standards we should always keep in mind as we write code that standards are great. They help maintain a cohesiveness that’s understood globally, but standards are not meant to be Draconian Law.


Remember to experiment and accept the occasional failure when taking the time to learn new things in order to update your knowledge in a specific area. As we all know, this industry moves fast so don’t be afraid to take bite sized amounts to digest.




Helpful Tools & References



The post Preparing for ECMAScript6 appeared first on Web Design Weekly.




by Dennis Gaebel via Web Design Weekly

No comments:

Post a Comment