Slide 1

Slide 1 text

ECMAScript 6: what’s next for JavaScript? Dr. Axel Rauschmayer 2ality.com 2013-12-04 NDC London

Slide 2

Slide 2 text

JavaScript has become dangerous Used everywhere: browsers, servers, devices, . . . For much more than it was created for Let’s make it better at those tasks. . . Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 2 / 69

Slide 3

Slide 3 text

ECMAScript 6 (ES6): JavaScript, improved ECMAScript 6: next version of JavaScript (current: ECMAScript 5). This talk: Goals Design process Features When can I use it? Warning All information is preliminary, features can and will change. Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 3 / 69

Slide 4

Slide 4 text

Background

Slide 5

Slide 5 text

Background Important ES6 terms TC39 (Ecma Technical Committee 39): the committee evolving JavaScript. Members: companies (all major browser vendors etc.). Meetings attended by employees and invited experts. ECMAScript: the official name of the language Versions: ECMAScript 5 is short for “ECMAScript Language Specification, Edition 5” JavaScript: colloquially: the language formally: one implementation of ECMAScript ECMAScript Harmony: improvements after ECMAScript 5 (ECMAScript 6 and 7) Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 5 / 69

Slide 6

Slide 6 text

Background Goals for ECMAScript 6 One of several official goals [1]: make JavaScript better for complex applications for libraries (possibly including the DOM) as a target of code generators Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 6 / 69

Slide 7

Slide 7 text

Background How ECMAScript features are designed Avoid “design by committee”: Design by “champions” (groups of 1–2 experts) Feedback from TC39 and the web community TC39 has final word on whether/when to include Stages of designing a feature [2]: Strawman proposal TC39 is interested ⇒ proposal Field-testing via one or more implementations, refinements TC39 accepts feature ⇒ included in ECMAScript draft Included in final spec ⇒ Standard Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 7 / 69

Slide 8

Slide 8 text

Background How to upgrade a web language? Challenges w.r.t. upgrading: 1 JavaScript engines: Must run all existing code New versions = forced upgrades ⇒ ECMAScript 6 only adds features 2 JavaScript code: Must run on all engines that are in use ⇒ wait or compile ECMAScript 6 to ES5 (details later) Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 8 / 69

Slide 9

Slide 9 text

Variables and scoping

Slide 10

Slide 10 text

Variables and scoping Block-scoped variables Function scope (var) function order(x, y) { if (x > y) { var tmp = x; x = y; y = tmp; } console.log(tmp===x); // true return [x, y]; } Block scope (let, const) function order(x, y) { if (x > y) { let tmp = x; x = y; y = tmp; } console.log(tmp===x); // ReferenceError: // tmp is not defined return [x, y]; } Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 10 / 69

Slide 11

Slide 11 text

Variables and scoping Destructuring: objects Extract data (more than one value!) via patterns: let obj = { first: 'Jane', last: 'Doe' }; let { first: f, last: l } = obj; console.log(f + ' ' + l); // Jane Doe Usage: variable declarations assignments parameter definitions Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 11 / 69

Slide 12

Slide 12 text

Variables and scoping Object literals: property value shorthand Shorthand: {x,y} is the same as { x: x, y: y }. let obj = { first: 'Jane', last: 'Doe' }; let { first, last } = obj; console.log(first + ' ' + last); // Jane Doe Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 12 / 69

Slide 13

Slide 13 text

Variables and scoping Multiple return values function findElement(arr, predicate) { for (let index=0; index < arr.length; index++) { let element = arr[index]; if (predicate(element)) { return { element, index }; } } } let {element} = findElement(someArray, somePredicate); let {index} = findElement(someArray, somePredicate); // Order doesn't matter: let {index, element} = findElement(...); let {element, index} = findElement(...); Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 13 / 69

Slide 14

Slide 14 text

Variables and scoping Destructuring: arrays let [x, y] = [ 'a', 'b' ]; // x='a', y='b' let [x, y, ...rest] = [ 'a', 'b', 'c', 'd' ]; // x='a', y='b', rest = [ 'c', 'd' ] [x,y] = [y,x]; // swap values let [all, year, month, day] = /^(\d\d\d\d)-(\d\d)-(\d\d)$/ .exec('2999-12-31'); Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 14 / 69

Slide 15

Slide 15 text

Variables and scoping Destructuring: refutable by default Refutable (default): exception if match isn’t exact. { a: x, b: y } = { a: 3 }; // fails Default value: use if no match or value is undefined { a: x, b: y=5 } = { a: 3 }; // x=3, y=5 { a: x, b: y=5 } = { a: 3, b: undefined }; // x=3, y=5 Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 15 / 69

Slide 16

Slide 16 text

Parameter handling

Slide 17

Slide 17 text

Parameter handling Parameter handling 1: parameter default values Use a default value if parameter is missing. function func1(x, y=3) { return [x,y]; } Interaction: # func1(1, 2) [1, 2] # func1(1) [1, 3] # func1() [undefined, 3] Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 17 / 69

Slide 18

Slide 18 text

Parameter handling Parameter handling 2: rest parameters Put trailing parameters in an array. function func2(arg0, ...others) { return others; } Interaction: # func2(0, 1, 2, 3) [1, 2, 3] # func2(0) [] # func2() [] Eliminate the need for the special variable arguments. Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 18 / 69

Slide 19

Slide 19 text

Parameter handling Spread operator (...) Turn an array into function/method arguments: # Math.max(7, 4, 11) 11 # Math.max(...[7, 4, 11]) 11 The inverse of a rest parameter Mostly replaces Function.prototype.apply() Also works in constructors Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 19 / 69

Slide 20

Slide 20 text

Parameter handling Parameter handling 3: named parameters Use destructuring for named parameters opt1 and opt2: function func3(arg0, { opt1, opt2 }) { return [opt1, opt2]; } // {opt1,opt2} is same as {opt1:opt1,opt2:opt2} Interaction: # func3(0, { opt1: 'a', opt2: 'b' }) ['a', 'b'] Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 20 / 69

Slide 21

Slide 21 text

Arrow functions

Slide 22

Slide 22 text

Arrow functions Arrow functions: less to type Compare: let squares = [1, 2, 3].map(function (x) {return x * x}); let squares = [1, 2, 3].map(x => x * x); Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 22 / 69

Slide 23

Slide 23 text

Arrow functions Arrow functions: lexical this, no more that=this function UiComponent { var that = this; var button = document.getElementById('#myButton'); button.addEventListener('click', function () { console.log('CLICK'); that.handleClick(); }); } UiComponent.prototype.handleClick = function () { ... }; function UiComponent { let button = document.getElementById('#myButton'); button.addEventListener('click', () => { console.log('CLICK'); this.handleClick(); }); } Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 23 / 69

Slide 24

Slide 24 text

Arrow functions Arrow functions: versions General form: (arg1, arg2, ...) => expr (arg1, arg2, ...) => { stmt1; stmt2; ... } Shorter version – single parameter: arg => expr arg => { stmt1; stmt2; ... } Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 24 / 69

Slide 25

Slide 25 text

Object-orientation and modularity

Slide 26

Slide 26 text

Object-orientation and modularity Object literals ECMAScript 6: let obj = { __proto__: someObject, // special property myMethod(arg1, arg2) { // method definition ... } }; ECMAScript 5: var obj = Object.create(someObject); obj.myMethod = function (arg1, arg2) { ... }; Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 26 / 69

Slide 27

Slide 27 text

Object-orientation and modularity Classes class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return '('+this.x+', '+this.y+')'; } } function Point(x, y) { this.x = x; this.y = y; } Point.prototype.toString = function () { return '('+this.x+', '+this.y+')'; }; Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 27 / 69

Slide 28

Slide 28 text

Object-orientation and modularity Classes: subclass class ColorPoint extends Point { constructor(x, y, color) { super(x, y); // same as super.constructor(x, y) this.color = color; } toString() { return this.color+' '+super(); } } function ColorPoint(x, y, color) { Point.call(this, x, y); this.color = color; } ColorPoint.prototype = Object.create(Point.prototype); ColorPoint.prototype.constructor = ColorPoint; ColorPoint.prototype.toString = function () { return this.color+' '+Point.prototype.toString.call(this); }; Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 28 / 69

Slide 29

Slide 29 text

Object-orientation and modularity Static methods class Point { static zero() { return new Point(0, 0); } constructor(x, y) { this.x = x; this.y = y; } } let p = Point.zero(); Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 29 / 69

Slide 30

Slide 30 text

Object-orientation and modularity Modules: overview // lib/math.js let notExported = 'abc'; export function square(x) { return x * x; } export const MY_CONSTANT = 123; // main.js import {square} from 'lib/math'; console.log(square(3)); Alternatively: import 'lib/math' as math; console.log(math.square(3)); Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 30 / 69

Slide 31

Slide 31 text

Object-orientation and modularity Modules: features More features [3]: Rename imports Module IDs are configurable (default: paths relative to importing file) Programmatic (e.g. conditional) loading of modules via an API Module loading is customizable: Automatic linting (think: JSLint, JSHint) Automatically translate files (CoffeeScript, TypeScript) Use legacy modules (AMD, Node.js) Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 31 / 69

Slide 32

Slide 32 text

Template strings

Slide 33

Slide 33 text

Template strings Template strings: string interpolation Invocation: templateHandler`Hello ${first} ${last}!` Syntactic sugar for: templateHandler(['Hello ', ' ', '!'], first, last) Two kinds of tokens: Literal sections (static): 'Hello' Substitutions (dynamic): first Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 33 / 69

Slide 34

Slide 34 text

Template strings Template strings: interpolation, raw strings No handler ⇒ string interpolation. if (x > MAX) { throw new Error(`At most ${MAX} allowed: ${x}`); } Multiple lines, no escaping: var str = raw`This is a text with multiple lines. Escapes are not interpreted, \n is not a newline.`; Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 34 / 69

Slide 35

Slide 35 text

Template strings Template strings: regular expressions ECMAScript 6: XRegExp library – ignored whitespace, named groups, comments let str = '/2012/10/Page.html'; let parts = str.match(XRegExp.rx` ^ # match at start of string only / (? [^/]+ ) # capture top dir as year / (? [^/]+ ) # capture subdir as month / (? [^/]+ ) # file name base \.html? # file name extension: .htm or .html $ # end of string `); console.log(parts.year); // 2012 Advantages: Raw characters: no need to escape backslash and quote Multi-line: no need to concatenate strings with newlines at the end Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 35 / 69

Slide 36

Slide 36 text

Template strings Template strings: regular expressions ECMAScript 5: var str = '/2012/10/Page.html'; var parts = str.match(XRegExp( '^ # match at start of string only \n' + '/ (? [^/]+ ) # capture top dir as year \n' + '/ (? [^/]+ ) # capture subdir as month \n' + '/ (? [^/]+ ) # file name base \n' + '\\.html? # file name extension: .htm or .html \n' + '$ # end of string', 'x' )); Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 36 / 69

Slide 37

Slide 37 text

Template strings Template strings: other use cases Query languages Text localization Templating etc. Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 37 / 69

Slide 38

Slide 38 text

Symbols

Slide 39

Slide 39 text

Symbols Symbols Inspired by Lisp, Smalltalk etc. A new kind of primitive value: # let sym = Symbol(); # typeof sym 'symbol' Each symbol is unique. Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 39 / 69

Slide 40

Slide 40 text

Symbols Symbols: enum-style values const red = Symbol(); const green = Symbol(); const blue = Symbol(); function handleColor(color) { switch(color) { case red: ... case green: ... case blue: ... } } Previously: var red = 'red'; var green = 'green'; var blue = 'blue'; Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 40 / 69

Slide 41

Slide 41 text

Symbols Symbols: property keys let specialMethod = Symbol(); let obj = { // computed property key [specialMethod]: function (arg) { ... } }; obj[specialMethod](123); Shorter – method definition syntax: let obj = { [specialMethod](arg) { ... } }; Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 41 / 69

Slide 42

Slide 42 text

Symbols Symbols: property keys Advantage: No name clashes! Configure objects for ECMAScript and frameworks: Introduce publicly known symbols. Example: public symbol iterate makes an object iterable (details: later). Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 42 / 69

Slide 43

Slide 43 text

Standard library

Slide 44

Slide 44 text

Standard library Maps Data structure mapping from arbitrary values to arbitrary values (objects: keys must be strings). let map = new Map(); let obj = {}; map.set(obj, 123); console.log(map.get(obj)); // 123 console.log(map.has(obj)); // true map.delete(obj); console.log(map.has(obj)); // false Also: iteration (over keys, values, entries) and more. Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 44 / 69

Slide 45

Slide 45 text

Standard library Sets A collection of values without duplicates. let set1 = new Set(); set1.add('hello'); console.log(set1.has('hello')); // true console.log(set1.has('world')); // false let set2 = new Set([3,2,1,3,2,3]); console.log(set2.values()); // 1,2,3 Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 45 / 69

Slide 46

Slide 46 text

Standard library Object.assign Merge one object into another one. class Point { constructor(x, y) { Object.assign(this, { x, y }); } } Similar to Underscore.js _.extend(). Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 46 / 69

Slide 47

Slide 47 text

Standard library Standard library: new string methods # 'abc'.repeat(3) 'abcabcabc' # 'abc'.startsWith('ab') true # 'abc'.endsWith('bc') true # 'foobar'.contains('oo') true And more. Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 47 / 69

Slide 48

Slide 48 text

Standard library Standard library: new array methods # [13, 7, 8].find(x => x % 2 === 0) 8 # [1, 3, 5].find(x => x % 2 === 0) undefined # [13, 7, 8].findIndex(x => x % 2 === 0) 2 # [1, 3, 5].findIndex(x => x % 2 === 0) -1 And more. Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 48 / 69

Slide 49

Slide 49 text

Loops and iteration

Slide 50

Slide 50 text

Loops and iteration Iterables and iterators Iteration protocol: Iterable: a data structure whose elements can be traversed Iterator: the pointer used for traversal Examples of iterables: Arrays Sets Results produced by tool functions Examples (built-in, for objects): keys(), values(), entries() All array-like DOM objects (eventually) Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 50 / 69

Slide 51

Slide 51 text

Loops and iteration for-of: a better loop Replaces: for-in Array.prototype.forEach() Works for: iterables Convert array-like objects via Array.from(). Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 51 / 69

Slide 52

Slide 52 text

Loops and iteration for-of loop: arrays Replaces: for-in, Array.prototype.forEach() Loops over: iterables let arr = [ 'hello', 'world' ]; for (let elem of arr) { console.log(elem); } Output – elements, not indices: hello world Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 52 / 69

Slide 53

Slide 53 text

Loops and iteration for-of loop: objects let obj = { first: 'Jane', last: 'Doe' }; Iterate over properties: import {entries} from '@dict'; // returns an iterable for (let [key, value] of entries(obj)) { console.log(key + ' = ' + value); } Iterate over property keys: import {keys} from '@dict'; // returns an iterable for (let key of keys(obj)) { console.log(key); } Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 53 / 69

Slide 54

Slide 54 text

Loops and iteration Comprehensions Array comprehensions produce arrays: let numbers = [1,2,3]; let squares = [for (x of numbers) x * x]; [for (i of document.querySelectorAll('.item')) i.textContent] Generator comprehensions produce generator objects (iterators): let twice = (for (x of iterable) x + x); iterable can be “infinite”! Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 54 / 69

Slide 55

Slide 55 text

Loops and iteration Odds and ends Also part of ECMAScript 6: Promises Better support for Unicode (strings, regular expressions) Standard modules Optimized tail calls Probably in ECMAScript 7: Handling binary data Object.observe() for data binding Integers (64 bit, 32 bit, etc.) Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 55 / 69

Slide 56

Slide 56 text

When?

Slide 57

Slide 57 text

When? Time table ECMAScript specification: November 2013: final review of draft July 2014: editorially complete December 2014: Ecma approval Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 57 / 69

Slide 58

Slide 58 text

When? Using ECMAScript 6 today First features are already in engines [5] Traceur by Google: compiles ECMAScript 6 to ECMAScript 5. dynamically (on the fly) statically (e.g. via tools) TypeScript by Microsoft: ECMAScript 6 + optional static typing (at development time) compiles to ECMAScript 5 es6-shim by Paul Miller: features of the ES6 standard library, backported to ES5. Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 58 / 69

Slide 59

Slide 59 text

Conclusion

Slide 60

Slide 60 text

Conclusion Take-aways: ECMAScript 6 First features already in browsers, much of ES6 supported by late 2014. Can be used today (via TypeScript et al.) Biggest impact on community (currently: too much variety): Classes Modules More on ECMAScript 6 in my 2nd talk. . . Topics: callable entities, iterators, generators, etc. Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 60 / 69

Slide 61

Slide 61 text

Thank you! Blog posts on ECMAScript 6: 2ality.com/search/label/esnext

Slide 62

Slide 62 text

Annex

Slide 63

Slide 63 text

Annex References 1 ECMAScript Harmony wiki 2 “The Harmony Process” by David Herman 3 “ES6 Modules” by Yehuda Katz 4 “Why coroutines won’t work on the web” by David Herman 5 “ECMAScript 6 compatibility table” by kangax [features already in JavaScript engines] Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 63 / 69

Slide 64

Slide 64 text

Annex Resources ECMAScript 6 specification drafts by Allen Wirfs-Brock ECMAScript mailing list: es-discuss TC39 meeting notes by Rick Waldron “A guide to 2ality’s posts on ECMAScript 6” by Axel Rauschmayer Continuum, an ECMAScript 6 virtual machine written in ECMAScript 3. (Links are embedded in this slide.) Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 64 / 69

Slide 65

Slide 65 text

Bonus: proxies

Slide 66

Slide 66 text

Bonus: proxies Proxies The handler h observes operations applied to object proxy: let target = {}; let proxy = Proxy(target, h); Each of the following operations triggers a method invocation on h: proxy['foo'] → h.get(target, 'foo', proxy) proxy['foo'] = 123 → h.set(target, 'foo', 123, proxy) 'foo' in proxy → h.has(target, 'foo') for (key in proxy) {...} → h.enumerate(target) Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 66 / 69

Slide 67

Slide 67 text

Bonus: proxies Proxies in the prototype chain let child = Object.create(proxy); Operations on child can still trigger handler invocations (if the search for properties reaches proxy): child['foo'] → h.get(target, 'foo', child) child['foo'] = 123 → h.set(target, 'foo', 123, child) 'foo' in child → h.has(target, 'foo') for (key in child) {...} → h.enumerate(target) Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 67 / 69

Slide 68

Slide 68 text

Bonus: proxies Proxy: example let handler = { get(target, name, receiver) { return (...args) => { console.log('Missing method '+name + ', arguments: '+args); } } }; let proxy = Proxy({}, handler); Using the handler: # let obj = Object.create(proxy); # obj.foo(1, 2) Missing method foo, arguments: 1, 2 Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 68 / 69

Slide 69

Slide 69 text

Bonus: proxies Use cases for proxies Typical meta-programming tasks: Sending all method invocations to a remote object Implementing data access objects for a database Data binding Logging Dr. Axel Rauschmayer (2ality.com) ECMAScript 6 2013-12-04 69 / 69