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

Road to ES6

Road to ES6

An introduction to ES6 (and some ESnext) new features.

weLaika

May 04, 2016
Tweet

More Decks by weLaika

Other Decks in Technology

Transcript

  1. Let The let statement declares a block ({ statements })

    scope local variable. let is the new var
  2. The problem with blocks in ES5 was var i =

    1; console.log(i); // 1 if (true) { var i = 0; console.log(i); // 0 } console.log(i); // 0
  3. ES6 var i = 1; console.log(i); // 1 if (true)

    { let i = 0; console.log(i); // 0 } console.log(i); // 1 ES5 var i = 1; console.log(i); // 1 if (true) { var _i = 0; console.log(_i); // 0 } console.log(i); // 1
  4. Const The const declaration creates a read-only reference to a

    value. It does not mean the value it holds is immutable, just that the variable identi er cannot be reassigned. Constants can be declared with uppercase or lowercase, but a common convention is to use all- uppercase letters.
  5. CONST const MY_CONST = 7; MY_CONST = 20; // repl:

    "MY_CONST" is read-only const MY_CONST = 20; // repl: Duplicate declaration "MY_CONST" var MY_CONST = 20; // repl: Duplicate declaration "MY_CONST" const FOO; // SyntaxError: missing = in const declaration
  6. CONST // const also works on objects const MY_OBJECT =

    {"key": "value"}; MY_OBJECT = {"OTHER_KEY": "value"}; // repl: "MY_OBJECT" is read-only // Object attributes are not protected MY_OBJECT.key = "otherValue"; console.log(MY_OBJECT) // {"key":"otherValue"} // const are not immutable const MY_ARRAY = [1]; MY_ARRAY.push(2); console.log(MY_ARRAY); // [1,2]
  7. ES6 i => i*2 () => 2 (a,i) => i*a

    i => { a = i*2 return a + 4 } ES5 (function (i) { return i * 2; }); (function () { return 2; }); (function (a, i) { return i * a; }); (function (i) { a = i * 2; return a + 4; });
  8. LEXICAL THIS ES6 this.nums.forEach((v) => { if (v % 5

    === 0) this.fives.push(v) }) ES5 // variant 1 var self = this; this.nums.forEach(function (v) { if (v % 5 === 0) self.fives.push(v); }); // variant 2 (since ECMAScript 5.1 only) this.nums.forEach(function (v) { if (v % 5 === 0) this.fives.push(v); }.bind(this));
  9. ARRAY MATCHING ES6 let list = [ 1, 2, 3

    ] let [ a, , b ] = list [ b, a ] = [ a, b ] ES5 var list = [1, 2, 3]; var a = list[0]; var b = list[2]; var _ref = [a, b]; b = _ref[0]; a = _ref[1];
  10. OBJECT MATCHING ES6 // direct assignment let obj = {

    a: 1, b: 2 }; let { a: a_var, b: b_var } = obj // assign returning object from a function let { st_par, nd_par } = getParams() // Default params var list = [ 7, 42 ] var [ a = 1, b, d = 0 ] = list ES5 var obj = { a: 1, b: 2 }; var a_var = obj.a; var b_var = obj.b; var _getParams = getParams(); var st_par = _getParams.st_par; var nd_par = _getParams.nd_par; var list = [7, 42]; var _list$ = list[0]; var a = _list$ === undefined ? 1 : _list$; var _list$2 = list[1]; var b = _list$2 === undefined ? 2 : _list$2; var d = list[2]; console.log(a, b, d) // 7, 42, 0
  11. OBJECT MATCHING ES6 // automatic assignment and filtering let user

    = {name: "Filippo", nickname: "mukkoo", socials: [{id: 1, facebook: "null"}, {id: 2, twitter: "@mukkoo" let {nickname, socials: [, twitter] } = user // nickname: "mukkoo" // twitter: {id: 2, twitter: "@mukkoo"} ES5 var _slicedToArray = function () { **...something here...** }(); var user = { name: "Filippo", nickname: "mukkoo", socials: [{ id: 1, facebook: "null" }, { id: 2, twitter: "@mukkoo var nickname = user.nickname; var _user$socials = _slicedToArray(user.socials, 2); var twitter = _user$socials[1];
  12. DEFAULT VALUES ES6 let my_func = (a = 2, b)

    => a + b ES5 var my_func = function my_func(a, b) { var a = arguments.length <= 0 || arguments[0] === undefined ? 2 : arguments var b = arguments[1]; return a + b; };
  13. REST PARAMETERS ES6 function f (x, ...a) { a //

    [2,"something",true,[1,2,3]] } f(1, 2, "something", true, [1,2,3]) ES5 function f(x) { for (var _len = arguments.length, a = Array(_len > 1 ? _len - 1 : _key = 1; _key < _len; _key++) { a[_key - 1] = arguments[_key]; } return a; } f(1, 2, "something", true, [1, 2, 3]);
  14. SPREAD OPERATOR ES6 let str = "foo" let chars =

    [ ...str ] // ["f", "o", "o"] let chars_obj = { ...str } // {"0":"f","1":"o","2":"o"} ES5 var str = "foo"; function _toConsumableArray(arr) { **...something here...** } var chars = [].concat(_toConsumableArray(str)); var _extends = Object.assign || function (target) { **...something here...** var chars_obj = _extends({}, str);
  15. STRING INTERPOLATION ` operator (multiline) and ${} interpolation ES6 let

    user = { name: "Filippo" } let cart = { amount: 7 } let message = `Hello ${user.name}, your cart total is ${cart.amount} $` // Hello Filippo, // your cart total is 7 $ ES5 var user = { name: "Foo" }; var cart = { amount: 7 }; var message = "Hello " + user.name + ",\nyour cart total is " + cart.amount +
  16. Iterators An iterator enables custom iterations over an object. Is

    a function (Symbol.iterator) that return an object.
  17. ITERATORS Declare a function that returns an object with one

    function called next() that returns an object with two properties: value (current) and done (if iteration finished). let fibonacci = { [Symbol.iterator]() { let pre = 0, cur = 1 return { next () { [ pre, cur ] = [ cur, pre + cur ] return { done: false, value: cur } } } } } // for..of operator for (let n of fibonacci) { if (n > 100) break
  18. CLASS DEFINITION ES6 class Shape { constructor (id, x, y)

    { this.id = id this.move(x, y) } move (x, y) { this.x = x this.y = y } } ES5 raw var Shape = function (id, x, y) { this.id = id; this.move(x, y); }; Shape.prototype.move = function (x, y) { this.x = x; this.y = y; };
  19. CLASS INHERITANCE ES6 class Rectangle extends Shape { constructor (id,

    x, y, width, height) { super(id, x, y) this.width = width this.height = height } } class Circle extends Shape { constructor (id, x, y, radius) { super(id, x, y) this.radius = radius } }
  20. Modules Support for exporting/importing values from/to modules (also single modules)

    without global namespace pollution. Support for asynchronous module loading.
  21. MODULES // lib/math.js export function sum (x, y) { return

    x + y } export var pi = 3.141593 // someApp.js import * as math from "lib/math" console.log("2π = " + math.sum(math.pi, math.pi)) // otherApp.js import { sum, pi } from "lib/math" console.log("2π = " + sum(pi, pi)) // lib/mathplusplus.js export * from "lib/math" export var e = 2.71828182846
  22. Promises The Promise object is used for deferred and asynchronous

    computations. A Promise represents an operation that hasn't completed yet, but is expected in the future. A Promise is in one of these states: pending: initial state, not ful lled or rejected. ful lled: meaning that the operation completed successfully. rejected: meaning that the operation failed.
  23. PROMISES & CHAINED PROMISES No more callback pyramid! ES6 function

    msgAfterTimeout (msg, who, timeout) { return new Promise((resolve, reject) => { setTimeout(() => resolve(` `), timeout) }) } msgAfterTimeout("", "Foo", 100).then((msg) => msgAfterTimeout(msg, "Bar", 200) ).then((msg) => { console.log(` `) }) ${msg} Hello ${who}! done after 300ms:${msg}
  24. PROMISES COMBINATION Parallel usage ES6 function fetchAsync (url, timeout, onData,

    onError) { … } let fetchPromised = (url, timeout) => { return new Promise((resolve, reject) => { fetchAsync(url, timeout, resolve, reject) }) } Promise.all([ fetchPromised("http://backend/foo.txt", 500), fetchPromised("http://backend/bar.txt", 500), fetchPromised("http://backend/baz.txt", 500) ]).then((data) => { let [ foo, bar, baz ] = data console.log(` `) success: foo=${foo} bar=${bar} baz=${baz}
  25. Assign var dst = { quux: 0 } var src1

    = { foo: 1, bar: 2 } var src2 = { foo: 3, baz: 4 } Object.assign(dst, src1, src2) // dst: { quux: 0, foo: 3, bar: 2, baz: 4 } Find [ 1, 3, 4, 2 ].find(x => x > 3) // 4 [ 1, 3, 4, 2 ].find(x => x > 2) // 3 [ 1, 4, 3, 2 ].find(x => x > 2) // 4 Repeat "foo".repeat(3) // foofoofoo
  26. String search "hello".startsWith("ello", 1) // true "hello".endsWith("hell", 4) // true

    "hello".includes("ell") // true "hello".includes("ell", 1) // true "hello".includes("ell", 2) // false Number check Number.isNaN(42) === false Number.isNaN(NaN) === true Number.isFinite(Infinity) === false Number.isFinite(-Infinity) === false Number.isFinite(NaN) === false Number.isFinite(123) === true Number.isFinite("123") === false isFinite("123") = true
  27. Number trunc Math.trunc(42.7) // 42 Math.trunc( 0.1) // 0 Math.trunc(-0.1)

    // -0 Number sign Math.sign(7) // 1 Math.sign(0) // 0 Math.sign(-0) // -0 Math.sign(-7) // -1 Math.sign(NaN) // NaN
  28. PIPE OPERATOR ES6 let repeat = (str) => str +

    ", " + str let exclaim = (str) => str + "!" exclaim(repeat('hello')) // hello, hello! ESnext let repeat = (str) => str + ", " + str let exclaim = (str) => str + "!" 'hello' |> repeat |> exclaim // hello, hello!
  29. ASYNC/AWAIT function wait(t){ return new Promise((r) => setTimeout(r, t)); }

    async function asyncFunc(){ await wait(1000); } asyncFunc().then(() => console.log("3"));
  30. OTHER STUFF Exponentiation Operator let squared = 2 ** 2;

    // same as: 2 * 2 let cubed = 2 ** 3; // same as: 2 * 2 * 2 Values/Entries { a: 1, b: 2, c: 3 }.values // [1, 2, 3] { a: 1, b: 2, c: 3 }.entries // [['a', 1], ['b', 2], ['c', 3]]
  31. LEFT OUT Block-scoped functions Regular Expression Sticky Matching Enhanced Object

    Properties: Computed Property Names Enhanced Object Properties: Method Properties Destructuring Assignment: Fail-So Destructuring Template Literals: Custom Interpolation Template Literals: Raw String Access Extended Literals: Binary & Octal Literal
  32. Extended Literals: Unicode String & RegExp Literal Generators Classes: Static

    members Modules: Default export Symbol type Typed Arrays Meta-Programming: Proxying and Reflection Internationalization & Localization