ES6 with Babel.js

80
ES6

Transcript of ES6 with Babel.js

Page 1: ES6 with Babel.js

ES6

Page 2: ES6 with Babel.js

Agenda

1. Why & How

2. ES6 features

Page 3: ES6 with Babel.js

Why & How

1

Page 4: ES6 with Babel.js
Page 5: ES6 with Babel.js
Page 6: ES6 with Babel.js
Page 7: ES6 with Babel.js
Page 8: ES6 with Babel.js

gulp.src('src/static/js/**/*.js') .pipe(babel()) .pipe(uglify()) .pipe(gulp.dest('dist/static/js/'))

Page 9: ES6 with Babel.js

ES6 features

2

Page 10: ES6 with Babel.js

ArrowsFeature

Page 11: ES6 with Babel.js

Arrows

• Function shorthand• Syntax: =>• Lexical this

Page 12: ES6 with Babel.js

Arrows

var odds = evens.map(v => v + 1);//=>var odds = evens.map(function(v) { return v + 1;});

Page 13: ES6 with Babel.js

Arrows: Lexical this

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

Page 14: ES6 with Babel.js

Enhanced Object LiteralsFeature

Page 15: ES6 with Babel.js

Enhanced Object Literals

var obj = { handler, toString() { return "d " + super.toString(); }}

Page 16: ES6 with Babel.js

ClassesFeature

Page 17: ES6 with Babel.js

Classes

• Just syntactic sugar• Still a prototypal system• Compiles to:• IIFE• c.prototype = Object.create(p.prototype);• parent.call(this, x, y);

• Functions added to the prototype• etc.

Page 18: ES6 with Babel.js

Classes

class SkinnedMesh extends THREE.Mesh { constructor(geometry, materials) { super(geometry, materials); this.idMatrix = SkinnedMesh.matrix(); } update(camera) { super.update(); }}

Page 19: ES6 with Babel.js

Template StringsFeature

Page 20: ES6 with Babel.js

Template Strings

// Multiline strings`In ES6 this is now legal.`

// String interpolationvar name = "Bob", time = "today";`Hello ${name}, how are you ${time}?`

Page 21: ES6 with Babel.js

DestructuringFeature

Page 22: ES6 with Babel.js

Destructuring: List matching

var [m, d, y] = [3, 14, 1977];//=>var m = 3, d = 14, y = 1977;

Page 23: ES6 with Babel.js

Destructuring: Object matchingvar {op, lhs, rhs} = getASTNode();//=>var _ast = getASTNode();var op = _ast.op, lhs = _ast.lhs, rhs = _ast.rhs;

Page 24: ES6 with Babel.js

Destructuring: Parameter positionfunction g({name: x}) { console.log(x); //=> 5}

g({name: 5})

Page 25: ES6 with Babel.js

Default, Rest, SpreadFeature

Page 26: ES6 with Babel.js

Default parameter values

function f(x, y=12) { return x + y;}

f(3) //=> 15

Page 27: ES6 with Babel.js

Rest: Trailing parameters

function f(x, ...y) { return x * y.length;}

f(3, "hello", true) //=> 6

Page 28: ES6 with Babel.js

Spread array values

function f(x, y, z) { return x + y + z;}

f(...[1,2,3]) //=> 6

Page 29: ES6 with Babel.js

Let & ConstFeature

Page 30: ES6 with Babel.js

let is the new var

Page 31: ES6 with Babel.js

Block scoping

{ let x = 2; x; //=> 2}x; //=> undefined

Page 32: ES6 with Babel.js

Block scoping

for (let i = 0; i < 10; i++) { console.log(i * 10);}i; //=> undefined

Page 33: ES6 with Babel.js

Const

pi + 2; //=> Not defined errorconst pi = 3.14;pi = 3.15; //=> Silent fail

const obj = { 'a': 'b' };obj = 3; //=> Silent failobj.a = 'c'; //=> Works!

Page 34: ES6 with Babel.js

SymbolsFeature

Page 35: ES6 with Babel.js

Symbols: Private data

var MyModule = (function() { var myKey = Symbol(); function MyModule(private) { this[myKey] = private; } return MyModule;})();

var c = new MyModule("hello");

Page 36: ES6 with Babel.js

Iterators & For..OfFeature

Page 37: ES6 with Babel.js

Iterator

• An object that has a method with key:Symbol.iterator

• That method returns an object with a next() method

• The next() method keeps returning the next item

Page 38: ES6 with Babel.js

Iterator: example

Counter[Symbol.iterator] = function() {

let step = 0;

return {

next() {

return {value: step+1, done: false};

}

};

}

Page 39: ES6 with Babel.js

Iterator: Array

let arr = ['a', 'b', 'c'];

let iter = arr[Symbol.iterator]();

iter.next() //=> { value: 'a', done: false }

iter.next() //=> { value: 'b', done: false }

iter.next() //=> { value: 'c', done: false }

iter.next()

//=> { value: undefined, done: true }

Page 40: ES6 with Babel.js

For…Of

• A way of iterating an iterator• But nothing else!

Page 41: ES6 with Babel.js

For…Of

let arr = [3, 5, 7];arr.foo = "hello";

for (let i in arr) { console.log(i); //=> 0, 1, 2, "foo"}

for (let i of arr) { console.log(i); //=> 3, 5, 7}

Page 42: ES6 with Babel.js

GeneratorsFeature

Page 43: ES6 with Babel.js

Generator

• An Iterator factory• A function that can be paused and

resumed• Syntax: function* myFn() {}• Syntax: yield• Returns an Iterator internally

Page 44: ES6 with Babel.js

Generator

function* idMaker() { var index = 0; while(true) yield index++;}

var gen = idMaker();

gen.next().value //=> 0gen.next().value //=> 1gen.next().value //=> 2

Page 45: ES6 with Babel.js

Looks sync, is async

co(function* () {

let [croftStr, bondStr] = yield Promise.all([

getFile('http://server.co/croft.json'),

getFile('http://server.co/bond.json'),

]);

let croftJson = JSON.parse(croftStr);

let bondJson = JSON.parse(bondStr);

});

Page 46: ES6 with Babel.js

ModulesFeature

Page 47: ES6 with Babel.js

Modules

// lib/math.js

export function sum(x, y) {

return x + y;

}

export var pi = 3.141593;

// app.js

import * as m from "lib/math";

alert("2π = " + m.sum(m.pi, m.pi));

Page 48: ES6 with Babel.js

Module LoaderFeature

Page 49: ES6 with Babel.js

Module Loader

System .import('lib/math') .then(function(m) { alert("2π = " + m.sum(m.pi, m.pi)); });

Page 50: ES6 with Babel.js

Map, SetWeakMap, WeakSetFeature

Page 51: ES6 with Babel.js

Map

• Associative Collection• Keys can be any variable type• Iterable• Unordered

Page 52: ES6 with Babel.js

Map: example

let map = new Map(); map.set('foo', 123);

map.size //=> 1map.get('foo') //=> 123map.has('foo') //=> truemap.delete('foo') //=> truemap.has('foo') //=> false

Page 53: ES6 with Babel.js

WeakMap

• Associative Collection• Keys must be objects• Keys not prevented from garbage-

collection• Same API as Map• Not an Iterable• Unordered

Page 54: ES6 with Babel.js

Set

• Collection of uniques• No keys, just values• Iterable• Unordered

Page 55: ES6 with Babel.js

Set: example

let set = new Set(['red', 'green', 'blue']);

set //=> Set {'red', 'green', 'blue'}

Page 56: ES6 with Babel.js

WeakSet

• Collection of uniques• No keys, just values• Keys not prevented from garbage-

collection• Same API as Set• Not an Iterable• Unordered

Page 57: ES6 with Babel.js

ProxiesFeature

Page 58: ES6 with Babel.js

Proxying an object

var target = {};

var handler = {

get: function(receiver, name) {

return `Hello, ${name}!`;

}

};

var p = new Proxy(target, handler);

p.world === 'Hello, world!';

Page 59: ES6 with Babel.js

Proxying a function

var target = function() { return 'target'; };

var handler = {

apply: function(receiver, ...args) {

return 'proxy';

}

};

var p = new Proxy(target, handler);

p() === 'proxy';

Page 60: ES6 with Babel.js

Subclassable Built-insFeature

Page 61: ES6 with Babel.js

Array, Date, Element, etc.

class MyArray extends Array { constructor(...args) { super(...args); }}

Page 62: ES6 with Babel.js

Standard libraryFeatures

Page 63: ES6 with Babel.js

Stdlib: Number

Number.EPSILONNumber.isInteger(Infinity) //=> falseNumber.isNaN("NaN") //=> false

Page 64: ES6 with Babel.js

Stdlib: String

"abcde".includes("cd") //=> true"abc".repeat(3) //=> "abcabcabc"

Page 65: ES6 with Babel.js

Stdlib: Math

Math.acosh(3) //=> 1.762747174039086Math.hypot(3, 4) //=> 5Math.imul(16, 16) //=> 256

Page 66: ES6 with Babel.js

Stdlib: Array

Array.from(nodeList) //=> […]

Array.of(1, 2, 3) //=> [1, 2, 3]

[0, 0, 0].fill(7, 1) //=> [0, 7, 7]

[1, 2, 3].find(x => x == 3) //=> 3

[1, 2, 3].findIndex(x => x == 2) //=> 1

[1, 2, 3, 4, 5].copyWithin(3, 0) //=> [1, 2, 3, 1, 2]

["a", "b", "c"].entries() //=> iterator [0, "a"], …

["a", "b", "c"].keys() //=> iterator 0, 1, 2

["a", "b", "c"].values() //=> iterator "a", "b", "c"

Page 67: ES6 with Babel.js

Binary & Octal LiteralsFeature

Page 68: ES6 with Babel.js

Binary & Octal Literals

0b111110111 === 503 //=> true0o767 === 503 //=> true

Page 69: ES6 with Babel.js

PromisesFeature

Page 70: ES6 with Babel.js

Promises

function timeout(duration = 0) {

return new Promise((resolve, reject) => {

setTimeout(resolve, duration);

})

}

timeout(1000)

.then(() => {

return timeout(2000);

});

Page 71: ES6 with Babel.js

Reflect APIFeature

Page 72: ES6 with Babel.js

Reflect API

Reflect.get(target, name, [receiver])

Reflect.set(target, name, value, [receiver])

Reflect.has(target, name) //=> first class `name in obj`

Reflect.apply(target, receiver, args)

Reflect.construct(target, args) //=> apply on constructor

Reflect.getOwnPropertyDescriptor(target, name)

Reflect.defineProperty(target, name, desc) //=> return vs. throw

Reflect.getPrototypeOf(target)

Reflect.setPrototypeOf(target, newProto)

Reflect.deleteProperty(target, name) //=> first class `delete o[n]`

Reflect.enumerate(target)

Reflect.preventExtensions(target)

Reflect.isExtensible(target)

Reflect.ownKeys(target)

Page 73: ES6 with Babel.js

Tail CallsFeature

Page 74: ES6 with Babel.js

Recursion

function factorial(n, acc = 1) { if (n <= 1) return acc; return factorial(n - 1, n * acc);}

factorial(6) //=> 720

Page 75: ES6 with Babel.js

Recursion

factorial(6) // allocate memory and save state

6 * factorial(5) // allocate memory and save state

6 * (5 * factorial(4)) // allocate mem...

6 * (5 * (4 * factorial(3))) // allocate mem...

6 * (5 * (4 * (3 * factorial(2)))) // allocate mem...

6 * (5 * (4 * (3 * (2 * factorial(1))))) // allocate mem...

6 * (5 * (4 * (3 * (2 * (1 * factorial(0)))))) // allocate mem... (max depth)

6 * (5 * (4 * (3 * (2 * (1 * 1)))))

6 * (5 * (4 * (3 * (2 * 1))))

6 * (5 * (4 * (3 * 2)))

6 * (5 * (4 * 6))

6 * (5 * 24)

6 * 120

720

Page 76: ES6 with Babel.js

factorial(600000)

Page 77: ES6 with Babel.js
Page 78: ES6 with Babel.js

Tail Calls

function factorial(n, acc = 1) { if (n <= 1) return acc; return factorial(n - 1, n * acc);}

factorial(100000)

Page 79: ES6 with Babel.js
Page 80: ES6 with Babel.js

Have fun!

Questions?