Upgrade to Pro — share decks privately, control downloads, hide ads and more …

A Quick Intro to ES6

A Quick Intro to ES6

Avatar for Frank Lai

Frank Lai

March 16, 2018

More Decks by Frank Lai

Other Decks in Programming

Transcript

  1. History • ECMAScript 6 • Standardize by ECMA International ◦

    European Computer Manufacturers Association • Finalized in June 2015 • Also known as ECMAScript 2015
  2. History • ES 3, December 1999 • ES 4, Abandoned

    • ES 5, December 2009 ◦ JSON, Array.prototype.forEach(), ... • ES 5.1, June 2011 ◦ Just document correction of ES 5 • ES 6, June 2015 • ES 7, June 2016 ◦ Array.prototype.includes, Exponentiation operator (**) • ES 8, June 2017 ◦ await/async, Object.entries() and Object.values(), ...
  3. TC39 Process • ECMA Technical Committee 39 • Starting with

    ECMAScript 2016 (ES7) • ES6 was too large • Each proposal goes through stage 0 to stage 4 • Standard releases yearly • http://exploringjs.com/es2016-es2017/ch_tc39-process.html
  4. ES6 Feature • let/const • Template Literal • Arrow Function

    • Destructuring • Rest/Spread operator (...) • Class • ...
  5. From var to const/let • var is function-scoped • const

    and let are block-scoped var x = 3; function func(randomize) { if (randomize) { var x = Math.random(); // (A) scope: whole function return x; } return x; // accesses the x from line A } func(false); // undefined let x = 3; function func(randomize) { if (randomize) { let x = Math.random(); return x; } return x; } func(false); // 3
  6. From var to const/let • const creates immutable variables ◦

    but does not make the value immutable const z = 1; if (true) { const z = 3; console.log(z); // z = 3 } console.log(z); // z = 1 z = 5; // error: assignment to constant variable const obj = {a: 3}; console.log(obj.a); // 3 obj.a = 5; console.log(obj.a); // 5 obj = {a: 5}; // error: assignment to constant variable
  7. Template Literal • Template literals are enclosed by the back-tick

    (` `) • String interpolation // ES5 function printCoord(x, y) { console.log('(' + x + ', ' + y + ')'); } // ES6 function printCoord(x, y) { console.log(`(${x}, ${y})`); }
  8. Template Literal • Multi-line strings var a = 'string text

    line 1\n' + 'string text line 2'; var b = 'string text line 1\n\ string text line 2'; const c = `string text line 1 string text line 2`;
  9. Arrow Function • Shoter functions // ES5 var arr =

    [1, 2, 3]; var squares = arr.map(function (x) { return x * x }); // ES6 const arr = [1, 2, 3]; const squares = arr.map(x => x * x);
  10. Arrow Function • Lexical this // ES5 function UiComponent() {

    var that = this; // (A) var btn = document.getElementById('myButton'); btn.addEventListener('click', function () { console.log('CLICK'); that.handleClick(); // (B) }); } UiComponent.prototype.handleClick = function () { }; // ES6 function UiComponent() { var btn = document.getElementById('myButton'); btn.addEventListener('click', () => { console.log('CLICK'); this.handleClick(); // (A) }); }
  11. Arrow Function () => { ... } // no parameter

    x => { ... } // one parameter, an identifier (x, y) => { ... } // several parameters x => { return x * x } // block x => x * x // expression, equivalent to previous line
  12. Destructuring • Array destructuring let list = [ 1, 2,

    3 ]; let [ a, , b ] = list; // a = 1, b = 3 [ b, a ] = [ a, b ]; // a = 3, b = 1 function f() { return [1, 2]; } [a, b] = f(); // a = 1, b = 2
  13. Destructuring • Object destructuring // ES5 var tmp = getASTNode();

    var op = tmp.op; var lhs = tmp.lhs; var rhs = tmp.rhs; // ES6 var { op, lhs, rhs } = getASTNode(); const { x, y } = { x: 11, y: 8 }; // x = 11; y = 8 // Same as: const { x: x, y: y } = { x: 11, y: 8 }; // with default values const { x, y = 1 } = {}; // x = undefined; y = 1
  14. Parameter Handling • Parameter default values • Simulating named parameters

    function func(x, y=0) { return [x, y]; } func(1, 2); // [1, 2] func(1); // [1, 0] func(); // [undefined, 0] // ES5 function selectEntries(options) { options = options || {}; var start = options.start || 0; var end = options.end || -1; var step = options.step || 1; } // ES6 function selectEntries({ start=0, end=-1, step=1 } = {}) { }
  15. Rest Operator • Remaining parameters • Array destructuring // Remaining

    parameters function f(x, ...y) { } f('a', 'b', 'c'); // x = 'a'; y = ['b', 'c'] // Array destructuring const [x, ...y] = ['a', 'b', 'c']; // x='a'; y=['b', 'c']
  16. Spread Operator • Spreading into function and method calls •

    Spreading into Arrays Math.max(13, 7, 30) // 30 Math.max.apply(null, [13, 7, 30]) // 30 Math.max(...[13, 7, 30]) // 30 // ES5 var x = ['a', 'b']; var y = ['c']; var z = ['d', 'e']; var arr = x.concat(y, z); // ES6 const x = ['a', 'b']; const y = ['c']; const z = ['d', 'e']; const arr = [...x, ...y, ...z];
  17. ES2018: Object Rest/Spread Properties • ES6 introduces rest/spread for array

    literals • https://github.com/tc39/proposal-object-rest-spread • Not yet supported in Edge 16, Safari 11 // Rest Properties let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }; x; // 1 y; // 2 z; // { a: 3, b: 4 } // Spread Properties let n = { x, y, ...z }; n; // { x: 1, y: 2, a: 3, b: 4 }
  18. Class • No separators between members of class definitions •

    super() calls parent constructor class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return `(${this.x}, ${this.y})`; } } class ColorPoint extends Point { constructor(x, y, color) { super(x, y); this.color = color; } toString() { return super.toString() + ' in ' + this.color; } }
  19. Class • ES6 can declare static method • No class

    field declaration in standard yet (stage 3 proposal) class Point { constructor(x, y) { this.x = x; this.y = y; } static defaultPoint () { return new Point(0, 0); } } let point = Point.defaultPoint();
  20. Promise • Promise is an alternative to callback for asynchronous

    computation $.ajax('/', { success: function(result) { console.log('success'); }, error:function (err) { console.log('error'); } }); // require jQuery 3.0 $.ajax('/') .then(function(result) { console.log('then success'); }) .catch(function(err) { console.log('catch error'); });
  21. Promise // ES5 function func(msg, timeout, onDone) { setTimeout(function ()

    { onDone(msg); }, timeout); } func('Hello', 100, function (msg) { console.log(msg); }); // ES6 function func(msg, timeout) { return new Promise((resolve, reject) => { setTimeout(() => resolve(msg), timeout); }); } func('Hello', 100) .then((msg) => { console.log(msg); });
  22. Promise // Producing a Promise const p = new Promise(

    function (resolve, reject) { // (A) ··· if (···) { resolve(value); // success } else { reject(reason); // failure } }); // Consuming a Promise promise .then(value => { /* fulfillment */ }) .catch(error => { /* rejection */ });
  23. Promise • Promises can be chained $.ajax('/list', { success: function

    (res) { $.ajax('/book/' + res[0].id, { success: function (res) { $.ajax('/author/' + res.aid, { success: function (res) { console.log(res.name); } }); } }); } }); $.ajax('/list') .then((res) => { return $.ajax('/book/' + res[0].id); }) .then((res) => { return $.ajax('/author/' + res.aid); }) .then((res) => { console.log(res.name); });
  24. Promise • Executing asynchronous functions in parallel function fetchAll(urls) {

    for (var i = 0, ok = 0; i < urls.length; i++) { $.ajax(urls[i], { success: function() { ok += 1; if (ok === urls.length) console.log('got all'); } }); } } fetchAll(urls); Promise.all(urls.map( url => $.ajax(url) )) .then((results) => { console.log('promise got all'); });
  25. ES2017: async / await • Synchronous-looking style $.ajax('/list') .then((res) =>

    { return $.ajax('/book/' + res[0].id); }) .then((res) => { return $.ajax('/author/' + res.aid); }) .then((res) => { console.log(res.name); }); (async () => { const list = await $.ajax('/list'); const book = await $.ajax('/book/' + list[0].id); const author = await $.ajax('/author/' + book.aid); console.log(author.name); });
  26. ES2017: async / await • async functions always return Promises

    async function asyncFunc() { return 123; } asyncFunc() .then(x => console.log(x)); // 123 async function asyncFunc() { throw new Error('Problem!'); } asyncFunc() .catch(err => console.log(err)); // Error: Problem!
  27. ES2017: async / await • Handling errors async function asyncFunc()

    { try { await otherAsyncFunc(); } catch (err) { console.error(err); } } // Equivalent to: function asyncFunc() { return otherAsyncFunc() .catch(err => { console.error(err); }); }
  28. Compatibility • ES6 Compatibility Table http://kangax.github.io/compat-table/es6/ ◦ Chrome 65, Firefox

    59: 97% ◦ Edge 16: 96%, Safari 11: 99% ◦ IE 11: 11% • Polyfill ◦ core-js: https://github.com/zloirock/core-js ◦ Polyfill service: https://polyfill.io/ • Transpile ◦ Babel: https://babeljs.io/
  29. Reference • ECMAScript 6: New Features ◦ http://es6-features.org • Exploring

    ES6 ◦ http://exploringjs.com/es6.html • Learn ES2015 ◦ https://babeljs.io/learn-es2015/ • ECMAScript proposals ◦ https://github.com/tc39/proposals • Python VS ES6 Syntax Comparison ◦ https://gist.github.com/Cu7ious/80c056ef4afb12314c6237b07d422c02