Top Banner
Introduction to ES6 Introduction to ES6 Tommy Cresine
18

Introduction to ES6 with Tommy Cresine

Jul 16, 2015

Download

Software

Movel
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Introduction to ES6 with Tommy Cresine

Introduction to ES6Introduction to ES6Tommy Cresine

Page 2: Introduction to ES6 with Tommy Cresine

What is ECMAScript?What is ECMAScript?

ECMAScript is the underlying core language of JS. The features for ES are defined in a standard knownas ECMA-262. Supersets of ES including Node.js, io.js, and client-sideJS add capabilities on top of the core capabilities. ES6 also known as ECMA Script Harmony is the latestversion and reached completion in 2014.

Page 3: Introduction to ES6 with Tommy Cresine

Current Compatibility Current Compatibility BrowsersBrowsersFF 36 - 65%

Chrome 41 - 45%IE 11 - 15%

RuntimesRuntimesio.js - 43%

Node - 25%PJS - 5%

Compilers & PolyfillsCompilers & PolyfillsBabel + core-js - 76%

Traceur - 64%Closure - 33%

es6-shim - 21%JSX- 16%

TypeScript- 9%

Page 4: Introduction to ES6 with Tommy Cresine

Object Literal ChangesObject Literal Changes

let first = 'John';let last = 'Doe';

let obj = { first, last };

// equivalent tolet obj = { first: first, last: last };

Property Value Shorthands

Method Definitionslet obj = { myMethod() { return 'foo'; }};

//equivvar obj = { myMethod: function() { return 'foo'; }};

let propKey = 'foo'; let obj = { [propKey]: true, ['b'+'ar']: 123};

Computed Property Keys

let obj = { ['f'+'oo']() { return 'bar'; }};

console.log(obj.foo()); // bar

Page 5: Introduction to ES6 with Tommy Cresine

ClassesClasses// Superclassclass Person { constructor(name) { this.name = name; } describe() { return 'Person called ' + this.name; }}

// Subclassclass Employee extends Person { constructor(name, title) { super(name); this.title = title; } describe() { return super.describe() + ' (' + this.title + ')'; }}

//Subclass built-in classesclass AppError extends Error { ...}

Page 6: Introduction to ES6 with Tommy Cresine

Arrow FunctionsArrow Functions// More compact syntaxlet arr = [1, 2, 3];let squares = arr.map(x => x * x);

// `this` is picked up from surroundings (lexical)// Therefore: no more `that = this` or bind()function UiComponent {

let button = document.getElementById('myButton'); button.addEventListener('click', () => { console.log('CLICK'); this.handleClick(); // lexical `this` });}

Page 7: Introduction to ES6 with Tommy Cresine

ModulesModules// lib.jsexport const sqrt = Math.sqrt;export function square(x) { return x * x;}export function diag(x, y) { return sqrt(square(x) + square(y));} // main.jsimport { square, diag } from 'lib';console.log(square(11)); // 121console.log(diag(4, 3)); // 5

Page 8: Introduction to ES6 with Tommy Cresine

Variables, Assigning & ParamsVariables, Assigning & Params// block-scoped let (write) const (read)function order(x, y) { if (x > y) { let tmp = x; x = y; y = tmp; } // ReferenceError: tmp is not defined console.log(tmp===x); return [x, y];}

//spread operatorlet arr = [-1, 7, 2];// 7let highest = Math.max(...arr);

// 2011, December 24, 00:00new Date(...[2011, 11, 24]) // Non-destructively concatenate elements// [-1, 7, 2, 9, -6]let arr2 = [...arr, 9, -6];

//default param valuesfunction initGrid(x=0, y=0) { // ...}

//destructuringlet obj = { first: 'Jane', last: 'Doe' };// f = 'Jane', l = 'Doelet { first: f, last: l } = obj;

//named params/optionsclass Person { ... displayName({ first: this.fname, last: this.lname } = {}) { ... }

}

let person = new Person();person.displayName({ first: 'Joe', last: 'Dirt' });person.displayName({ last: 'Smith' });

//rest paramsfunction foo(pattern, ...params) { return params;}// [1, 2]console.log(foo('bar', 1, 2));

Page 9: Introduction to ES6 with Tommy Cresine

Iterators, Loops & GeneratorsIterators, Loops & Generators//for-of looplet arr = ['foo', 'bar', 'baz'];

for (let element of arr) { console.log(element);}/* Output: foo bar baz*/ for (let [index,element] of arr.entries()) { console.log(`${index}. ${element}`);}/* Output: 0. foo 1. bar 2. baz*/

// Generator function, iterating over objfunction* objectEntries(obj) { for (let key of Reflect.ownKeys(obj)) { // pause and return a value yield [key, obj[key]]; }}

let obj = { first: 'Jane', last: 'Doe' };

for (let [key,value] of objectEntries(obj)) { console.log(`${key}. ${value}`);}

/* Output: first. Jane last. Doe*/

Page 10: Introduction to ES6 with Tommy Cresine

Template StringsTemplate Strings

let name = 'Jane';let str = `Hi ${name}! 3 plus 4 is ${3+4}`;

let text = `This is a textthat spansmultiple lines.`;

//use tags and tag handlerssafehtml`<a href="${url}">${text}</a>`

Page 11: Introduction to ES6 with Tommy Cresine

SymbolsSymbolslet obj = { data: [ 'hello', 'world' ], [Symbol.iterator]() { const self = this; let index = 0; return { next() { if (index < self.data.length) { return { value: self.data[index++] }; } else { return { done: true }; } } }; }};

for (let x of obj) { console.log(x);}// Output:// hello// world

Page 12: Introduction to ES6 with Tommy Cresine

ProxiesProxieslet target = {};let handler = { get(target, propKey, receiver) { console.log('get ' + propKey); return 123; }};let proxy = new Proxy(target, handler);

/** In console **/> proxy.foo get foo 123

Page 13: Introduction to ES6 with Tommy Cresine

Utility MethodsUtility Methods//Object.assignclass Point { constructor(x, y) { Object.assign(this, { x, y }); // ES6: { x, y } is abbrev. for { x: x, y: y } }}

//Array.prototype.findIndex> [6, 8, -5].findIndex(x => x < 0) 2> [6, 8, 5].findIndex(x => x < 0) -1

//Array.prototype.fill> ['a', 'b', 'c'].fill(7) [ 7, 7, 7 ]> new Array(3).fill(7) [ 7, 7, 7 ]

//new String methods> 'hello world'.startsWith('hello') true> '*'.repeat(5) '*****'

Page 14: Introduction to ES6 with Tommy Cresine

CollectionsCollections/** Arbitrary values Map keys **/ > let obj = {};> let map = new Map(); > map.set(obj, 123);> map.get(obj) 123> map.has(obj) true> map.delete(obj); true> map.has(obj) false

/** Sets are unique collections **/let arr = [5, 1, 5, 7, 7, 5];let unique = [...new Set(arr)]; // [ 5, 1, 7 ]

Page 15: Introduction to ES6 with Tommy Cresine

PromisesPromisesfunction httpGet(url) { return new Promise( function (resolve, reject) { var request = new XMLHttpRequest(); request.onreadystatechange = function () { if (this.status === 200) { // Success resolve(this.response); } else { // Something went wrong (404 etc.) reject(new Error(this.statusText)); } } request.onerror = function () { reject(new Error( 'XMLHttpRequest Error: '+this.statusText)); }; request.open('GET', url); request.send(); });}//implementationhttpGet('http://site.com/route').then( response => { console.log('Contents: ' + response); }, error => { console.error('Something went wrong', error); });

Page 16: Introduction to ES6 with Tommy Cresine

Using ES6 NowUsing ES6 NowNode v0.12.x using --harmony flagio.js v1.x ships with stable ES6 featuresAngularJS 2.0Aurelia FrameworkBabel ES6 to ES5 transpiler

Page 17: Introduction to ES6 with Tommy Cresine

Aurelia FrameworkAurelia Framework

Next generation JS client-side frameworkfeaturing Web Components, ES6 andmore.

Written with ES6 & ES7, no dependencies exceptpolyfills.Modular architecture: use-at-will or as full-featured.MV* with conventions over configuration.Dependency Injection ContainerAdvanced Routing / Child RoutingGulp Dev Pipeline & JSPM client-side packages

Page 18: Introduction to ES6 with Tommy Cresine

Thank YouThank You