SlideShare a Scribd company logo
@falsyvalues



ECMAScript > Future

    Dmitry A. Soshnikov
http://dmitrysoshnikov.com
Future > ES6
let : block scope
Block scope
// ES3


if (false) {
   var logLevel = 10;
}

alert(logLevel); // ?
Block scope
// ES3
var logLevel; // = undefined;
                                                 All variables are
if (false) {                                      created before
                                               code execution – on
   logLevel = 10;                              entering the context.

}                                              A so-called “hoisting”
                                                    of variables.
alert(logLevel); // undefined
See: http://dmitrysoshnikov.com/notes/note-4-two-words-about-hoisting/
Block scope
// ES6 Harmony


if (false) {
   let logLevel = 10;
}

alert(logLevel); // ReferenceError
Block scope
// ES3, ES5


var handlers = [];              handlers[0](); // ?
                                handlers[1](); // ?
for (var k = 0; k < 3; k++) {   handlers[2](); // ?
  handlers[k] = function () {
     alert(k);
  };
}
Block scope
// ES3, ES5


var handlers = [];              handlers[0](); // 3
var k;                          handlers[1](); // 3
for (k = 0; k < 3; k++) {       handlers[2](); // 3
  handlers[k] = function () {
     alert(k);
  };
}
let : block scope
ES3, ES5                           ES6
for (var k = 0; k < 3; k++) {       for (let k = 0; k < 3; k++) {
                                      let x = k;
  (function (x) {
                                      handlers[x] = function () {
     handlers[x] = function () {
                                         alert(x);
        alert(x);
                                      };
     };                             }
  })(k);
}

handlers[0](); // 0                handlers[0](); // 0
let : definition, statement, expression
let x = 10;                            // let-definition
let y = 20;

let (x = x * 2, y = 30) {
   console.log(x + y); // 50           // let-statement

}

console.log(x + y); // 30

console.log(let (x = 100) x); // 100   // let-expression

console.log(x); // 10
const : constants
const : constants

const MAX_SIZE = 100;

// cannot be redeclared (let, var, etc.)
let MAX_SIZE = 100; // error
const : constant functions

const registerUser() {
  // implementation
}

// redeclaration error (function, let, var)
function registerUser() { ... }
Function parameter
  default values
Function parameter
            default values
function handleRequest(data, method) {
  method = method || “GET”;
  ...
}
Function parameter
            default values
function handleRequest(data, method) {
  method = method || “GET”;
  ...
}
function handleRequest(data, method = “GET”) {
  ...
}
Destructuring
or “non-strict pattern-matching”
Destructuring: arrays

// for arrays
let [x, y] = [10, 20, 30]; // non-strict matching

console.log(x, y); // 10, 20
Destructuring: objects

// for objects
let user = {name: “Ann”, location: {x: 10, y: 20}};

let {name: n, location: {x: x, y: y}} = user;

console.log(n, x, y); // “Ann”, 10, 20
Destructuring of
           function parameters

function Panel(config) {
  var title = config.title;
  var x = config.pos[0];        Too “noisy”
  var y = config.pos[1];
  return title + x + y;
}
new Panel({title: “Users”, pos: [10, 15]});
Destructuring of
            function parameters

function Panel({title: title, pos: [x, y]}) {
  return title + x + y;
}

let config = {title: “Users”, pos: [10, 15]};

new Panel(config);
Destructuring:
           exchange of variables

// exchange two variables without third?

let x = 10;
let y = 20;

[x, y] = [y, x]; // easy
Replacement of arguments:
   ”rest” and ”spread”
Object arguments
// ES3, ES5

function format(pattern /*, rest */) {
  var rest = [].slice.call(arguments, 1);
  var items = rest.filter(function (x) { return x > 1});
  return pattern.replace(“%v”, items);
}

format(“scores: %v”, 1, 5, 3); // scores: 5, 3
Good bye, arguments
// ES3, ES5

function format(pattern /*, rest */) {
  var rest = [].slice.call(arguments, 1); // complicated
  var items = rest.filter(function (x) { return x > 1});
  return pattern.replace(“%v”, items);
}

format(“scores: %v”, 1, 5, 3); // scores: 5, 3
Hello, ”rest”
// ES6 aka Harmony

function format(pattern, …rest) { // real array
  var items = rest.filter(function (x) { return x > 1});
  return pattern.replace(“%v”, items);
}

format(“scores: %v”, 1, 5, 3); // scores: 5, 3
And also ”spread”
// ES6 aka Harmony

function showUser(name, age, weight) {
  return name + “:” + age + weight;
}

let user = [“Alex”, 28, 130];

showUser(…user); // ok
showUser.apply(null, user); // desugared
”rest” of arrays with destructuring
// ES6 aka Harmony

let userInfo = [“John”, 14, 21, 3];
let [name, ...scores] = userInfo;

console.log(name); // “John”
console.log(scores); // [14, 21, 3]
Short notations
Short notation in
                 destructuring
let 3DPoint = {x: 20, y: 15, z: 1};

// full notation
let {x: x, y: y, z: z} = 3DPoint;

// short notation
let {x, y, z} = 3DPoint;
Short syntax of functions.
                -> functions
// casual functions
[1, 2, 3].map(function (x) { return x * x; }); // [1, 4, 9]

// -> functions
[1, 2, 3].map((x) -> x * x); // [1, 4, 9]

Syntactically:
  • optional return;
  • -> instead of function
  • No curly braces are required
-> functions: examples
// Empty arrow function is minimal-length
let empty = ->;

// Expression bodies needs no parentheses or braces
let square= (x) -> x * x;

// Without parameters
let getUser = -> users[current];

// Statement body needs braces
let users = [{name: “Mark”, age: 28}, {name: “Sarah”, age: 26}];
users.forEach((user, k) -> { if (k > 2) console.log(user.name, k) });
simple functions: dynamic this

function Account(customer, cart) {
  this.customer = customer;
  this.cart = cart;
  $(‘#shopping-cart').on('click', function (event) {
      this.customer.purchase(this.cart); // error on click
  });
}                                    Solutions:
                                    var that = this;
                                      .bind(this)
=> functions: lexical this

function Account(customer, cart) {
  this.customer = customer;
  this.cart = cart;
  $(‘#shopping-cart').on('click', (event) =>
     this.customer.purchase(this.cart); // ok
  );
}
But... Currently block
functions are on agenda!
Short syntax of functions.
              Block-functions
// casual functions
[1, 2, 3].map(function (x) { return x * x; }); // [1, 4, 9]

// block-functions, Ruby’s way
[1, 2, 3].map {|x| x * x} // [1, 4, 9]

Syntactically:
  • optional return;
  • |x| instead of function
  • No call parens
Proxy objects : meta level
Proxy-objects
/* handler –meta-level handler
 * proto – prototype of the proxy object */
Proxy.create(handler, [proto])

/* handler – meta-handler
 * call – call trap
 * construct – construction trap */
Proxy.createFunction(handler, [call, [construct]])

See: http://wiki.ecmascript.org/doku.php?id=harmony:proxies
Proxy-objects
 // original object       // proxied object
 let point = {            let loggedPoint = Proxy.create({
    x: 10,                   get: function (rcvr, name) {
    y: 20                       console.log(“get: ”, name);
 };                             return point[name];
                             },
                             set: function (rcvr, name, value) {
Trap of getting of              console.log(“set: ”, name, value);
   properties
                                point[name] = value;
                             }
Trap of setting the       }, Object.getPrototypeOf(point));
    properties
Proxy-objects
                                    // proxied object
    Meta-handler                    let loggedPoint = Proxy.create({
                                       get: function (rcvr, name) {
// reading trap                           console.log(“get: ”, name);
loggedPoint.x; // get: x, 10              return point[name];
                                       },
// writing trap                        set: function (rcvr, name, value) {
loggedPoint.x = 20; // set: x, 20         console.log(“set: ”, name, value);
                                          point[name] = value;
// reflected on the original object    }
point.x; // 20                      }, Object.getPrototypeOf(point));
Callable Proxy-objects
// original object            // proxied object
let point = {x: 10, y: 20};   let loggedPoint = Proxy.createFunction({
                                 get: function (rcvr, name) {
function callTrap() {               console.log(“get: ”, name);
  console.log(“call”);              return foo[name];
}                                },
                                 set: function (rcvr, name, value) {
function constructTrap() {
                                    console.log(“set: ”, name, value);
  console.log(“construct”);
                                    foo[name] = value;
}
                                 }
                              }, callTrap, constructTrap);
loggedPoint(10, 20);
new loggedPoint(100);
                                                         Catching of
                                 Catching of calling
                                                        construction
Proxy : simple generic read logger
function logged(object) {
  return Proxy.create({
     get: function (rcvr, name) {
       console.log(“get:”, name);
       return object[name];
     }
  }, Object.getPrototypeOf(object));
}

let connector = logged({
    join: function (node) { ... }
});

connector.join(“store@master-node”); // get: join
Proxy : examples
// loggers (on reading and writing)
Proxy.create(logHandler(object));

// multiple inheritance (delegation-based mixins)
Proxy.create(mixin(obj1, obj2));

// noSuchMethod
Proxy.create(object, noSuchMethod)

// Arrays with negative indices (as in Python)
let a = Array.new([1, 2, 3]);
console.log(a[-1]); // 3
a[-1] = 10; console.log(a); // [1, 2, 10]

See: https://github.com/DmitrySoshnikov/es-laboratory/tree/master/examples
Modules system
Modules in ES3, ES5
var DBLayer = (function (global) {
   /* save original */
   var originalDBLayer = global.DBLayer;
   function noConflict() {
      global.DBLayer = originalDBLayer;    1.   Create local scope
   }                                       2.   Restoring function
   /* implementation */                    3.   Implementation
                                           4.   Public API
   function query() { ... }
   /* exports, public API */
   return {
      noConflict: noConflict,
      query: query
   };
})(this);
Modules in ES3, ES5
var DBLayer = (function (global) {
   /* save original */
   var originalDBLayer = global.DBLayer;
   function noConflict() {
      global.DBLayer = originalDBLayer;    1.    Create local scope
   }                                       2.    Restoring function
   /* implementation */                    3.    Implementation
                                           4.    Public API
   function query() { ... }
   /* exports, public API */
                                                Too much of “noise”.
   return {                                     A “sugar” is needed.
      noConflict: noConflict,
      query: query
   };
})(this);
Modules in ES6
module DBLayer {
  export function query(s) { ... }
  export function connection(...args) { ... }
}

import DBLayer.*; // import all

import DBLayer.{query, connection: attachTo}; // import only needed exports

query(“SELECT * FROM books”).format(“escape | split”);

attachTo(“/books/store”, {
   onSuccess: function (response) { ... }
})
External modules in ES6
// on file system
module $ = require(“./library/selector.js”);

// globally, from the Net, we define the name of the module
module CanvasLib = require(“http:// ... /js-modules/canvas.js”);

// use either directly
let rect = new CanvasLib.Rectangle({width: 30, height: 40, shadow: true});

// or import needed exports
import CanvasLib.{Triangle, rotate};

rotate(-30, new Triangle($.query(...params)));
Require module and
        import with destructuring


// require the module and directly
// import via pattern-matching
let {read, format} = require(“fs.js”);

// use the imported binding
read(“storage/accounts.dat”). format(“%line: value”)
Generators : iterators,
coroutines/multi-tasks
Generators : yield
                      “infinite” streams
function fibonacci() {
  let [prev, curr] = [0, 1];
  while (true) {
    [prev, curr] = [curr, prev + curr];
    yield curr;
                                          Next
                                       entry point    Manual iteration:
    }
}                                                    let seq = fibonacci();
                                                     seq.next(); // 1
for (let n in fibonacci()) {                         seq.next(); // 2
                                                     seq.next(); // 3
  // truncate the sequence at 1000                   seq.next(); // 5
  if (n > 1000) break; // 1, 2, 3, 5, 8 ...          seq.next(); // 8
  console.log(n);
}
Generators : yield
                      custom iterators
function iterator(object) {
  for (let k in object) {
    yield [k, object[k]];               Proposed iterators of ES6:

  }                                     // by properties (key+value)
                                        for (let [k, v] in properties(foo))
}
                                        // by values
let foo = {x: 10, y: 20};               for (let v in values(foo))

for (let [k, v] in iterator(foo)) {     // by property names
  console.log(k, v); // x 10, y 20      for (let k in keys(foo))
}

See: http://wiki.ecmascript.org/doku.php?id=strawman:iterators
See: https://gist.github.com/865630
Generators : yield
            asynchronous programming
Callbacks                                   Coroutines
xhr("data.json", function (data) {          new Task(function () {
    xhr("user.dat", function (user) {        let data = yield xhr("data.json“);
      xhr("user/save/", function (save) {    let user = yield xhr(“user.dat“);
         /* code */                          let save = yield xhr(“/user/save“);
      }                                      /* code */
    }                                       });
});

/* other code */                            /* other code */
Generators : yield
     cooperative multitasks (threads)
let thread1 = new Thread(function (...args) {
   for (let k in values([1, 2, 3])) yield k + “ from thread 1”;
}).start();

let thread2 = new Thread(function (...args) {
   for (let k in values([1, 2, 3])) yield k + “ from thread 2”;
}).start();

// 1 from thread 1
// 2 from thread 1
// 1 from thread 2
// 3 from thread 1
// 2 from thread 2
// etc.
Array comprehensions
Array comprehensions
// map + filter way
let scores = [1, 7, 4, 9]
  .filter(function (x) { return x > 5 })
  .map(function (x) { return x * x }); // [49, 81]
Array comprehensions
// map + filter way
let scores = [1, 7, 4, 9]
  .filter(function (x) { return x > 5 })
  .map(function (x) { return x * x }); // [49, 81]


// array comprehensions
let scores = [x * x for (x in values([1, 7, 4, 9])) if (x > 5)];
Thanks for your attention


     Dmitry Soshnikov

dmitry.soshnikov@gmail.com
  http://dmitrysoshnikov.com

      @DmitrySoshnikov
Ad

More Related Content

What's hot (20)

Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
Kyung Yeol Kim
 
Testing Backbone applications with Jasmine
Testing Backbone applications with JasmineTesting Backbone applications with Jasmine
Testing Backbone applications with Jasmine
Leon van der Grient
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
Leo Hernandez
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
Cory Forsyth
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
Visual Engineering
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
Piotr Lewandowski
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
Brendan Eich
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
RameshNair6
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Raimonds Simanovskis
 
Why Every Tester Should Learn Ruby
Why Every Tester Should Learn RubyWhy Every Tester Should Learn Ruby
Why Every Tester Should Learn Ruby
Raimonds Simanovskis
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
Manoj Kumar
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7
Dongho Cho
 
Rails on Oracle 2011
Rails on Oracle 2011Rails on Oracle 2011
Rails on Oracle 2011
Raimonds Simanovskis
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
Jeado Ko
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
Solution4Future
 
Reactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaReactive Access to MongoDB from Scala
Reactive Access to MongoDB from Scala
Hermann Hueck
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
Sebastiano Armeli
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
boyney123
 
Rust ⇋ JavaScript
Rust ⇋ JavaScriptRust ⇋ JavaScript
Rust ⇋ JavaScript
Ingvar Stepanyan
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
FITC
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
Kyung Yeol Kim
 
Testing Backbone applications with Jasmine
Testing Backbone applications with JasmineTesting Backbone applications with Jasmine
Testing Backbone applications with Jasmine
Leon van der Grient
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
Cory Forsyth
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
Visual Engineering
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
Brendan Eich
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
RameshNair6
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Raimonds Simanovskis
 
Why Every Tester Should Learn Ruby
Why Every Tester Should Learn RubyWhy Every Tester Should Learn Ruby
Why Every Tester Should Learn Ruby
Raimonds Simanovskis
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7
Dongho Cho
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
Jeado Ko
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
Solution4Future
 
Reactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaReactive Access to MongoDB from Scala
Reactive Access to MongoDB from Scala
Hermann Hueck
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
Sebastiano Armeli
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
boyney123
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
FITC
 

Viewers also liked (11)

혁신적인 웹컴포넌트 라이브러리 - Polymer
혁신적인 웹컴포넌트 라이브러리 - Polymer혁신적인 웹컴포넌트 라이브러리 - Polymer
혁신적인 웹컴포넌트 라이브러리 - Polymer
Jae Sung Park
 
Functional Reactive Programming With RxSwift
Functional Reactive Programming With RxSwiftFunctional Reactive Programming With RxSwift
Functional Reactive Programming With RxSwift
선협 이
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streams
mattpodwysocki
 
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
Jong Wook Kim
 
Functional Reactive Programming with RxJS
Functional Reactive Programming with RxJSFunctional Reactive Programming with RxJS
Functional Reactive Programming with RxJS
stefanmayer13
 
[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍
NAVER D2
 
RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015
Ben Lesh
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS
偉格 高
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
NAVER / MusicPlatform
 
System webpack-jspm
System webpack-jspmSystem webpack-jspm
System webpack-jspm
Jesse Warden
 
Angular2 ecosystem
Angular2 ecosystemAngular2 ecosystem
Angular2 ecosystem
Kamil Lelonek
 
혁신적인 웹컴포넌트 라이브러리 - Polymer
혁신적인 웹컴포넌트 라이브러리 - Polymer혁신적인 웹컴포넌트 라이브러리 - Polymer
혁신적인 웹컴포넌트 라이브러리 - Polymer
Jae Sung Park
 
Functional Reactive Programming With RxSwift
Functional Reactive Programming With RxSwiftFunctional Reactive Programming With RxSwift
Functional Reactive Programming With RxSwift
선협 이
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streams
mattpodwysocki
 
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
Jong Wook Kim
 
Functional Reactive Programming with RxJS
Functional Reactive Programming with RxJSFunctional Reactive Programming with RxJS
Functional Reactive Programming with RxJS
stefanmayer13
 
[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍
NAVER D2
 
RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015
Ben Lesh
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS
偉格 高
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
NAVER / MusicPlatform
 
System webpack-jspm
System webpack-jspmSystem webpack-jspm
System webpack-jspm
Jesse Warden
 
Ad

Similar to FalsyValues. Dmitry Soshnikov - ECMAScript 6 (20)

JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
Luis Vendrame
 
Javascript
JavascriptJavascript
Javascript
Vlad Ifrim
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
Bruno Scopelliti
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
Binary Studio
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
msemenistyi
 
ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyond
Francis Johny
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
Adam L Barrett
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
Richard Paul
 
Call stack, event loop and async programming
Call stack, event loop and async programmingCall stack, event loop and async programming
Call stack, event loop and async programming
Masters Academy
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
erockendude
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
Fin Chen
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
Alfonso Peletier
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
Santosh Wadghule
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3
Simon Su
 
Internal workshop es6_2015
Internal workshop es6_2015Internal workshop es6_2015
Internal workshop es6_2015
Miguel Ruiz Rodriguez
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
Justin Alexander
 
JavaScript Lessons 2023
JavaScript Lessons 2023JavaScript Lessons 2023
JavaScript Lessons 2023
Laurence Svekis ✔
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
Michael Girouard
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
Michiel Borkent
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
Luis Vendrame
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
msemenistyi
 
ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyond
Francis Johny
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
Adam L Barrett
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
Richard Paul
 
Call stack, event loop and async programming
Call stack, event loop and async programmingCall stack, event loop and async programming
Call stack, event loop and async programming
Masters Academy
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
erockendude
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
Fin Chen
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
Alfonso Peletier
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3
Simon Su
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
Michiel Borkent
 
Ad

Recently uploaded (20)

Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 

FalsyValues. Dmitry Soshnikov - ECMAScript 6

  • 1. @falsyvalues ECMAScript > Future Dmitry A. Soshnikov http://dmitrysoshnikov.com
  • 3. let : block scope
  • 4. Block scope // ES3 if (false) { var logLevel = 10; } alert(logLevel); // ?
  • 5. Block scope // ES3 var logLevel; // = undefined; All variables are if (false) { created before code execution – on logLevel = 10; entering the context. } A so-called “hoisting” of variables. alert(logLevel); // undefined See: http://dmitrysoshnikov.com/notes/note-4-two-words-about-hoisting/
  • 6. Block scope // ES6 Harmony if (false) { let logLevel = 10; } alert(logLevel); // ReferenceError
  • 7. Block scope // ES3, ES5 var handlers = []; handlers[0](); // ? handlers[1](); // ? for (var k = 0; k < 3; k++) { handlers[2](); // ? handlers[k] = function () { alert(k); }; }
  • 8. Block scope // ES3, ES5 var handlers = []; handlers[0](); // 3 var k; handlers[1](); // 3 for (k = 0; k < 3; k++) { handlers[2](); // 3 handlers[k] = function () { alert(k); }; }
  • 9. let : block scope ES3, ES5 ES6 for (var k = 0; k < 3; k++) { for (let k = 0; k < 3; k++) { let x = k; (function (x) { handlers[x] = function () { handlers[x] = function () { alert(x); alert(x); }; }; } })(k); } handlers[0](); // 0 handlers[0](); // 0
  • 10. let : definition, statement, expression let x = 10; // let-definition let y = 20; let (x = x * 2, y = 30) { console.log(x + y); // 50 // let-statement } console.log(x + y); // 30 console.log(let (x = 100) x); // 100 // let-expression console.log(x); // 10
  • 12. const : constants const MAX_SIZE = 100; // cannot be redeclared (let, var, etc.) let MAX_SIZE = 100; // error
  • 13. const : constant functions const registerUser() { // implementation } // redeclaration error (function, let, var) function registerUser() { ... }
  • 14. Function parameter default values
  • 15. Function parameter default values function handleRequest(data, method) { method = method || “GET”; ... }
  • 16. Function parameter default values function handleRequest(data, method) { method = method || “GET”; ... } function handleRequest(data, method = “GET”) { ... }
  • 18. Destructuring: arrays // for arrays let [x, y] = [10, 20, 30]; // non-strict matching console.log(x, y); // 10, 20
  • 19. Destructuring: objects // for objects let user = {name: “Ann”, location: {x: 10, y: 20}}; let {name: n, location: {x: x, y: y}} = user; console.log(n, x, y); // “Ann”, 10, 20
  • 20. Destructuring of function parameters function Panel(config) { var title = config.title; var x = config.pos[0]; Too “noisy” var y = config.pos[1]; return title + x + y; } new Panel({title: “Users”, pos: [10, 15]});
  • 21. Destructuring of function parameters function Panel({title: title, pos: [x, y]}) { return title + x + y; } let config = {title: “Users”, pos: [10, 15]}; new Panel(config);
  • 22. Destructuring: exchange of variables // exchange two variables without third? let x = 10; let y = 20; [x, y] = [y, x]; // easy
  • 23. Replacement of arguments: ”rest” and ”spread”
  • 24. Object arguments // ES3, ES5 function format(pattern /*, rest */) { var rest = [].slice.call(arguments, 1); var items = rest.filter(function (x) { return x > 1}); return pattern.replace(“%v”, items); } format(“scores: %v”, 1, 5, 3); // scores: 5, 3
  • 25. Good bye, arguments // ES3, ES5 function format(pattern /*, rest */) { var rest = [].slice.call(arguments, 1); // complicated var items = rest.filter(function (x) { return x > 1}); return pattern.replace(“%v”, items); } format(“scores: %v”, 1, 5, 3); // scores: 5, 3
  • 26. Hello, ”rest” // ES6 aka Harmony function format(pattern, …rest) { // real array var items = rest.filter(function (x) { return x > 1}); return pattern.replace(“%v”, items); } format(“scores: %v”, 1, 5, 3); // scores: 5, 3
  • 27. And also ”spread” // ES6 aka Harmony function showUser(name, age, weight) { return name + “:” + age + weight; } let user = [“Alex”, 28, 130]; showUser(…user); // ok showUser.apply(null, user); // desugared
  • 28. ”rest” of arrays with destructuring // ES6 aka Harmony let userInfo = [“John”, 14, 21, 3]; let [name, ...scores] = userInfo; console.log(name); // “John” console.log(scores); // [14, 21, 3]
  • 30. Short notation in destructuring let 3DPoint = {x: 20, y: 15, z: 1}; // full notation let {x: x, y: y, z: z} = 3DPoint; // short notation let {x, y, z} = 3DPoint;
  • 31. Short syntax of functions. -> functions // casual functions [1, 2, 3].map(function (x) { return x * x; }); // [1, 4, 9] // -> functions [1, 2, 3].map((x) -> x * x); // [1, 4, 9] Syntactically: • optional return; • -> instead of function • No curly braces are required
  • 32. -> functions: examples // Empty arrow function is minimal-length let empty = ->; // Expression bodies needs no parentheses or braces let square= (x) -> x * x; // Without parameters let getUser = -> users[current]; // Statement body needs braces let users = [{name: “Mark”, age: 28}, {name: “Sarah”, age: 26}]; users.forEach((user, k) -> { if (k > 2) console.log(user.name, k) });
  • 33. simple functions: dynamic this function Account(customer, cart) { this.customer = customer; this.cart = cart; $(‘#shopping-cart').on('click', function (event) { this.customer.purchase(this.cart); // error on click }); } Solutions: var that = this; .bind(this)
  • 34. => functions: lexical this function Account(customer, cart) { this.customer = customer; this.cart = cart; $(‘#shopping-cart').on('click', (event) => this.customer.purchase(this.cart); // ok ); }
  • 36. Short syntax of functions. Block-functions // casual functions [1, 2, 3].map(function (x) { return x * x; }); // [1, 4, 9] // block-functions, Ruby’s way [1, 2, 3].map {|x| x * x} // [1, 4, 9] Syntactically: • optional return; • |x| instead of function • No call parens
  • 37. Proxy objects : meta level
  • 38. Proxy-objects /* handler –meta-level handler * proto – prototype of the proxy object */ Proxy.create(handler, [proto]) /* handler – meta-handler * call – call trap * construct – construction trap */ Proxy.createFunction(handler, [call, [construct]]) See: http://wiki.ecmascript.org/doku.php?id=harmony:proxies
  • 39. Proxy-objects // original object // proxied object let point = { let loggedPoint = Proxy.create({ x: 10, get: function (rcvr, name) { y: 20 console.log(“get: ”, name); }; return point[name]; }, set: function (rcvr, name, value) { Trap of getting of console.log(“set: ”, name, value); properties point[name] = value; } Trap of setting the }, Object.getPrototypeOf(point)); properties
  • 40. Proxy-objects // proxied object Meta-handler let loggedPoint = Proxy.create({ get: function (rcvr, name) { // reading trap console.log(“get: ”, name); loggedPoint.x; // get: x, 10 return point[name]; }, // writing trap set: function (rcvr, name, value) { loggedPoint.x = 20; // set: x, 20 console.log(“set: ”, name, value); point[name] = value; // reflected on the original object } point.x; // 20 }, Object.getPrototypeOf(point));
  • 41. Callable Proxy-objects // original object // proxied object let point = {x: 10, y: 20}; let loggedPoint = Proxy.createFunction({ get: function (rcvr, name) { function callTrap() { console.log(“get: ”, name); console.log(“call”); return foo[name]; } }, set: function (rcvr, name, value) { function constructTrap() { console.log(“set: ”, name, value); console.log(“construct”); foo[name] = value; } } }, callTrap, constructTrap); loggedPoint(10, 20); new loggedPoint(100); Catching of Catching of calling construction
  • 42. Proxy : simple generic read logger function logged(object) { return Proxy.create({ get: function (rcvr, name) { console.log(“get:”, name); return object[name]; } }, Object.getPrototypeOf(object)); } let connector = logged({ join: function (node) { ... } }); connector.join(“store@master-node”); // get: join
  • 43. Proxy : examples // loggers (on reading and writing) Proxy.create(logHandler(object)); // multiple inheritance (delegation-based mixins) Proxy.create(mixin(obj1, obj2)); // noSuchMethod Proxy.create(object, noSuchMethod) // Arrays with negative indices (as in Python) let a = Array.new([1, 2, 3]); console.log(a[-1]); // 3 a[-1] = 10; console.log(a); // [1, 2, 10] See: https://github.com/DmitrySoshnikov/es-laboratory/tree/master/examples
  • 45. Modules in ES3, ES5 var DBLayer = (function (global) { /* save original */ var originalDBLayer = global.DBLayer; function noConflict() { global.DBLayer = originalDBLayer; 1. Create local scope } 2. Restoring function /* implementation */ 3. Implementation 4. Public API function query() { ... } /* exports, public API */ return { noConflict: noConflict, query: query }; })(this);
  • 46. Modules in ES3, ES5 var DBLayer = (function (global) { /* save original */ var originalDBLayer = global.DBLayer; function noConflict() { global.DBLayer = originalDBLayer; 1. Create local scope } 2. Restoring function /* implementation */ 3. Implementation 4. Public API function query() { ... } /* exports, public API */ Too much of “noise”. return { A “sugar” is needed. noConflict: noConflict, query: query }; })(this);
  • 47. Modules in ES6 module DBLayer { export function query(s) { ... } export function connection(...args) { ... } } import DBLayer.*; // import all import DBLayer.{query, connection: attachTo}; // import only needed exports query(“SELECT * FROM books”).format(“escape | split”); attachTo(“/books/store”, { onSuccess: function (response) { ... } })
  • 48. External modules in ES6 // on file system module $ = require(“./library/selector.js”); // globally, from the Net, we define the name of the module module CanvasLib = require(“http:// ... /js-modules/canvas.js”); // use either directly let rect = new CanvasLib.Rectangle({width: 30, height: 40, shadow: true}); // or import needed exports import CanvasLib.{Triangle, rotate}; rotate(-30, new Triangle($.query(...params)));
  • 49. Require module and import with destructuring // require the module and directly // import via pattern-matching let {read, format} = require(“fs.js”); // use the imported binding read(“storage/accounts.dat”). format(“%line: value”)
  • 51. Generators : yield “infinite” streams function fibonacci() { let [prev, curr] = [0, 1]; while (true) { [prev, curr] = [curr, prev + curr]; yield curr; Next entry point Manual iteration: } } let seq = fibonacci(); seq.next(); // 1 for (let n in fibonacci()) { seq.next(); // 2 seq.next(); // 3 // truncate the sequence at 1000 seq.next(); // 5 if (n > 1000) break; // 1, 2, 3, 5, 8 ... seq.next(); // 8 console.log(n); }
  • 52. Generators : yield custom iterators function iterator(object) { for (let k in object) { yield [k, object[k]]; Proposed iterators of ES6: } // by properties (key+value) for (let [k, v] in properties(foo)) } // by values let foo = {x: 10, y: 20}; for (let v in values(foo)) for (let [k, v] in iterator(foo)) { // by property names console.log(k, v); // x 10, y 20 for (let k in keys(foo)) } See: http://wiki.ecmascript.org/doku.php?id=strawman:iterators See: https://gist.github.com/865630
  • 53. Generators : yield asynchronous programming Callbacks Coroutines xhr("data.json", function (data) { new Task(function () { xhr("user.dat", function (user) { let data = yield xhr("data.json“); xhr("user/save/", function (save) { let user = yield xhr(“user.dat“); /* code */ let save = yield xhr(“/user/save“); } /* code */ } }); }); /* other code */ /* other code */
  • 54. Generators : yield cooperative multitasks (threads) let thread1 = new Thread(function (...args) { for (let k in values([1, 2, 3])) yield k + “ from thread 1”; }).start(); let thread2 = new Thread(function (...args) { for (let k in values([1, 2, 3])) yield k + “ from thread 2”; }).start(); // 1 from thread 1 // 2 from thread 1 // 1 from thread 2 // 3 from thread 1 // 2 from thread 2 // etc.
  • 56. Array comprehensions // map + filter way let scores = [1, 7, 4, 9] .filter(function (x) { return x > 5 }) .map(function (x) { return x * x }); // [49, 81]
  • 57. Array comprehensions // map + filter way let scores = [1, 7, 4, 9] .filter(function (x) { return x > 5 }) .map(function (x) { return x * x }); // [49, 81] // array comprehensions let scores = [x * x for (x in values([1, 7, 4, 9])) if (x > 5)];
  • 58. Thanks for your attention Dmitry Soshnikov [email protected] http://dmitrysoshnikov.com @DmitrySoshnikov