Get Started With ES6


Word on the street is that ES6 will be finalized in 2015. This will be great because ES6 will ease a lot of pain and being lots of improvements. Some browsers already supports parts of the draft specification and once the spec is finalized, expect many of those red boxes to quickly turn green.

I know a lot of people, myself included, will be learning more deeply ES6 this year. I wanted to share my take on it and offer some tips on how to get started.

It's optional

First off, don't stress out about suddenly needing to master everything in ES6 to stay relevant. Your existing JS will work just fine (of course, silly) so you can gradually use the new features over time.

If you contribute to open source or find yourself reading through lots of third party library code, keep in mind that many JS libraries likely will move to ES6 soon.

Try it out

There are many resources on the web to learn about ES6. It can be a little overwhelming and some resources are out-of-date.

I learn best to doing. The 6to5 site is a fun place to learn about ES6 and immediately try it out in a REPL. One caveat: if you see errors in your console when using the REPL, clear your localStorage and reload.

6to5 REPL

There's also ES6 Fiddle which uses Traceur.

Break it down

Instead of lerning a long list of unrelated things, you can also try to categorize them. This isn't a complete list, but here what I came up with:

Some people are finding cool ways to combine these new features, like using destructuring, spreads and rests for recursion much like you might find in functional languages.

Use it today

Some browsers support ES6 stuff today, for others you'll need to compile down to ES5. Right now it seems Traceur and 6to5 are the most popular tools do this. I think I prefer 6to5 since it's more lightweight.

Bear in mind both tools don't support every single thing in the ES6 draft spec and that all polyfills/shims come with some trade-offs. So your success mostly depends on which features you want to use and what price you are willing to pay (extra downloads, build process, etc.) to get them now.

It's important to get comfortable with tools like this however because they will be used to support older browsers in the future when most JavaScript code is written in ES6.

Modules are tricky. There's two parts to them: module definition syntax and module loading. You can use the ES6 syntax to define and consume modules then use tools to compile them to other module formats like AMD or CommonJS. You can use a polyfill to load ES modules and optionally use System.js to add support for more module formats. There's a lot happening in this space so if you want to use modules plan on dedicating some time researching this.

Don't get me started on package management. Check out this impressive video about jspm to get a sense for how complex this topic has become recently.

What about CoffeeScript and TypeScript?

Arrow functions and classes are probably the most-loved features of CoffeeScript and both will be provided by ES6. Meaningful whitespace will not.

TypeScript is essentially ES6 with type annotations. Odds are if you're using TypeScript then tooling, documentation and compile-time checks are very important to you. ES6 won't be providing those things.

Some examples

Here are just a few things I'm looking forward to using:

    
        // OLD & BUSTED
        var states = {
            "MD": true,
            "PA": true
        }
        function isValidState(state){
            return states[state];       // truthy
        }

        // ES6 NEW HOTNESS
        var states = new Set(["MD", "PA"]);  // not an array internally
        function isValidState(state) {
            return states.has(state);       // bool
        }
    
    
        // OLD & BUSTED
        function doStuf(options){
            var a = options.a,
                b = options.b;
            //...
        }
        
        // ES6 NEW HOTNESS
        function doStuff({a, b}){
            //...
        }
    
    
        // OLD & BUSTED
        [1,2,3,4].forEach(function(num){
            console.log(num);
        });
        
        // ES6 NEW HOTNESS
        [1,2,3,4].forEach((num) => console.log(num));
    
    
        // OLD & BUSTED
        function printNums(num) {
            num = num || 15;    // bad idea
            console.log(num);

            // if there are any additional params...
            var args = Array.prototype.slice.call(arguments);
            args.slice(1).forEach(function(arg){
                 console.log(arg * num)
            });
        }
        console.log(printNums(10,2,3,4));   // 10, 20, 30, 40
        
        // ES6 NEW HOTNESS
        function printNums(num = 15, ...moreArgs) {
            console.log(num);
            
            if(moreArgs.length) {
                moreArgs.forEach((arg) => console.log(arg * num));
            }
        }
        console.log(printNums(10,2,3,4));   // 10, 20, 30, 40
    
    
        // OLD & BUSTED
        var message = "Hello, " + firstName + ".\n" + "Welcome to JS." 
        
        // ES6 NEW HOTNESS
        var message = `Hello, ${firstName}
        Welcome to JS.`
    
    
        // OLD & BUSTED
        var numberDatabase = {
            numbers : [1,2,3,4,5,6],
            getNumbers : function() {
                // I only want to return evens!
                return this.numbers.filter(function(n){
                    return n % 2 === 0;
                });
            }
        };
        numberDatabase.getNumbers().forEach(function(x){
            console.log(x);
        }); // 2,4,6
        
        // ES6 NEW HOTNESS
        var numberDatabase = {
          numbers : [1,2,3,4,5,6],
          [Symbol.iterator]: function*() {
             for(let i=0;i

Then there are classes... On the plus side, they provide a standard/sugar'ed way to do things (super() calls, static methods, etc.) which will be very helpful if you're into using prototypal inheritance.

There are many alternatives for code re-use out there. Inheritance, in general, tends to be abused until people learn the hard way and prototypal inheritance is not widely understood (in my experience). I'm worried that ES6 classes will only make this worse in some situations.

Ultimately, classes are an improvement to what's in JavaScript today. If you're not totally confident in your understanding of prototypes, learning ES6 might be an opportunity to change that. Try creating some classes using the 6to5 REPL and look at the ES5 code it generates.

    
    class Animal {
        constructor(noise) {
            this.noise = noise;
        }
        speak() {
          console.log(this.noise);
        }
    }
    class Cat extends Animal {
        constructor(name){
            super("meow");
            this.name = name;
        }
    }
    var c = new Cat("milo");
    c.speak();        // "meow"
    console.log(c);   // {name: "milo"}
    console.log(c instanceof Cat);  // true
    console.log(c instanceof Animal);  // true
    console.log(c.__proto__ === Cat.prototype); // true
    console.log(Cat.prototype.speak === Animal.prototype.speak); // true
    console.log(c.speak === Animal.prototype.speak);  // true
    

Summary

Go forth and learn ES6 my friends!

[ Archive · Home ]