Understanding ES6

Kelvin Ma
2 min readJul 17, 2016

Been writing a lot of JS code late at work. Before I started my Codecademy I found JS code to be difficult to read given the oddities of the language. ES6 (ES2015) cleans up a lot of it and we can take advantage of the new features through babel compiler.

This post will cover a few new features and explain what they are by showing the ES6 code and the resulting JS code.

Babel compiler with Stage 3 config

Export

Exporting is finally a part of the language. You can either use default export to export 1 value:

export default function() {
return 1;
}
// import
import f from 'lib'

Or export multiple values

let a = function() {
return 1;
}
let b = function() {
return 2;
}
export {
a,b
}

Which is just:

var a = function a() {
return 1;
};
var b = function b() {
return 2;
};
exports.a = a;
exports.b = b;

Then you’d use it by:

import { a, b} from ‘lib’ //prev file was lib.js

Const

ES6 also introduces ‘const’ keyword to declare a read-only reference to a value. Note the referenced object value can change but the reference cannot. But what does it compile?

const a = 2;// becomesvar a = 3;

So it’s just var! What happens if we try to assign it a new value? See that result here.

Babel will throw an error and refuse to compile.

Class and arrow function

Arrow function is a shorter syntax for declaring anonymous functions with the added advantage of binding ‘this’ to the enclosing context.

So

foo() {
return () => {
this.x;
}
}

Turns into:

function foo() {
var _this = this;
return function () {
_this.x;
};
}

You no longer have to do ‘var that = this’ yourself or bind on each function.

See the full example with class here

Default parameters

Finally you can declare default values for parameters, note in JS you don’t need to place params with default values last in the argument list unlike python for example.

so you can do

function foo(a = 1, b) {
return a + b;
}

which turns into

function foo() {
var a = arguments.length <= 0 || arguments[0] === undefined ? 1 : arguments[0];
var b = arguments[1];
return a + b;
}

There are more features that came with ES6 and supported by babel. (like tail recursion!), check them out at https://github.com/lukehoban/es6features#tail-calls.

Enjoy!

--

--