Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
ES6
Agenda
1. Why & How
2. ES6 features
Why & How
1
gulp.src('src/static/js/**/*.js')
.pipe(babel())
.pipe(uglify())
.pipe(gulp.dest('dist/static/js/'))
ES6 features
2
Arrows
Feature
Arrows
• Function shorthand
• Syntax: =>
• Lexical this
Arrows
var odds = evens.map(v => v + 1);
//=>
var odds = evens.map(function(v) {
return v + 1;
});
Arrows: Lexical this
var bob = {
_name: "Bob",
_friends: [],
printFriends: function() {
this._friends.forEach(f =>
console...
Enhanced Object Literals
Feature
Enhanced Object Literals
var obj = {
handler,
toString() {
return "d " + super.toString();
}
}
Classes
Feature
Classes
• Just syntactic sugar
• Still a prototypal system
• Compiles to:
• IIFE
• c.prototype = Object.create(p.prototype...
Classes
class SkinnedMesh extends THREE.Mesh {
constructor(geometry, materials) {
super(geometry, materials);
this.idMatri...
Template Strings
Feature
Template Strings
// Multiline strings
`In ES6 this is
now legal.`
// String interpolation
var name = "Bob", time = "today"...
Destructuring
Feature
Destructuring: List matching
var [m, d, y] = [3, 14, 1977];
//=>
var m = 3,
d = 14,
y = 1977;
Destructuring: Object matching
var {op, lhs, rhs} = getASTNode();
//=>
var _ast = getASTNode();
var op = _ast.op,
lhs = _a...
Destructuring: Parameter position
function g({name: x}) {
console.log(x); //=> 5
}
g({name: 5})
Default, Rest, Spread
Feature
Default parameter values
function f(x, y=12) {
return x + y;
}
f(3) //=> 15
Rest: Trailing parameters
function f(x, ...y) {
return x * y.length;
}
f(3, "hello", true) //=> 6
Spread array values
function f(x, y, z) {
return x + y + z;
}
f(...[1,2,3]) //=> 6
Let & Const
Feature
let is the new var
Block scoping
{
let x = 2;
x; //=> 2
}
x; //=> undefined
Block scoping
for (let i = 0; i < 10; i++) {
console.log(i * 10);
}
i; //=> undefined
Const
pi + 2; //=> Not defined error
const pi = 3.14;
pi = 3.15; //=> Silent fail
const obj = { 'a': 'b' };
obj = 3; //=> ...
Symbols
Feature
Symbols: Private data
var MyModule = (function() {
var myKey = Symbol();
function MyModule(private) {
this[myKey] = privat...
Iterators & For..Of
Feature
Iterator
• An object that has a method with key:
Symbol.iterator
• That method returns an object with a next()
method
• Th...
Iterator: example
Counter[Symbol.iterator] = function() {
let step = 0;
return {
next() {
return {value: step+1, done: fal...
Iterator: Array
let arr = ['a', 'b', 'c'];
let iter = arr[Symbol.iterator]();
iter.next() //=> { value: 'a', done: false }...
For…Of
• A way of iterating an iterator
• But nothing else!
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 ar...
Generators
Feature
Generator
• An Iterator factory
• A function that can be paused and resumed
• Syntax: function* myFn() {}
• Syntax: yield
...
Generator
function* idMaker() {
var index = 0;
while(true)
yield index++;
}
var gen = idMaker();
gen.next().value //=> 0
g...
Looks sync, is async
co(function* () {
let [croftStr, bondStr] = yield Promise.all([
getFile('http://server.co/croft.json'...
Modules
Feature
Modules
// lib/math.js
export function sum(x, y) {
return x + y;
}
export var pi = 3.141593;
// app.js
import * as m from ...
Module Loader
Feature
Module Loader
System
.import('lib/math')
.then(function(m) {
alert("2π = " + m.sum(m.pi, m.pi));
});
Map, Set
WeakMap, WeakSet
Feature
Map
• Associative Collection
• Keys can be any variable type
• Iterable
• Unordered
Map: example
let map = new Map();
map.set('foo', 123);
map.size //=> 1
map.get('foo') //=> 123
map.has('foo') //=> true
ma...
WeakMap
• Associative Collection
• Keys must be objects
• Keys not prevented from garbage-collection
• Same API as Map
• N...
Set
• Collection of uniques
• No keys, just values
• Iterable
• Unordered
Set: example
let set = new Set(['red', 'green', 'blue']);
set //=> Set {'red', 'green', 'blue'}
WeakSet
• Collection of uniques
• No keys, just values
• Keys not prevented from garbage-collection
• Same API as Set
• No...
Proxies
Feature
Proxying an object
var target = {};
var handler = {
get: function(receiver, name) {
return `Hello, ${name}!`;
}
};
var p =...
Proxying a function
var target = function() { return 'target'; };
var handler = {
apply: function(receiver, ...args) {
ret...
Subclassable Built-ins
Feature
Array, Date, Element, etc.
class MyArray extends Array {
constructor(...args) {
super(...args);
}
}
Standard library
Features
Stdlib: Number
Number.EPSILON
Number.isInteger(Infinity) //=> false
Number.isNaN("NaN") //=> false
Stdlib: String
"abcde".includes("cd") //=> true
"abc".repeat(3) //=> "abcabcabc"
Stdlib: Math
Math.acosh(3) //=> 1.762747174039086
Math.hypot(3, 4) //=> 5
Math.imul(16, 16) //=> 256
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]...
Binary & Octal Literals
Feature
Binary & Octal Literals
0b111110111 === 503 //=> true
0o767 === 503 //=> true
Promises
Feature
Promises
function timeout(duration = 0) {
return new Promise((resolve, reject) => {
setTimeout(resolve, duration);
})
}
ti...
Reflect API
Feature
Reflect API
Reflect.get(target, name, [receiver])
Reflect.set(target, name, value, [receiver])
Reflect.has(target, name) /...
Tail Calls
Feature
Recursion
function factorial(n, acc = 1) {
if (n <= 1) return acc;
return factorial(n - 1, n * acc);
}
factorial(6) //=> 7...
Recursion
factorial(6) // allocate memory and save state
6 * factorial(5) // allocate memory and save state
6 * (5 * facto...
factorial(600000)
Tail Calls
function factorial(n, acc = 1) {
if (n <= 1) return acc;
return factorial(n - 1, n * acc);
}
factorial(100000)
Have fun!
Questions?
ES6 with Babel.js
ES6 with Babel.js
ES6 with Babel.js
ES6 with Babel.js
ES6 with Babel.js
ES6 with Babel.js
Upcoming SlideShare
Loading in …5
×

ES6 with Babel.js

1,541 views

Published on

Babel will turn your ES6+ code into ES5 friendly code, so you can start using it right now without waiting for browser support.

This presentation will walk you through new ES6 features.

Published in: Internet
  • Be the first to comment

ES6 with Babel.js

  1. 1. ES6
  2. 2. Agenda 1. Why & How 2. ES6 features
  3. 3. Why & How 1
  4. 4. gulp.src('src/static/js/**/*.js') .pipe(babel()) .pipe(uglify()) .pipe(gulp.dest('dist/static/js/'))
  5. 5. ES6 features 2
  6. 6. Arrows Feature
  7. 7. Arrows • Function shorthand • Syntax: => • Lexical this
  8. 8. Arrows var odds = evens.map(v => v + 1); //=> var odds = evens.map(function(v) { return v + 1; });
  9. 9. Arrows: Lexical this var bob = { _name: "Bob", _friends: [], printFriends: function() { this._friends.forEach(f => console.log(this._name, f)); } }
  10. 10. Enhanced Object Literals Feature
  11. 11. Enhanced Object Literals var obj = { handler, toString() { return "d " + super.toString(); } }
  12. 12. Classes Feature
  13. 13. 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.
  14. 14. Classes class SkinnedMesh extends THREE.Mesh { constructor(geometry, materials) { super(geometry, materials); this.idMatrix = SkinnedMesh.matrix(); } update(camera) { super.update(); } }
  15. 15. Template Strings Feature
  16. 16. Template Strings // Multiline strings `In ES6 this is now legal.` // String interpolation var name = "Bob", time = "today"; `Hello ${name}, how are you ${time}?`
  17. 17. Destructuring Feature
  18. 18. Destructuring: List matching var [m, d, y] = [3, 14, 1977]; //=> var m = 3, d = 14, y = 1977;
  19. 19. Destructuring: Object matching var {op, lhs, rhs} = getASTNode(); //=> var _ast = getASTNode(); var op = _ast.op, lhs = _ast.lhs, rhs = _ast.rhs;
  20. 20. Destructuring: Parameter position function g({name: x}) { console.log(x); //=> 5 } g({name: 5})
  21. 21. Default, Rest, Spread Feature
  22. 22. Default parameter values function f(x, y=12) { return x + y; } f(3) //=> 15
  23. 23. Rest: Trailing parameters function f(x, ...y) { return x * y.length; } f(3, "hello", true) //=> 6
  24. 24. Spread array values function f(x, y, z) { return x + y + z; } f(...[1,2,3]) //=> 6
  25. 25. Let & Const Feature
  26. 26. let is the new var
  27. 27. Block scoping { let x = 2; x; //=> 2 } x; //=> undefined
  28. 28. Block scoping for (let i = 0; i < 10; i++) { console.log(i * 10); } i; //=> undefined
  29. 29. Const pi + 2; //=> Not defined error const pi = 3.14; pi = 3.15; //=> Silent fail const obj = { 'a': 'b' }; obj = 3; //=> Silent fail obj.a = 'c'; //=> Works!
  30. 30. Symbols Feature
  31. 31. Symbols: Private data var MyModule = (function() { var myKey = Symbol(); function MyModule(private) { this[myKey] = private; } return MyModule; })(); var c = new MyModule("hello");
  32. 32. Iterators & For..Of Feature
  33. 33. 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
  34. 34. Iterator: example Counter[Symbol.iterator] = function() { let step = 0; return { next() { return {value: step+1, done: false}; } }; }
  35. 35. 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 }
  36. 36. For…Of • A way of iterating an iterator • But nothing else!
  37. 37. 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 }
  38. 38. Generators Feature
  39. 39. Generator • An Iterator factory • A function that can be paused and resumed • Syntax: function* myFn() {} • Syntax: yield • Returns an Iterator internally
  40. 40. Generator function* idMaker() { var index = 0; while(true) yield index++; } var gen = idMaker(); gen.next().value //=> 0 gen.next().value //=> 1 gen.next().value //=> 2
  41. 41. 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); });
  42. 42. Modules Feature
  43. 43. 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));
  44. 44. Module Loader Feature
  45. 45. Module Loader System .import('lib/math') .then(function(m) { alert("2π = " + m.sum(m.pi, m.pi)); });
  46. 46. Map, Set WeakMap, WeakSet Feature
  47. 47. Map • Associative Collection • Keys can be any variable type • Iterable • Unordered
  48. 48. Map: example let map = new Map(); map.set('foo', 123); map.size //=> 1 map.get('foo') //=> 123 map.has('foo') //=> true map.delete('foo') //=> true map.has('foo') //=> false
  49. 49. WeakMap • Associative Collection • Keys must be objects • Keys not prevented from garbage-collection • Same API as Map • Not an Iterable • Unordered
  50. 50. Set • Collection of uniques • No keys, just values • Iterable • Unordered
  51. 51. Set: example let set = new Set(['red', 'green', 'blue']); set //=> Set {'red', 'green', 'blue'}
  52. 52. WeakSet • Collection of uniques • No keys, just values • Keys not prevented from garbage-collection • Same API as Set • Not an Iterable • Unordered
  53. 53. Proxies Feature
  54. 54. Proxying an object var target = {}; var handler = { get: function(receiver, name) { return `Hello, ${name}!`; } }; var p = new Proxy(target, handler); p.world === 'Hello, world!';
  55. 55. Proxying a function var target = function() { return 'target'; }; var handler = { apply: function(receiver, ...args) { return 'proxy'; } }; var p = new Proxy(target, handler); p() === 'proxy';
  56. 56. Subclassable Built-ins Feature
  57. 57. Array, Date, Element, etc. class MyArray extends Array { constructor(...args) { super(...args); } }
  58. 58. Standard library Features
  59. 59. Stdlib: Number Number.EPSILON Number.isInteger(Infinity) //=> false Number.isNaN("NaN") //=> false
  60. 60. Stdlib: String "abcde".includes("cd") //=> true "abc".repeat(3) //=> "abcabcabc"
  61. 61. Stdlib: Math Math.acosh(3) //=> 1.762747174039086 Math.hypot(3, 4) //=> 5 Math.imul(16, 16) //=> 256
  62. 62. 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"
  63. 63. Binary & Octal Literals Feature
  64. 64. Binary & Octal Literals 0b111110111 === 503 //=> true 0o767 === 503 //=> true
  65. 65. Promises Feature
  66. 66. Promises function timeout(duration = 0) { return new Promise((resolve, reject) => { setTimeout(resolve, duration); }) } timeout(1000) .then(() => { return timeout(2000); });
  67. 67. Reflect API Feature
  68. 68. 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)
  69. 69. Tail Calls Feature
  70. 70. Recursion function factorial(n, acc = 1) { if (n <= 1) return acc; return factorial(n - 1, n * acc); } factorial(6) //=> 720
  71. 71. 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
  72. 72. factorial(600000)
  73. 73. Tail Calls function factorial(n, acc = 1) { if (n <= 1) return acc; return factorial(n - 1, n * acc); } factorial(100000)
  74. 74. Have fun! Questions?

×