ES6/ES2015

Modern Javascript

Jan Smarschevski & Robin Gloster at TUM Javascript Technology Seminar

ES5 Recap

Short Property Notation

Short Method Notation

Trailing Commas

Let/Const

ES 5

ES 6

Functions

Arrow Functions

                                
//Syntactical difference in general

//ES5
function (arguments) { expression }

//ES6
(arguments) => { expression }
                                
                            

Arrow Functions

                            
//ES5 scope of "this"
function add() {
    this.counter = 0;

    function plus() {
        this.counter += 1;
    }
    plus();
}

var myObject = {};

myObject.add = add;
myObject.add();

//TypeError: cannot read property 'counter' of undefined
                            
                        

Arrow Functions

Arrow Functions

Arrow Functions

                                
//Arrow Functions are not "newable"
var Foo = (a) => {a + 1};
var f = new Foo(); //TypeError (a) => {a+1} is not a constructor
                                
                            

Default Parameters - ES5

Default Parameters - ES6

Default Parameters

Rest Parameters - ES5

Rest Parameters - ES6

Spread Operator - ES5

Spread Operator - ES6

for-of loop

                            
//ES5: for-in loop
var food = ["banana", "orange", "apple"];
food.NotAnIndex = "123";

for (var x in food) {
    console.log(x);
}
/*
0
1
2
NotAnIndex
*/
                            
                        
                            
//ES5: forEach()
var food = ["banana", "orange", "apple"];

food.forEach(function (entry) {
    if (entry == "orange") {
       break;
    }

    console.log(entry);
});

//Uncaught SyntaxError: Illegal break statement
                            
                        
                            
//ES5: forEach()
var food = ["banana", "orange", "apple"];

food.forEach(function (entry) {
    if (entry == "orange") {
        return;
    }

    console.log(entry);
});
/*
banana
apple
*/
                            
                        
                            
//ES6: for-of loop
var food = ["banana", "orange", "apple"];
food.NotAnIndex = "123"

for (var x of food) {
    console.log(x);
}
/*
banana
orange
apple
*/
                            
                        
                            
//ES6: for-of loop
var food = {a: "banana", b:"orange", c: "apple"};
food.NotAnIndex = "123"

for (x of food) {
    console.log(x);
}
/*
TypeError
for-of only works for iterable objects
*/
                            
                        

Destructuring

Class + Subclassing

Class

                            
//ES5
//function constructor
function Circle(radius) {
    this.radius = radius;
    Circle.circlesMade++;
}

//static property
Circle.circlesMade = 0;

//static function
Circle.draw = function draw(circle, canvas) {
    /* Canvas drawing code */
};

//instance properties/functions
Circle.prototype = {
    area() {
        return Math.pow(this.radius, 2) * Math.PI;
    },

    get radius() {
        return this._radius;
    },
    set radius(radius) {
       if (!Number.isInteger(radius))
           throw new Error("Circle radius must be an integer.");
       this._radius = radius;
    }
};
                            
                        

Class

                            
//ES6
class Circle {

    //add static property (actually already ES7)
    static circlesMade = 0;

    // instance property
    color = 'red';

    constructor(radius) {
        this.radius = radius;
        Circle.circlesMade++;
    }

    //class method
    static draw(circle, canvas) {
        // Canvas drawing code
    }

    //instance method
    area() {
        return Math.pow(this.radius, 2) * Math.PI;
    }

    //getter and setter
    get radius() {
        return this.radius;
    }

    set radius(radius) {
        if (!Number.isInteger(radius))
            throw new Error("Circle radius must be an integer.");
            this._radius = radius;
        };
    }
}
                            
                        

Subclassing

                            
//ES5
//function constructor
function Circle(radius) {
    this.radius = radius;
    Circle.circlesMade++;
}

// prototype of Circle inherits instance properties of Shape prototype
Circle.prototype = Object.create(Shape.prototype)

// Circle inherits static properties of Shape
Circle = Object.create(Shape)
                            
                        

Subclassing

                            
//ES6
class ScalableCircle extends Circle {
    constructor(scalingFactor) {
        super();
        this.scalingFactor = scalingFactor;
    }

    get radius() {
        return this.scalingFactor * super.radius;
    }

    set radius(radius) {
        throw new Error("ScalableCircle radius is constant." +
        "Set scaling factor instead.");
    }
}
                            
                        

Modules


define(['http'], function (http) {
    var toExport = {};

    return toExport;
});
                        

var http = require('http');

var toExport = {};

module.exports = toExport;
                        

import http from 'http';

var toExport = {};

export default toExport;
                        

export { named1, named2 }

// -----

import { named1, named2 } from 'module-name';
                        

Template Strings

Promises


fetch(someUrl)
    .then((response) => response.text())
    .catch((error) => handleError(error))
    .then((responseText) => console.log(responseText));
                        

let promises = [fetch(someUrl), fetch(someOtherUrl), 'string content'];

Promise.all(promises).then(function (texts) {
    texts.forEach((text) => console.log())
});
                        

let promise1 = new Promise(function (resolve, reject) {
    let value = doStuffToCreateValue();
    resolve(value);
});

let promise2 = Promise.resolve(otherValue);
                        

Overview all features

Covered Here

  • let/const
  • Arrow Functions
  • Default Parameters
  • Rest Parameters
  • Spread Operator
  • for-of Loop
  • Destructuring
  • Class + Subclassing
  • Modules
  • Template Strings
  • Promises

Other Features

  • Generators
  • Unicode
  • Map + Set + WeakMap + WeakSet
  • Proxy
  • Symbol
  • Subclassable Built-Ins
  • Math + Number + String + Array + Object APIs
  • Binary and Octal Literals
  • Reflect API

ES 7

  • Decorators
  • Bind Operator
  • async/await
  • List/Generator Comprehensions

Compatibility Table

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