Slide 1

Slide 1 text

Road to ES6 Torino Coding Society 02/05/2016

Slide 2

Slide 2 text

Change is good

Slide 3

Slide 3 text

WHY JAVASCRIPT?

Slide 4

Slide 4 text

WHY (AND WHAT IS) ES6?

Slide 5

Slide 5 text

Let The let statement declares a block ({ statements }) scope local variable. let is the new var

Slide 6

Slide 6 text

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

Slide 7

Slide 7 text

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

Slide 8

Slide 8 text

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.

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

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]

Slide 11

Slide 11 text

Arrow functions A new compact syntax for functions. Arrow operator preserve context.

Slide 12

Slide 12 text

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; });

Slide 13

Slide 13 text

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));

Slide 14

Slide 14 text

Destructuring Arrays and object pattern matching and assignment.

Slide 15

Slide 15 text

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];

Slide 16

Slide 16 text

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

Slide 17

Slide 17 text

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];

Slide 18

Slide 18 text

Parameter handling Default values, rest parameters & spread operator

Slide 19

Slide 19 text

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; };

Slide 20

Slide 20 text

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]);

Slide 21

Slide 21 text

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);

Slide 22

Slide 22 text

String interpolation

Slide 23

Slide 23 text

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 +

Slide 24

Slide 24 text

Iterators An iterator enables custom iterations over an object. Is a function (Symbol.iterator) that return an object.

Slide 25

Slide 25 text

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

Slide 26

Slide 26 text

Classes OOP-style objects.

Slide 27

Slide 27 text

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; };

Slide 28

Slide 28 text

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 } }

Slide 29

Slide 29 text

Modules Support for exporting/importing values from/to modules (also single modules) without global namespace pollution. Support for asynchronous module loading.

Slide 30

Slide 30 text

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

Slide 31

Slide 31 text

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.

Slide 32

Slide 32 text

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}

Slide 33

Slide 33 text

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}

Slide 34

Slide 34 text

No content

Slide 35

Slide 35 text

Built-in methods

Slide 36

Slide 36 text

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

Slide 37

Slide 37 text

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

Slide 38

Slide 38 text

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

Slide 39

Slide 39 text

ESnext

Slide 40

Slide 40 text

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!

Slide 41

Slide 41 text

ASYNC/AWAIT function wait(t){ return new Promise((r) => setTimeout(r, t)); } async function asyncFunc(){ await wait(1000); } asyncFunc().then(() => console.log("3"));

Slide 42

Slide 42 text

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]]

Slide 43

Slide 43 text

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

Slide 44

Slide 44 text

Extended Literals: Unicode String & RegExp Literal Generators Classes: Static members Modules: Default export Symbol type Typed Arrays Meta-Programming: Proxying and Reflection Internationalization & Localization

Slide 45

Slide 45 text

References corso-javascript.it babeljs.io es6-features.org github.com/hemanth/es7-features http://kangax.github.io/compat-table/esnext/

Slide 46

Slide 46 text

THANKS! torinocodingsociety.it dev.welaika.com @MUKKOO