An Intro To ES6

107
ES6: An Intro

Transcript of An Intro To ES6

ES6: An Intro

Grant Skinnergskinner.com@gskinner

This Talk:- brief intro to ES6- getting started / workflow- glance at some new features- a whole lotta code- maybe some Q&A if I’m fast

what is ES6?

ECMA-262 Edition 6

ECMAScript 6

ECMAScript 2015

JavaScript Next

1995 Mocha / LiveScript Prototype

1996 JavaScript in Netscape Navigator

1997 ECMA-262 "ECMAScript"

1998 V2: editorial

1999 V3: regex, try/catch

1999 </progress>

2003 V4: drama, mothballed

2008 V4v2: drama, incinerated

2009 V3.1: strict, json, reflection5

2015 V6: biggest JS update ever!

designed by committees of committees

backwards (in)compatibility

compromise

a heap of syntactic sugar

a dollop of architectural features

a sprinkling of new functionality

getting started

ES6 is a superset of ES5 learn / apply progressively

dependent on broad support by deployment environments

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

transpilers

convert code from one language to another (es6 —> es5)

abstracts production code vs deployed code (source maps help)

introduce additional setup complexity & time (minor, but noticeable)

cannot transpile genuinely new features (weak maps, symbols, etc)

the best of both worlds with gulp / grunt (write now, deploy later)

DEMOtarget

gulp workflow:github.com/gskinner/es6gulp

JSFiddle.net

some easy ones

let + consttarget

var a = "outer";let b = "outer";

if (true) {var a = "block";let b = "block";

}

console.log(a); // "block"console.log(b); // "outer"

let b = "outer";

if (true) { console.log(b); // "outer"}

console.log(a); // undefinedvar a = "foo";

console.log(b); // error! not definedlet b = "bar";

// activation objects:

for (var i=0; i<9; i++) { let j=i; setTimeout(function() { console.log(i, j); }, i);}

// 9,0// 9,1// 9,2 etc.

const RED = "red";RED = "green"; // fails silently!console.log(RED); // "red"

const RED = "blue"; // error! already defined

string templates

var str = "template";var tstr = `${str} ${typeof str}s rock!`;// "template strings rock!"

var foo = `hello there ${name}. Welcome to ${getLocation()}, we hope you enjoy your stay!`;

var foo = `hello there ${name}.Welcome to ${getLocation()},we hope you enjoy your stay!`;

class Foo {function bar() {

var foo = `hello there ${name}.Welcome to ${getLocation()},we hope you enjoy your stay!`;}

}

var _ = "\n";var foo = `hello there ${name}.${_}Welcome to ${getLocation()},${_}we hope you enjoy your stay!`;

function dedent(str) { var lines = str.split("\n"); var indent = lines[1].match(/^\s+/); if (!indent) { return str; } var r = new RegExp("^"+indent); lines.forEach((v,i,a)=>a[i]=v.replace(r,"")); return lines.join("\n");}

var foo = dedent(`hello there ${name}. Welcome to ${getLocation()}, we hope you enjoy your stay!`);

/*SEE ALSO:- improved unicode support- regexp y & u flags- octal & binary literals*/

functions

arrow functions

function(a, b) {return a + b;

}

// es6:(a, b) => {return a + b;

}

1. less typing

function(a, b) {return a + b;

}

// es6:(a, b) => {return a + b;

}

function(a, b) {return a + b;

}

// es6:(a, b) => a + b;

r => pi*r*r;

() => Math.random()*360;

(a,d) => ({x:Math.cos(a)*d, y:Math.sin(a)*d});

arr.sort((a,b) => a-b);

oldFolk = folk.filter(o => o.age > 35);

myDiv.onclick = evt => console.log(evt.clientX);

2. lexical scoping

var _this = this;setInterval(function() { _this.seconds++ }, 1000);

// es6:setInterval(()=>this.seconds++;, 1000);

this.uiPanel.upBtn.onclick = ()=>this.rocket.y--;

default params

function sum(a, b) {if (b == null) { b = 0; }return a+b;

}

// es6:function sum(a, b=0) {return a+b;

}

function test(a, b=1, c=2) {console.log(a, b, c);

}

test(20, undefined, 5); // "20, 1, 5"

function scale(scaleX=1, scaleY=scaleX) {// etc.

}

function rotate(angle=Math.random()*360) {// etc.

}

function translate(x=this.tx, y=this.ty) {// etc.

}

rest

sum(2, 5, 9, 17);

// es5:function sum(num) {for (var i=arguments.length-1; i>=1; i--) {num += arguments[i];

}return num;

}

// es6:function sum(...nums) {return nums.reduce((a,b)=>a+b);

}

function.name

function foo() {}foo.name; // "foo"

var bar = function() {}bar.name; // "bar"

let baz;baz = ()=>{};baz.name; // "baz"

spread

var neutralNames = ["kelly", "jordan"]var boyNames = ["thor", "grant", ...neutralNames];var girlNames = ["sarah", ...neutralNames, "sue"];

var list = ["john", "jane"]inject(nameList, 1, "bob", "sue");

function inject(list, index, ...items) {list.splice(index, 0, ...items);

}

destructuring

function polarToXY(a, d) { a *= Math.PI/180; return [Math.cos(a)*d, Math.sin(a)*d];}

var [x,y] = polarToXY(30,100);console.log(x,y); // 86, 49

var [,y] = polarToXY(30,100);console.log(y); // 49

function polarToXY(a, d) { a *= Math.PI/180; return {x: Math.cos(a)*d, y: Math.sin(a)*d};}

var {x,y} = polarToXY(30,100);console.log(x,y); // 86, 49

var {x:x1, y:y1} = polarToXY(30,100);console.log(x1,y1); // 86, 49

let {name, email, phone="n/a"} = getUser(id);

var a=1, b=2;[a,b] = [b,a] // swap values!console.log(a,b); // 2, 1

object literals

const PROP_NAME = "foo";var position = 20;var obj = {__proto__: new Bar(),

position, // position:position

advance(delta=0) {this.position += delta;

},

[PROP_NAME]: 20};

classes

class Circle extends Shape {constructor(color, x=0, y=0, radius=Circle.DEF_RADIUS) {x = Math.round(x);super(color, x, y);this.radius = radius;

}

draw() {// … draw circle …super.fill();

}

get area() { return Circle.getArea(this.radius);}

static getArea(radius) { return Math.PI*radius*radius; }}Circle.DEF_RADIUS = 10;

YAY!

/*SEE ALSO:- modules (module loader)- generator methods- promises- new.target*/

one more

if we have time?

maps

this.user = new User("Scrooge", "McDuck");// ... netData = new Map();netData.set(user, {NETDATA});// ...netData.get(user); // NETDATA

this.user = new User("Scrooge", "McDuck");// ... netData = new Map();netData.set(user, {NETDATA});// ...netData.get(user); // NETDATA

weak maps

this.user = new User("Scrooge", "McDuck");// ... netData = new WeakMap();netData.set(user, {NETDATA});// ...netData.get(user); // NETDATA

this.user = new User("Scrooge", "McDuck");// ... netData = new WeakMap();netData.set(user, {NETDATA});// ...netData.get(user); // NETDATA

/*SEE ALSO:- Set & WeakSet- Symbol- Proxy*/

/*MISSED ANYTHING?- reflect APIs- for…of & iterators- tail call optimizations- typed arrays- function.name- new String, Math, Object, Number, Array APIs- subclassable built-ins*/

in summary

ES6 is here, and you should learn it.

You can learn and apply it iteratively.

Use a transpiler for client-side code.

Most features are syntactic sugar, but still nice.Use them responsibly!

A few new bits too, but wait to use them.

we’re done!

thanks!@gskinner

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

2ality.com/2015/02/es6-classes-final.html

babeljs.io/docs/learn-es2015/

developer.mozilla.org/en-US/docs/Web/JavaScript

github.com/gskinner/es6gulp

jsfiddle.net