SlideShare una empresa de Scribd logo
1 de 56
ES6 is Nigh
A PRESENTATION ON THE FUTURE OF JAVASCRIPT


http://es6isnigh.com
@domenic
Domenic Denicola




              https://github.com/domenic
              https://npmjs.org/~domenic
              @esdiscuss




@domenic
History




          ES1 → ES3: try/catch, do/while, switch, regular expressions, …
          ES3 → ES5: accessors, strict mode (static scoping), object reflection, JSON,
           array extras, …
          Now, ES5 → ES6




@domenic
Why?




           “Stagnation on the web is a social ill.”
                                         —Brendan Eich


                          http://news.ycombinator.com/item?id=4634735
@domenic
Why?




              Say what you mean!



@domenic
How?




@domenic
   All ES5 code is ES6 code and
                        has the same meaning
                       No modes

       One          

                    
                        No backwards incompatibility
                        No “fixes”


       JavaScript      ES6 is purely additive




@domenic
@domenic
Better object literals      Spread               Const               Sets and maps
                                    Rest    Block scoping       Destructuring                   Iteration




@domenic
@domenic
Parameter defaults

                      Arrow functions

           Classes

                            Modules
@domenic
@domenic
Tail calls
           Template strings
                                        Binary data
              Unicode
                                 Symbols
             Weak maps and sets
                                             Generators
                              Proxies




@domenic
   Better object literals
                    Rest and spread

       Comfort   

                 
                     Block scoping
                     Const
                    Destructuring
                    Sets and maps
                    Iteration




@domenic
Better Object Literals


       var empireJS = {
         attendees: "many",
         preParty() {
           console.log(this.attendees + " attendees are partying!");
         }
       };

       var conferences = { empireJS, cascadiaJS };




@domenic
Rest and Spread


       function sprintf(format, ...params) {
         assert(Array.isArray(params));
       }

       Math.max(...array);

       Math.max(0, ...array, 5, ...array2);

       new Date(...dateFields);

       array.push(...array2);



@domenic
More Spread


       var prequels = ["tpm", "aotc", "rots"];
       var movies = [...prequels, "anh", "tesb", "rotj"];

       var nodeList = document.querySelectorAll("div");
       [...nodeList].forEach(function (node) {
         // finally!
       });




@domenic
Block Scoping


       let log = console.log.bind(console);

       function f(x) {
        if (Math.random() > 0.5) {
          let log = Math.log;
          x = log(x);
        }

           log("result: " + x);
       }




@domenic
Block Scoping


       let log = console.log;

       function f(x) { // 5 refactorings later
        if (Math.random() > 0.5) {
          x = log(x); // error! used a `let` before declaration.
          let log = Math.log;
        }

           log("result: " + x);
       }

       f(Math.E); // but, the error doesn’t occur until here: runtime, not static.


@domenic
Block Scoping


       function f(x) { // 10 refactorings later
        let log = console.log;
        let log = Math.log; // `SyntaxError`! No double `let`s.

           if (Math.random() > 0.5) {
             x = log(x);
           }

           log("result: " + x);
       }




@domenic
Block Scoping


       for (let i = 0; i < a.length; ++i) {
         els[i].onclick = function () {
           return a[i];
         };
       }

       assert(typeof i === "undefined");
       assert(els[0].onclick() === a[0]);




@domenic
Block Scoping


       if (Math.random() > 0.5) {
         function go() {
           console.log("gone!");
         }

           el.onmousedown = go;
           el.ontouchstart = go;
       }

       assert(typeof go === "undefined");




@domenic
Const


       const PI = Math.PI;

       PI = 22/7; // error! cannot reassign

       const E; // SyntaxError! need initializer

       // plus all the yummy `let` semantics




@domenic
Destructuring


       [a, b] = [b, a];

       let [x, y] = f();

       let re = /([a-z]+)(s)(.*)([^a-z])/;
       let [, hello, space, world, bang] = re.exec("hello world!");

       let [first, ...allButFirst] = document.querySelectorAll("p");




@domenic
Destructuring


       let { tagName, textContent } = el;
       let { viewModel, bindings } = doDataBinding();

       let { firstElementChild: first, lastElementChild: last } = el;

       let { firstElementChild: { tagName: firstTag } } = document.body;
       let { children: [first, ...others] } = document.body;




@domenic
Destructuring


       function runTests({ reporter, ui }, [firstFile, ...others]) {
         // ...
       }

       try {
         runTests({ reporter: "spec", ui: "tdd" }, ["test1", "test2"]);
       } catch ({ message }) {
         console.error(message);
       }




@domenic
Sets and Maps


       let s = new Set([...document.body.children]);

       // `s.has`, `s.add`, `s.delete` — too obvious

       // let's do something cool instead:
       function unique(array) {
         return [...new Set(array)]; // O(n)!
       }

       let m = new Map();
       m.add(model, new ViewModel(model)); // objects as keys!
       // otherwise obvious — `m.has`, `m.get`, `m.add`, `m.delete`


@domenic
Iteration


       for (let x of ["one", "two", "three"]) { }

       for (let value of set) { }

       for (let [key, value] of map) { }

       // customizing iteration requires some magic




@domenic
   Parameter defaults
                     Arrow functions
                     Classes
       Cowpaths      Modules




@domenic
Parameter Defaults


       function fill(mug, liquid = "coffee") {
         // …
       }

       function pour(person, mug1 = person.mug, mug2 = new Mug()) {
        // …
       }

       pour(domenic, undefined, you.mug);




@domenic
Arrow Functions


       array.map(x => x * x);

       array.filter(x => x === this.target);

       [...$("p")].forEach((el, i) => {
         el.textContent = "The #" + i + " <p>";
       });




@domenic
Classes


       class EventEmitter {
         constructor() {
           this.domain = domain.active;
         }
         emit(type, ...args) { /* ... */ }
         // ...
       }

       class Stream extends EventEmitter {
         pipe(dest, options) { /* ... */ }
       }



@domenic
Modules


       import http from "http";
       import { read, write } from "fs";
       import { draw: drawShape } from "graphics";
       import { draw: drawGun } from "cowboy";

       export sprintf;
       export function $(selector) {
         return [...document.querySelectorAll(selector)];
       };

       // what about `module.exports = aFunction`?



@domenic
   Proper tail calls
                  Template strings
                  Binary data
                  Unicode
                  Symbols
       Magic      Weak sets and maps
                  Generators
                  Proxies




@domenic
Proper Tail Calls


       "use strict"; // for its effect on arguments/caller.

       function sumTo(n, accumulator = 0) {
         return n === 0 ? accumulator : sumTo(n - 1, accumulator);
       }

       sumTo(123456); // no “too much recursion error”; no stack usage at all in fact!




@domenic
Template Strings


       let x = 1;
       let y = 2;

       let s = `${x} + ${y} = ${x + y}`;

       let multiline = `<html>
         <body>
          Hello world!
         </body>
       </html>`;




@domenic
Template Strings


       let url = "http://example.com/";
       let query = "Hello & Goodbye";
       let s = safehtml`
       <a href="${url}?q=${query}“
         onclick="alert('${query}')">
         ${query}
       </a>`;

       assert(s === `<a href="http://example.com/?q=Hello%20%26%20Goodbye"
         onclick="alert('Hello&#32;x26&#32;Goodbye')">
        Hello &amp; Goodbye
       </a>`);


@domenic
Binary Data


       const Point2D = new StructType({ x: uint32, y: uint32 });
       const Color = new StructType({ r: uint8, g: uint8, b: uint8 });
       const Pixel = new StructType({ point: Point2D, color: Color });
       const Triangle = new ArrayType(Pixel, 3);

       let t = new Triangle([
         { point: { x: 0, y: 0 }, color: { r: 255, g: 255, b: 255 } },
         { point: { x: 5, y: 5 }, color: { r: 128, g: 0, b: 0 } },
         { point: { x: 10, y: 0 }, color: { r: 0, g: 0, b: 128 } }
       ]);




@domenic
Unicode


       // Emoji take more than two bytes: one code *point*, two code *units*.

       let x = "😁 ";
       let y = "uD83DuDE01"; // ES5
       let z = "u{1F638}"; // ES6

       assert(x === y && y === z);

       assert(x.charCodeAt(0) === 0xD83D); // ES5
       assert(x.charCodeAt(1) === 0xDE01); // ES5
       assert(x.codePointAt(0) === 0x1F638); // ES6

                                                         https://gist.github.com/1850768
@domenic
Unicode


       // iterator goes over code *points*, yay.
       for (let c of "😁 ") {
         assert(c === "😁 ");
       }

       assert("😁 ".length === 2); // can't break the web, still code units :-/

       // The "u" flag on regexes adds lots of Unicode fixes, e.g.:
       assert(/^.$/.test("😁 ") === false);
       assert(/^.$/u.test("😁 ") === true);




@domenic
Symbols


       function S3Bucket(apiKey, apiSecret) {
         this._apiKey = apiKey;
         this._apiSecret = apiSecret;
       }

       S3Bucket.prototype.request = function (url) {
         let signature = calculateSignature(this._apiKey, this._apiSecret);
         this._sendRequest(url, signature);
       };

       S3Bucket.prototype._sendRequest = function () { };



@domenic
Symbols


       function S3Bucket(apiKey, apiSecret) {
        this.request = function (url) {
          let signature = calculateSignature(apiKey, apiSecret);
          sendRequest(url, signature);
        };

           function sendRequest() { }
       }




@domenic
Symbols

       let apiKey = new Symbol(), apiSecret = new Symbol(), sendRequest = new Symbol();

       function S3Bucket(theApiKey, theApiSecret) {
         this[apiKey] = theApiKey;
         this[apiSecret] = theApiSecret;
       }

       S3Bucket.prototype.request = function (url) {
         let signature = calculateSignature(this[apiKey], this[apiSecret]);
         this[sendRequest](url, signature);
       };

       S3Bucket.prototype[sendRequest] = function () { };

@domenic
Symbols

       private @apiKey, @apiSecret, @sendRequest;

       function S3Bucket(theApiKey, theApiSecret) {
         this.@apiKey = theApiKey;
         this.@apiSecret = theApiSecret;
       }

       S3Bucket.prototype.request = function (url) {
         let signature = calculateSignature(this.@apiKey, this.@apiSecret);
         this.@sendRequest(url, signature);
       };

       S3Bucket.prototype.@sendRequest = function () { };

@domenic
Weak Sets


       let trustedObjects = new WeakSet();

       function createTrustedObject() {
        let trusted = { /* ... */ };
        trustedObjects.add(trusted);

           return trusted;
       }

       function isTrusted(obj) {
         return trustedObjects.has(obj);
       }


@domenic
Weak Maps


       let cache = new WeakMap();

       function calculateChecksum(httpResponse) {
        if (cache.has(httpResponse)) {
          return cache.get(httpResponse);
        }

           let checksum = calculateChecksum(httpResponse);
           cache.set(httpResponse, checksum);
           return checksum;
       }


@domenic
Symbols Again


       let checksum = new Symbol();

       function calculateChecksum(httpResponse) {
        if (!(checksum in httpResponse)) {
          httpResponse[checksum] = calculateChecksum(httpResponse);
        }

           return httpResponse[checksum];
       }




@domenic
Back to Iterators


       import { iterator } from "@iter"; // a symbol in the standard library

       let obj = {};
       obj[iterator] = function () {
         return {
           next() { return 5; }
         };
       };

       for (let n of obj) {
         assert(n === 5);
       }


@domenic
Generators


       function* naturalNumbers() {
         let current = 0;
         while (true) {
           yield current++;
         }
       }

       let seq = naturalNumbers();
       assert(seq.next() === 0);
       assert(seq.next() === 1);
       assert(seq.next() === 2);



@domenic
Generators Return Iterators


       // Generator functions return iterators
       for (let n of naturalNumbers()) {
         console.log(n);
       }

       // Use them to create your own iterators
       obj[iterator] = function* () {
         yield 5;
       };




@domenic
Generators Are Shallow Coroutines

       function* demo() {
         console.log("a");
         yield;
         console.log("b");
         yield;
         console.log("c");
       }

       let seq = demo(); // “paused,” with no code executed
       seq.next(); // execution resumes; logs "a"; then pause
       seq.next(); // execution resumes; logs "b"; then pause
       seq.next(); // execution resumes; logs "c"; enters “done” state
       seq.next(); // throws `StopIteration`


@domenic
Shallow Coroutines for Async


       spawn(function* () {
        try {
          let post = yield getJSON("/post/1.json");
          let comments = yield getJSON(post.commentURL);

           yield fadeInCommentUI();
           comments.innerHTML = template(comments);
         } catch (e) {
           comments.innerText = e.message;
         }
       });



@domenic                                                   http://taskjs.org/
Proxies

       let handler = {
         getOwnPropertyDescriptor(target, name) { },
         getOwnPropertyNames(target) { },
         getPrototypeOf(target) { },
         defineProperty(target, name, desc) { },
         deleteProperty(target, name) { },
         freeze(target) { },
         seal(target) { },
         preventExtensions(target) { },
         isFrozen(target) { },
         isSealed(target) { },
         isExtensible(target) { },
         ⋮



@domenic
Proxies

         ⋮
         has(target, name) { },
         hasOwn(target, name) { },
         get(target, name, receiver) { },
         set(target, name, val, receiver) { },
         enumerate*(target) { },
         keys(target) { },
         apply(target, thisArg, args) { },
         construct(target, args) { }
       });

       let theTarget = {};
       let virtualObject = new Proxy(theTarget, handler);


@domenic
   The future of JS: it’s important!
                           Follow @esdiscuss.
                           Stay tuned for more on es6isnigh.com.
       The Future Now      Be adventurous; use a transpiler!
                           Skate where the puck will be.




@domenic

Más contenido relacionado

La actualidad más candente

ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Web Crawling with NodeJS
Web Crawling with NodeJSWeb Crawling with NodeJS
Web Crawling with NodeJSSylvain Zimmer
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAnkit Agarwal
 
Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsMike Hagedorn
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.boyney123
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr Pelczar
 
History of jQuery
History of jQueryHistory of jQuery
History of jQueryjeresig
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptŁukasz Kużyński
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to NodejsGabriele Lana
 
You will learn RxJS in 2017
You will learn RxJS in 2017You will learn RxJS in 2017
You will learn RxJS in 2017名辰 洪
 

La actualidad más candente (20)

ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Web Crawling with NodeJS
Web Crawling with NodeJSWeb Crawling with NodeJS
Web Crawling with NodeJS
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.js
 
JavaScript Promise
JavaScript PromiseJavaScript Promise
JavaScript Promise
 
Promises, Promises
Promises, PromisesPromises, Promises
Promises, Promises
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
History of jQuery
History of jQueryHistory of jQuery
History of jQuery
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascript
 
Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to Nodejs
 
You will learn RxJS in 2017
You will learn RxJS in 2017You will learn RxJS in 2017
You will learn RxJS in 2017
 
Promise pattern
Promise patternPromise pattern
Promise pattern
 
Introduction of ES2015
Introduction of ES2015Introduction of ES2015
Introduction of ES2015
 

Destacado

Real World Windows 8 Apps in JavaScript
Real World Windows 8 Apps in JavaScriptReal World Windows 8 Apps in JavaScript
Real World Windows 8 Apps in JavaScriptDomenic Denicola
 
Creating Truly RESTful APIs
Creating Truly RESTful APIsCreating Truly RESTful APIs
Creating Truly RESTful APIsDomenic Denicola
 
[Tokyo NodeFest 2015] Hardware Hacking for Javascript Developers
[Tokyo NodeFest 2015] Hardware Hacking for Javascript Developers[Tokyo NodeFest 2015] Hardware Hacking for Javascript Developers
[Tokyo NodeFest 2015] Hardware Hacking for Javascript DevelopersTomomi Imura
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6Solution4Future
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptWojciech Dzikowski
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6Rob Eisenberg
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overviewhesher
 

Destacado (12)

Real World Windows 8 Apps in JavaScript
Real World Windows 8 Apps in JavaScriptReal World Windows 8 Apps in JavaScript
Real World Windows 8 Apps in JavaScript
 
Creating Truly RESTful APIs
Creating Truly RESTful APIsCreating Truly RESTful APIs
Creating Truly RESTful APIs
 
The Final Frontier
The Final FrontierThe Final Frontier
The Final Frontier
 
Client-Side Packages
Client-Side PackagesClient-Side Packages
Client-Side Packages
 
[Tokyo NodeFest 2015] Hardware Hacking for Javascript Developers
[Tokyo NodeFest 2015] Hardware Hacking for Javascript Developers[Tokyo NodeFest 2015] Hardware Hacking for Javascript Developers
[Tokyo NodeFest 2015] Hardware Hacking for Javascript Developers
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Domains!
Domains!Domains!
Domains!
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern Javascript
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
Lecture 2: ES6 / ES2015 Slide
Lecture 2: ES6 / ES2015 SlideLecture 2: ES6 / ES2015 Slide
Lecture 2: ES6 / ES2015 Slide
 

Similar a ES6 is Nigh

MiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptMiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptCaridy Patino
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Troy Miles
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
PHP Static Code Review
PHP Static Code ReviewPHP Static Code Review
PHP Static Code ReviewDamien Seguy
 
React Native Evening
React Native EveningReact Native Evening
React Native EveningTroy Miles
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchainedEduard Tomàs
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineMovel
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonAlex Payne
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot CampTroy Miles
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 

Similar a ES6 is Nigh (20)

Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
 
MiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptMiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScript
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
dojo.Patterns
dojo.Patternsdojo.Patterns
dojo.Patterns
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
PHP Static Code Review
PHP Static Code ReviewPHP Static Code Review
PHP Static Code Review
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy Cresine
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 
CppTutorial.ppt
CppTutorial.pptCppTutorial.ppt
CppTutorial.ppt
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 

Más de Domenic Denicola

How to Win Friends and Influence Standards Bodies
How to Win Friends and Influence Standards BodiesHow to Win Friends and Influence Standards Bodies
How to Win Friends and Influence Standards BodiesDomenic Denicola
 
Unit Testing for Great Justice
Unit Testing for Great JusticeUnit Testing for Great Justice
Unit Testing for Great JusticeDomenic Denicola
 
Understanding the Node.js Platform
Understanding the Node.js PlatformUnderstanding the Node.js Platform
Understanding the Node.js PlatformDomenic Denicola
 

Más de Domenic Denicola (8)

ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
Streams for the Web
Streams for the WebStreams for the Web
Streams for the Web
 
After Return of the Jedi
After Return of the JediAfter Return of the Jedi
After Return of the Jedi
 
The State of JavaScript
The State of JavaScriptThe State of JavaScript
The State of JavaScript
 
How to Win Friends and Influence Standards Bodies
How to Win Friends and Influence Standards BodiesHow to Win Friends and Influence Standards Bodies
How to Win Friends and Influence Standards Bodies
 
The Extensible Web
The Extensible WebThe Extensible Web
The Extensible Web
 
Unit Testing for Great Justice
Unit Testing for Great JusticeUnit Testing for Great Justice
Unit Testing for Great Justice
 
Understanding the Node.js Platform
Understanding the Node.js PlatformUnderstanding the Node.js Platform
Understanding the Node.js Platform
 

Último

Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 

Último (20)

Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 

ES6 is Nigh

  • 1. ES6 is Nigh A PRESENTATION ON THE FUTURE OF JAVASCRIPT http://es6isnigh.com
  • 3. Domenic Denicola  https://github.com/domenic  https://npmjs.org/~domenic  @esdiscuss @domenic
  • 4. History  ES1 → ES3: try/catch, do/while, switch, regular expressions, …  ES3 → ES5: accessors, strict mode (static scoping), object reflection, JSON, array extras, …  Now, ES5 → ES6 @domenic
  • 5. Why? “Stagnation on the web is a social ill.” —Brendan Eich http://news.ycombinator.com/item?id=4634735 @domenic
  • 6. Why? Say what you mean! @domenic
  • 8. All ES5 code is ES6 code and has the same meaning  No modes One   No backwards incompatibility No “fixes” JavaScript  ES6 is purely additive @domenic
  • 10. Better object literals Spread Const Sets and maps Rest Block scoping Destructuring Iteration @domenic
  • 12. Parameter defaults Arrow functions Classes Modules @domenic
  • 14. Tail calls Template strings Binary data Unicode Symbols Weak maps and sets Generators Proxies @domenic
  • 15. Better object literals  Rest and spread Comfort   Block scoping Const  Destructuring  Sets and maps  Iteration @domenic
  • 16. Better Object Literals var empireJS = { attendees: "many", preParty() { console.log(this.attendees + " attendees are partying!"); } }; var conferences = { empireJS, cascadiaJS }; @domenic
  • 17. Rest and Spread function sprintf(format, ...params) { assert(Array.isArray(params)); } Math.max(...array); Math.max(0, ...array, 5, ...array2); new Date(...dateFields); array.push(...array2); @domenic
  • 18. More Spread var prequels = ["tpm", "aotc", "rots"]; var movies = [...prequels, "anh", "tesb", "rotj"]; var nodeList = document.querySelectorAll("div"); [...nodeList].forEach(function (node) { // finally! }); @domenic
  • 19. Block Scoping let log = console.log.bind(console); function f(x) { if (Math.random() > 0.5) { let log = Math.log; x = log(x); } log("result: " + x); } @domenic
  • 20. Block Scoping let log = console.log; function f(x) { // 5 refactorings later if (Math.random() > 0.5) { x = log(x); // error! used a `let` before declaration. let log = Math.log; } log("result: " + x); } f(Math.E); // but, the error doesn’t occur until here: runtime, not static. @domenic
  • 21. Block Scoping function f(x) { // 10 refactorings later let log = console.log; let log = Math.log; // `SyntaxError`! No double `let`s. if (Math.random() > 0.5) { x = log(x); } log("result: " + x); } @domenic
  • 22. Block Scoping for (let i = 0; i < a.length; ++i) { els[i].onclick = function () { return a[i]; }; } assert(typeof i === "undefined"); assert(els[0].onclick() === a[0]); @domenic
  • 23. Block Scoping if (Math.random() > 0.5) { function go() { console.log("gone!"); } el.onmousedown = go; el.ontouchstart = go; } assert(typeof go === "undefined"); @domenic
  • 24. Const const PI = Math.PI; PI = 22/7; // error! cannot reassign const E; // SyntaxError! need initializer // plus all the yummy `let` semantics @domenic
  • 25. Destructuring [a, b] = [b, a]; let [x, y] = f(); let re = /([a-z]+)(s)(.*)([^a-z])/; let [, hello, space, world, bang] = re.exec("hello world!"); let [first, ...allButFirst] = document.querySelectorAll("p"); @domenic
  • 26. Destructuring let { tagName, textContent } = el; let { viewModel, bindings } = doDataBinding(); let { firstElementChild: first, lastElementChild: last } = el; let { firstElementChild: { tagName: firstTag } } = document.body; let { children: [first, ...others] } = document.body; @domenic
  • 27. Destructuring function runTests({ reporter, ui }, [firstFile, ...others]) { // ... } try { runTests({ reporter: "spec", ui: "tdd" }, ["test1", "test2"]); } catch ({ message }) { console.error(message); } @domenic
  • 28. Sets and Maps let s = new Set([...document.body.children]); // `s.has`, `s.add`, `s.delete` — too obvious // let's do something cool instead: function unique(array) { return [...new Set(array)]; // O(n)! } let m = new Map(); m.add(model, new ViewModel(model)); // objects as keys! // otherwise obvious — `m.has`, `m.get`, `m.add`, `m.delete` @domenic
  • 29. Iteration for (let x of ["one", "two", "three"]) { } for (let value of set) { } for (let [key, value] of map) { } // customizing iteration requires some magic @domenic
  • 30. Parameter defaults  Arrow functions  Classes Cowpaths  Modules @domenic
  • 31. Parameter Defaults function fill(mug, liquid = "coffee") { // … } function pour(person, mug1 = person.mug, mug2 = new Mug()) { // … } pour(domenic, undefined, you.mug); @domenic
  • 32. Arrow Functions array.map(x => x * x); array.filter(x => x === this.target); [...$("p")].forEach((el, i) => { el.textContent = "The #" + i + " <p>"; }); @domenic
  • 33. Classes class EventEmitter { constructor() { this.domain = domain.active; } emit(type, ...args) { /* ... */ } // ... } class Stream extends EventEmitter { pipe(dest, options) { /* ... */ } } @domenic
  • 34. Modules import http from "http"; import { read, write } from "fs"; import { draw: drawShape } from "graphics"; import { draw: drawGun } from "cowboy"; export sprintf; export function $(selector) { return [...document.querySelectorAll(selector)]; }; // what about `module.exports = aFunction`? @domenic
  • 35. Proper tail calls  Template strings  Binary data  Unicode  Symbols Magic  Weak sets and maps  Generators  Proxies @domenic
  • 36. Proper Tail Calls "use strict"; // for its effect on arguments/caller. function sumTo(n, accumulator = 0) { return n === 0 ? accumulator : sumTo(n - 1, accumulator); } sumTo(123456); // no “too much recursion error”; no stack usage at all in fact! @domenic
  • 37. Template Strings let x = 1; let y = 2; let s = `${x} + ${y} = ${x + y}`; let multiline = `<html> <body> Hello world! </body> </html>`; @domenic
  • 38. Template Strings let url = "http://example.com/"; let query = "Hello & Goodbye"; let s = safehtml` <a href="${url}?q=${query}“ onclick="alert('${query}')"> ${query} </a>`; assert(s === `<a href="http://example.com/?q=Hello%20%26%20Goodbye" onclick="alert('Hello&#32;x26&#32;Goodbye')"> Hello &amp; Goodbye </a>`); @domenic
  • 39. Binary Data const Point2D = new StructType({ x: uint32, y: uint32 }); const Color = new StructType({ r: uint8, g: uint8, b: uint8 }); const Pixel = new StructType({ point: Point2D, color: Color }); const Triangle = new ArrayType(Pixel, 3); let t = new Triangle([ { point: { x: 0, y: 0 }, color: { r: 255, g: 255, b: 255 } }, { point: { x: 5, y: 5 }, color: { r: 128, g: 0, b: 0 } }, { point: { x: 10, y: 0 }, color: { r: 0, g: 0, b: 128 } } ]); @domenic
  • 40. Unicode // Emoji take more than two bytes: one code *point*, two code *units*. let x = "😁 "; let y = "uD83DuDE01"; // ES5 let z = "u{1F638}"; // ES6 assert(x === y && y === z); assert(x.charCodeAt(0) === 0xD83D); // ES5 assert(x.charCodeAt(1) === 0xDE01); // ES5 assert(x.codePointAt(0) === 0x1F638); // ES6 https://gist.github.com/1850768 @domenic
  • 41. Unicode // iterator goes over code *points*, yay. for (let c of "😁 ") { assert(c === "😁 "); } assert("😁 ".length === 2); // can't break the web, still code units :-/ // The "u" flag on regexes adds lots of Unicode fixes, e.g.: assert(/^.$/.test("😁 ") === false); assert(/^.$/u.test("😁 ") === true); @domenic
  • 42. Symbols function S3Bucket(apiKey, apiSecret) { this._apiKey = apiKey; this._apiSecret = apiSecret; } S3Bucket.prototype.request = function (url) { let signature = calculateSignature(this._apiKey, this._apiSecret); this._sendRequest(url, signature); }; S3Bucket.prototype._sendRequest = function () { }; @domenic
  • 43. Symbols function S3Bucket(apiKey, apiSecret) { this.request = function (url) { let signature = calculateSignature(apiKey, apiSecret); sendRequest(url, signature); }; function sendRequest() { } } @domenic
  • 44. Symbols let apiKey = new Symbol(), apiSecret = new Symbol(), sendRequest = new Symbol(); function S3Bucket(theApiKey, theApiSecret) { this[apiKey] = theApiKey; this[apiSecret] = theApiSecret; } S3Bucket.prototype.request = function (url) { let signature = calculateSignature(this[apiKey], this[apiSecret]); this[sendRequest](url, signature); }; S3Bucket.prototype[sendRequest] = function () { }; @domenic
  • 45. Symbols private @apiKey, @apiSecret, @sendRequest; function S3Bucket(theApiKey, theApiSecret) { this.@apiKey = theApiKey; this.@apiSecret = theApiSecret; } S3Bucket.prototype.request = function (url) { let signature = calculateSignature(this.@apiKey, this.@apiSecret); this.@sendRequest(url, signature); }; S3Bucket.prototype.@sendRequest = function () { }; @domenic
  • 46. Weak Sets let trustedObjects = new WeakSet(); function createTrustedObject() { let trusted = { /* ... */ }; trustedObjects.add(trusted); return trusted; } function isTrusted(obj) { return trustedObjects.has(obj); } @domenic
  • 47. Weak Maps let cache = new WeakMap(); function calculateChecksum(httpResponse) { if (cache.has(httpResponse)) { return cache.get(httpResponse); } let checksum = calculateChecksum(httpResponse); cache.set(httpResponse, checksum); return checksum; } @domenic
  • 48. Symbols Again let checksum = new Symbol(); function calculateChecksum(httpResponse) { if (!(checksum in httpResponse)) { httpResponse[checksum] = calculateChecksum(httpResponse); } return httpResponse[checksum]; } @domenic
  • 49. Back to Iterators import { iterator } from "@iter"; // a symbol in the standard library let obj = {}; obj[iterator] = function () { return { next() { return 5; } }; }; for (let n of obj) { assert(n === 5); } @domenic
  • 50. Generators function* naturalNumbers() { let current = 0; while (true) { yield current++; } } let seq = naturalNumbers(); assert(seq.next() === 0); assert(seq.next() === 1); assert(seq.next() === 2); @domenic
  • 51. Generators Return Iterators // Generator functions return iterators for (let n of naturalNumbers()) { console.log(n); } // Use them to create your own iterators obj[iterator] = function* () { yield 5; }; @domenic
  • 52. Generators Are Shallow Coroutines function* demo() { console.log("a"); yield; console.log("b"); yield; console.log("c"); } let seq = demo(); // “paused,” with no code executed seq.next(); // execution resumes; logs "a"; then pause seq.next(); // execution resumes; logs "b"; then pause seq.next(); // execution resumes; logs "c"; enters “done” state seq.next(); // throws `StopIteration` @domenic
  • 53. Shallow Coroutines for Async spawn(function* () { try { let post = yield getJSON("/post/1.json"); let comments = yield getJSON(post.commentURL); yield fadeInCommentUI(); comments.innerHTML = template(comments); } catch (e) { comments.innerText = e.message; } }); @domenic http://taskjs.org/
  • 54. Proxies let handler = { getOwnPropertyDescriptor(target, name) { }, getOwnPropertyNames(target) { }, getPrototypeOf(target) { }, defineProperty(target, name, desc) { }, deleteProperty(target, name) { }, freeze(target) { }, seal(target) { }, preventExtensions(target) { }, isFrozen(target) { }, isSealed(target) { }, isExtensible(target) { }, ⋮ @domenic
  • 55. Proxies ⋮ has(target, name) { }, hasOwn(target, name) { }, get(target, name, receiver) { }, set(target, name, val, receiver) { }, enumerate*(target) { }, keys(target) { }, apply(target, thisArg, args) { }, construct(target, args) { } }); let theTarget = {}; let virtualObject = new Proxy(theTarget, handler); @domenic
  • 56. The future of JS: it’s important!  Follow @esdiscuss.  Stay tuned for more on es6isnigh.com. The Future Now  Be adventurous; use a transpiler!  Skate where the puck will be. @domenic

Notas del editor

  1. Intro with Michael’s concernsBrendan’s argument:Stagnation costs: IE6, Android 2.x. Developers get unhappy. CoffeeScript!Some parties might use such a crisis, plus their large browser marketshare, to force proprietary solutions: Silverlight (“WPF Everywhere”), Dart, NaCl. People will start using them because they can move faster than this language from 1998.This is not acceptable. What we’ve built is beautiful, and starting over means re-learning all those lessons. Too much code and developer brainpower gets thrown away.Skate where the puck will be.
  2. Classes, modules, callbacks, Object.keys(array).forEach(function () { }), arg = arg || default
  3. Iterate over data, not properties.