ES6Demo



ES6Demo

0 0


ES6Demo

Demonstration of ES6

On Github Abrissirba / ES6Demo

EcmaScript 6

Next version of JavaScript

History

  • ES3 1999
  • ES4 never released    Focused switched towards silverlight and flex
  • ES5 2009    Many new features. Focus switched back to javascript. Backbone, angular, ember etc.
  • ES6 2015

Features

  • Classes
  • Modules
  • Arrow functions
  • let + const
  • Promises

Class

  • Finally!
  • Support of inheritance and constructors
  • Syntactical sugar

Class

class View extends baseView {
	constructor(options) {
	    super(options);

	    this.model = options.model;
	    this.template = options.template;
	}

	render() {
	     return _.template(this.template, this.model.toObject());
	}
}

Modules

  • Not a new concept - CommonJS and AMD
  • Goal - split code into different files and maintain dependencies
  • Asynchronous loading

Modules example

 // lib.js 
export const sqrt = Math.sqrt;
export function square(x) {
    return x * x;
}
export function diag(x, y) {
    return sqrt(square(x) + square(y));
}

// main.js 
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5

Module Loader example

// Dynamic loading – ‘System’ is default loader
System.import('lib/math').then(function(m) {
  alert("2π = " + m.sum(m.pi, m.pi));
});

Promises

  • Used in asynchronous programming
  • Solves the problem with callback hell
//callback hell
getData(function(x){
    getMoreData(x, function(y){
        getMoreData(y, function(z){ 
            ...
        });
    });
});

Promises Example

function timeout(duration = 0) {
    return new Promise((resolve, reject) => {
        setTimeout(resolve, duration);
    })
}

var p = timeout(1000)
.then(() => {
    return timeout(2000);
}).then(() => {
    throw new Error("hmm");
}).catch(err => {
    return Promise.all([timeout(100), timeout(200)]);
})

let + const

  • let is the new var
  • let is scoped to its containg block
  • var is global inside a function
  • const works like let but can't be changed

let + const example

var a = 5;
var b = 10;

if (a === 5) {
  let a = 4; // The scope is inside the if-block
  var b = 1; // The scope is inside the function

  console.log(a);  // 4
  console.log(b);  // 1
} 

console.log(a); // 5
console.log(b); // 1

Arrow functions

  • Functions shorthands using the => syntax
  • Much like inline functions in c#
  • Share the same context as its surrounding code     No more var self = this

Arrow functions example

// Expression bodies
var odds = evens.map(v => v + 1);
var nums = evens.map((v, i) => v + i);

// Statement bodies
nums.forEach(v => {
  if (v % 5 === 0)
    fives.push(v);
});

// Lexical this
var bob = {
  _name: "Bob",
  _friends: [],
  printFriends() {
    this._friends.forEach(f =>
      console.log(this._name + " knows " + f));
  }
}

Other sessions

  • Docker
  • AngularJS 2.0
  • Stack overflow