Life, JavaScript & Everything else

ECMAScript 6 today with Babel.js

Introduction

user

Marcin Kumorek

Front-end Hacker, JavaScript maniac, Sublime Text and Vim user, addicted to cookies who loves travelling and contemplating about the endless Universe.


ECMAScript 6, ES6, JavaScript, Babel.js

ECMAScript 6 today with Babel.js

Posted by Marcin Kumorek on .
Featured

ECMAScript 6, ES6, JavaScript, Babel.js

ECMAScript 6 today with Babel.js

Posted by Marcin Kumorek on .

JavaScript is the most popular language on github.com according to githut.info. It is available in every browser, most of new phones, tablets, TVs and even some fridges! The next version, ECMAScript 6, will bring loads of interesting features. We can use most of them today thanks to ES6 transpilers. The one I've decided to use is called - Babel.js.

Great, so we can start writing more concise, readable and maintainable code. But before we do, let's take a look at...

The brief history of JavaScript

JavaScript was created in 10 days, in May 1995, by Brendan Eich. It was first released in Netscape 2 browser in early 1996. Originally called Mocha but soon after renamed to LiveScript, to reflect it's dynamic nature. Later on renamed once again, this time to JavaScript after Sun Microsystem's very popular Java language.

In 1997, the JavaScript core language features were defined in a standard called ECMA-262. The official name of the language in this standard is ECMAScript. JavaScript in the browser and Node.js environments are a supersets of ECMAScript.

The first significant update was ECMAScript 3 in 1999. ECMAScript 4 was abandoned due to many political reasons. The fifth edition was released in December 2009. The current edition of the ECMAScript standard is 5.1, released in June 2011. Next version is called ECMAScript 6 or ECME-262 6th Edition. The final draft has been submitted to TC39 for approval. The meeting will be held in June 2015 which means that we're getting really close to the day of the release. Which obviously leads to the question...

How can I try it right now?

In order to use ES6 today we need to transpile (transcode + compile) ES6 syntax into ES5. There is large number of available tools that can do this. There is a great github repository es6-tools from @addyosmani. The one I'll be using is called Babel.js. According to ECMAScript 6 compatibility table we can now use 76% of the new features of ES6! Awesome! There's a small number of polyfills that you need to use if you plan to support older browsers. Apart from this, there's just the sweet joy of writing more elegant, concise and readable code.

New features in ES6

ECMAScript 6 will bring tons of new features. Here's a couple of interesting ones:

  • let and const keywords
  • => a.k.a. fat arrow
  • destructuring
  • classes
  • modules
  • Set, Map, WeakSet, WeakMap
  • new Object literal syntax
  • new Array methods
  • Symbols
  • String templates
  • and more...

If you want to know more about the new features of ES6 see an excellent repo from lukehoban or visit Babel.js learn-es6 section.

Show time

Right, now let's write some ES6 code. Let's create a Person class in src/ and export it using the new modules feature.

// src/Person.js
export default class Person {  
    constructor(firstName, lastName) {
        this.firstName = firstName
        this.lastName = lastName
        this.friendsList = []
    }

    friendsWith(...friends) {
        for (let friend of friends) {
            this.friendsList.push(friend)
        }
    }

    getFriends() {
        return [].slice.call(this.friendsList)
    }

    get fullName() {
        return `${ this.firstName } ${ this.lastName }`
    }

    set fullName(name) {
        let [ firstName, lastName ] = name.split(' ')
        this.firstName = firstName
        this.lastName = lastName
    }
}

Person class is a plain old constructor function. When instantiated with new keyword, it will create a brand new object. If you look into dist/Person.js you will see how the ES6 syntax has been translated to ES5. That's a lot more code and it's definitely harder to read!

Person class has a method friendsWith which accepts any number of friends and adds them to array using two new features: Rest arguments and for..of loop.

Person has also getter and setter methods for fullName. Getter uses the new template strings which can interpolate variables in the string. Setter method uses destructuring.

We now have the Person class which we can import using the new modules feature in the src/main.js

import Person from './Person.js'

let walter = new Person('Walter', 'White')
let jesse = new Person('Jesse', 'Pinkman')
let hank = new Person('Hank', 'Schrader')
let saul = new Person('Saul', 'Goodman')

walter.friendsWith(jesse)
walter.friendsWith(hank, saul)

// loop through Walter's friends
for (let friend of walter.getFriends()) {
    console.log(`${ walter.fullName } friends with ${ friend.fullName }`)
}
// Walter friends with Jesse Pinkman
// Walter friends with Hank Schrader
// Walter friends with Saul Goodman

walter.fullName = 'Mr. Heisenberg'
console.log(walter.firstName) // Mr. Heisenberg

In the first line we use import statement which will look for the Person.js file. In the next lines we create 4 people and assign them as let variables. After that we can use our Person.friendsWith method to assign friends to our character and use for..of once again to print out Walter's friends. Finally, we can use the setter method to change Walt's name. That's it, clean, nice and simple.

I hope that you find the new ES6 features useful as I did. Big thanks goes to @sebmck for his work on Babel.js!

Source code

The examples are available at my es6-today-with-babel repository.


Resources:

user

Marcin Kumorek

http://qmmr.me

Front-end Hacker, JavaScript maniac, Sublime Text and Vim user, addicted to cookies who loves travelling and contemplating about the endless Universe.