ES6, ECMAScript2015

AaronFriday, March 4th 2016

What is it?

  • The Sixth Major release of the ECMAScript (Javascript) specification
    • Also Known as ES6, Harmony, ES2015, ECMAScript 6
    • First of a new living standard for Javascript
    • ECMAScript 2016 (ES7) should be finalised in June
    • The first changes to the ECMA language standards since 2009

How often should we expect changes to the standard?

The aim of the ECMA living standard is to make a release of finalised language features every 12 months, these releases should be substantially smaller than the changes made in ES6 as ES6 represents 6 years of standards.

Whats New?

ES6 adds a number of new features to the JavaScript language syntax some of which are listed bellow and most of wich can be used today through Babel.

  • Arrow Functions
  • Lexical this
  • Block Scoping (let + const)
  • Classes
  • Modules
  • Default + Rest + Spread for function arguments
  • Iterators + For..Of
  • Generators
  • Full Unicode Support
  • Map + Set + WeakMap + WeakSet
  • Proxies
  • Subclassable Builtins
  • Promises
  • String Improvements
  • Array Improvements
  • ...And more

Arrow Functions

The only difference between using arrow functions and decalring a function more traditionally is that Arrow functions will share the scope that they were defined in i.e. they have access to all of the local variables where they were defined and this inside an arrow function refers to the scope in which it was defined.

  • Very similar syntax to Java and c#
    • () => {}
    • (arg1) => {}
    • x => {}
    • x => statement
  • Syntactic sugar and shorthand for
    • function () {}
let a = [
  "Hydrogen",
  "Helium",
  "Lithium",
  "Beryl­lium"
];

//ES5
var a2 = a.map(function(s){ return s.length });

//ES6
let a3 = a.map( s => s.length );

Lexical this

This works with classes and arrow functions to allow more intuitive use of the this keyword.

  • Inside classes this refers to the class
  • Inside Objects this is the object
  • Inside arrow functions this refers to the definition context

Classes

Using classes provides a simpler way to perform prototype based inheritence and gives a much clearer view of the code intent.

  • Similar to Java and other languages
  • Defined using the class keyword
  • Can extend another class
  • Has a constructor and static or instance variables or functions
class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

Let and Const

This is probably one of the largest changes as it allows you to completely replace the var keyword with either let for normal local variables or const for readonly variables. An emerging best practice is to stop using var altogether and instead use let and const appropriately as there scope is simpler.

  • Replace var
  • let
    • The new var
    • Block scoped variable
  • const
    • single-assignment
    • read only
    • Cannot be used before assignment

Generators

These allow you to write a iterative algorithm in a single function that maintians it's own state across iterations. For example:

function* idMaker(){
  let index = 0;
  while(true)
    yield index++;
}

let gen = idMaker();

console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
// ...	
  • Yielding functions
  • defined as function*()
  • must contain a yield statement instead of return
  • good for creating infinite sequences or doing calculations on each iteration

Modules

JavaScript modules are distinct from classes as a module may contain one or more classes that may or may not be exported.

  • Allow the import of other javascript files or parts of them
  • Allow the export of an interface from a javascript file
  • Defined by the file they are in i.e. you cannot have 2 modules in one file

Module Example:

// Inside module.js
export class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

export function something(){
	//...
}

Import Example:

//Imports only the polygon class
import { Polygon } from "module.js";

Destructuring

This covers a wide range of related improvements all related to the use and handling of variables and assignments. These improvements allow you to build more flexible methods that are self describing.

Default Parameters

Default parameters allow you to specify a default value to be used if the argument is not supplied by the caller.

function test(required, controls = {}, name = "test", value = 4){ /*...*/ }

Rest Arguments

This allows functions to take an any number of arguments and aggregate them into an array, this means that you no longer have to use the args array inside a function. Note that functions can only have a single Rest argument and it must be the last argument.

function test( a, b, ...c){
	console.log(c.length);
	return (a + b) * c.length;
}

Spread Operator

This is similar to Rest arguments but for array assignment.

let b = [ "bob", "jones" ];
let a = [ 1, 2, ...b ]; // [ 1, 2, "bob", "jones"]

For Loops

For loops can take advantage of destructuring through the new For... Of... loop, this allows you to interate over an array or iterator assigning each item to a local variable.

//Take advantage of destructuring to map two variables from a key value pair
for (let [name, builder] of Object.entries(models))

//Basic for of loop
for (let x of array)

String Improvements

Strings can now have template literals removing some of the need for templating libraries like Handlebars for basic interpolation, multiline strings are also supported. In order to take advantage of new features in strings you'll need to define your strings using backticks.

  • Template literals
  • Strings enclosed in backticks ` `
    • Multiline
    • Interpolation ${identity}
    • String.Raw resolves interpolations
let customer = `Bob`;
let welcome = `Welcome ${customer}`;

let rawString = String.raw(welcome); // Welcome Bob

How can we use ES6 today?

Using ES6 today requires a transpiler, I'd recommend the use of Babel as it closely follows ECMAScript standards and is committed to supporting new standards using the same syntax as the implemented standards. Babel also allows you to enable or disable transpilation transformations using a config file which means that as browsers start to support more of the ES6 standards you can disable increasing amounts of the transpilation to benifit from native implementations.

The best way to use Babel is to integrate it with you build process, you can do this using gulp with the gulp-babel plugin. There are also plugins for most other build systems see http://babeljs.io/docs/setup/

  • Other Transpilers
    • Typescript
    • Tracur

Why use Babel?

  • Focused on ES6 standards
  • Transformers can be enabled or disabled as browsers introduce native support
  • Starting to support ES7 standards

Want to learn more?