ECMAScript 2015

An overview

by

In the browsers, and on the servers too,

in a not too far future ...

It is a period of fatigue for javascripter around the world. While underscore and lodash fight each other for the domain of the market of utility library, new frameworks, and new tools come out at an increasing pace.

With the hope to bring order, and long awaited features into the language, a group of people, called TC39 group, meet secretly to define the new ES6 standard. But their plans go stolen and @sebmck creates Babel, a transpiler library that makes available almost all the new features in ES5 environment.

At this point the hype around the new features quickly increases; recruiters around the world immediately set out in search of people with 5+ yrs of experience with ES6. It's June 2015 when the new features are finally added into the standard, ECMAScript 2015.

Object Literals Shorthand

It's just sintactic sugar for Object Literals.


var v = 42, propertyName = 'count'
function fn() { console.log(v); }

// the old way
var obj = { v: v, fn: fn, fn2: function() { /*...*/ } }
obj[propertyName] = 10

// es6 shorthand \O/
var obj = {
  v,
  fn,
  fn2() { /*...*/ },
  [propertyName]: 10
}

Destructuring

Allows to extract values from object and array using patterns.


var { v: value, fn: log } = obj
console.log(value) // 42

// destructuring + object literal shorthand
var { v, fn } = obj
console.log(v) // 42

// it works with array too!
var [name, extension] = 'me.jpeg'.split('.')
console.log(extension) // jpeg

// ... and support default values
var [name, extension = ''] = 'LICENSE'.split('.')
console.log(extension) // ''

Rest & Spread Operator

The Spread operator turns an array into consecutive arguments in a function call. The Rest operator binds trailing parameters to an array.


// spread
var date = [2015, 11, 25]

var LastChristmas = Function.prototype.bind.apply(Date, [null].concat(date))
var christmas = new LastChristmas // Fri Dec 25 2015 ... ಥ_ಥ

// Could it be a little simpler? Spread operator to the rescue!
var christmas = new Date(...date)


// rest
var [winner, ...theOthers] = ['a', 'b', 'c'];

console.log(theOthers instanceof Array); // true
console.log(theOthers.length); // 2

Super-powered functions

Default parameters.


function repeat(msg, time = 2) {
  return msg.repeat(time);
}

repeat('yo'); // yoyo

Super-powered functions

Varargs (or rest parameters)


function resize(width, height, ...elems){
  console.log(elems);
}

resize(100, 100, '#box', '#photo'); // ['#box', '#photo']

// no need for arguments!

function fn(...args){
  console.log(args);
}

fn(); // []
fn(42, 'bho!'); // [42, 'bho!']

Block Scoped variables

Block scoped variable assignments with let and const.
> Organized code!


// let creates a block scoped variable

if(true){
  let v = 42;
}

console.log(v); // ReferenceError: v is not defined


// constants (they're block scoped too!)

const pi = 3.14156;
pi = 3.14; // SyntaxError: invalid assignment to const pi

Arrow Functions

Function shorthand with arrow syntax, and more...


[1,2,3].reduce(function(a, b) { return a+b; });

// vs.

[1,2,3].reduce((a,b) => a+b);

... However arrow functions are not about less typing.

Arrow Functions

... arrow functions share the same context/arguments with their surrounding code;
the context can’t be modified via call, apply nor bind.


var team = {
  name: 'Justice League',
  people: ['Batman', '...'],
  logMember() {
    // arrows have the same context (this) of their surrounding code.
    this.people.forEach(x => console.log(x + ' is member of the ' + this.name))
  }
}

team.logMember() // Batman is member of the Justice League
      

Class sugar

ES6 classes are a simple sugar over the prototype-based Object Oriented pattern.


class Animal {

  constructor(name) {
    this.name = name
  }

  getName() {
    return this.name
  }

}

var pet = new Animal('foo')

pet instanceof Animal // true
pet.getName() // foo

class Fish extends Animal {

  constructor(name){
    // execute Animal's constructor
    super(name)
    this.domain = 'water'
  }

  getName() {
    return super.getName() + ', the fish.'
  }

  static canSwim() {
    return true
  }

}

Fish.canSwim() // true

var fish = new Fish('nemo')

fish instanceof Animal // true
fish instanceof Fish // true
fish.getName() // nemo, the fish.

Modules

A standard module system for JavaScript.


// utils.js
export function decode(str) { /*...*/ }
export function encode(str) { /*...*/ }

// main.js
import * as helper from 'utils';

utils.encode('foo');

Template Strings

String interpolation that do not sucks.


var cssClass = 'visible';
var content = 'Hello, world!';

// old

var str = '<p class="'+cssClass+'">'+content+'</p>';

// welcome template string

var str = `<p class='${cssClass}'>${content}</p>`;

// backtick is ALT+96
// progressive enhancement -_-

JavaScript has not private object property

ECMAScript 6 proposal
Object can have non-string private property

A new primitive type was created for this purpose, Symbol

* At the end, the requisite of privateness for Symbol properties was dropped.
Symbolic properties are enumerable, but do not show up in a for .. in loop

Symbol

A new primitive type.


var s = Symbol(); // Symbol()
typeof s === "symbol" // true


var s1 = Symbol("s1");
var s2 = Symbol("s1");

s1 === s2 // false

for ..of is a new loop construct.
It allows to loop over the values of an iterable collection.

A collection is iterable if has a symbol property Symbol.iterator,
that returns an iterator.

An iterator is an object that define a next method,
that returns a { done, value } tuple.

Iterators & for ..of

for ..of loops over values of an iterable collection.


var collection = ["a", "b", "c", "d", "e", "f", "g"];

for(value of collection){
  console.log(value);
}

// "a", "b", "c", "d", "e", "f", "g"

// custom iteration
collection[Symbol.iterator] = function() {
  var index = 0;
  return {
    next: () => {
      if (index < this.length) {
        let obj = { done: false, value: this[index] };
        index = index + 2;
        return obj;
      } else {
        return { done: true };
      }
    }
  }
}

for(value of collection){
  console.log(value);
}

// "a", "c", "e", "g"

Generator

It's a function that can be interrupted, and then eventually resumed.
They're great to create iterators.


collection[Symbol.iterator] = function* () {
  for (let i = 0; i < this.length; i++) {
    if (i%2 === 0) yield this[i];
  }
};

for(value of collection){
  console.log(value);
}

// "a", "c", "e", "g"

The yield operator is used to interrupt the execution;
the execution resumes when the iterator's method method is called.

Set

An ordered collection with no duplicates.


var arr = [1, 2, 2, 3, 3, 3, 4];
var set = new Set(arr);

set; // Set {1, 2, 3, 4}

Set has a rich prototype that expose methods to work with the set instance.

Map

An ordered collection of { key, value } tuples, without duplicated keys.


var arr = [ [1, "first"], [1, "one"], [2, "two"] ];
var map = new Map(arr);

map; // Map { 1: "one", 2: "two" }

Map has a rich prototype that expose methods to work with the map instance.

Proxies

Allows to intercept, and re-implement, operations executed over an object.


var obj = { v: 42 };
var traps = {
  set(target, propKey, value, receiver) {
    console.log('SET '+propKey+'='+value);
    target[propKey] = value;
  }
};

var proxy = new Proxy(obj, traps);
proxy.v = 0; // SET v=0

Promises

Execute asynchronous code like if it’s synchronous.


function getJSON() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve('{"value": 42}');
    }, 500);
  });
}

getJSON().then(function(resp) {
  console.log("success", resp);
});

Reflection

There is a new built-in object, Reflect, that provides methods for interceptable JavaScript operations.


var obj = { v: 42 };
var proxy = new Proxy(obj, {
  set(target, propKey, value, receiver) {
    console.log('SET '+propKey+'='+value);
    Reflect.set(target, propKey, value, receiver);
  }
});

Did you like this?

//kangax.github.io/compat-table/es6/

2015: This is not a problem!

Transpile
all the things

Grazie!