Niels Dequeker

When I read what I write I learn what I think

Exploring ECMAScript 6

| Comments

On July 2nd, ECMA published a press release announcing ECMAScript® 2015. I’ve been experimenting with some of the new features of the language.

Because most of the new features aren’t supported by all browsers, the ES6 code must be transpiled to ES5 compatible code. There are a couple of tools out there which can do the job.

My setup consists of:

  • Traceur — to compile the ES6 code to ES5 code
  • Gulp — to run the webserver and trigger the compile task

The repository on GitHub contains all source code, including documentation.

I’ll describe some of the new features I’ve tried and think are worth to be shared.

New String features

Methods

New methods like startsWith() and includes() feel much more natural to work with strings. They are more readable than doing the same checks using indexOf() in ES5.

Note that these methods are case sensitive, as I found out while experimenting.

Multiline strings

It is now possible to use multiline strings, without having to concatenate each line.

1
2
`This is
valid ES2015`

String interpolation

Instead of concatenating strings and variables, code can now be more readable using string interpolation. Note that the backticks are required here.

1
2
var theAnswer = 42;
`The answer is ${theAnswer}`

Functions

Named parameters

Functions can take named parameters using ES6, which can have default values. When you execute the doGreeting() function below without passing a value, it’s default output will be Hi!

1
2
3
function doGreeting(greeting = Hi!) {
    console.log(greeting);
}

Arrow functions

This is basically a new syntax to write functions, with a few differences. The example code below defines the function sayIt(), which takes one parameter, it.

1
2
var sayIt = it => console.log(it);
sayIt('Yo');

Generators

I’ve worked with Python before, where terms as list comprehension and generators are commonly used. Good news, generators are now part of ECMAScript 6!

A simple example is the generator alphabetGenerator().

1
2
3
4
5
function *alphabetGenerator() {
    yield 'A';
    yield 'B';
    yield 'C';
}

A working example can be found on line 53 of my ES6 experiments.

Deploying ES6 code

The code generated by Traceur depends on a small runtime library containing Javascript code for things like creating classes, handling spread arguments, etc.

There is not yet a ‘One Size Fits All’ solution to compile all code during the build process. Dr. Axel Rauschmayer has written a great overview on how to deploy ECMAScript 6 code.

Comments