SlideShare a Scribd company logo
@HelsinkiJS meet-up
       December 12, 2011




   ECMAScript, 6

     Dmitry Soshnikov
http://dmitrysoshnikov.com
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”) {
  ...
}
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 * from DBLayer; // import all

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

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

attachTo(“/books/store”, {
   onSuccess: function (response) { ... }
})
Quasi-Literals
(String templates)
Quasis : string templates
let content = “<a href=‘” + url + “’ title=‘”
  + title + “’>” + text+ “</a>”;

$(“#bar”).html(content);
Quasis : string templates
let content = “<a href=‘” + url + “’ title=‘”
  + title + “’>” + text+ “</a>”;

$(“#bar”).html(content);

let content = safeHtml `<a href=“${url} “ title=“${title}”>${text}</a>`;

$(“#bar”).html(content);

See: http://wiki.ecmascript.org/doku.php?id=harmony:quasis
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)];
Map and WeakMap
Map and WeakMap
let user = {name: “Ann”, x: 10, y: 20};
// Keys in a map are objects
let scoresMap = new Map;
map.set(user, 100);
console.log(scoresMap.get(user)); // 100
Map and WeakMap
let user = {name: “Ann”, x: 10, y: 20};
// Keys in a map are objects
let scoresMap = new Map;
map.set(user, 100);
console.log(scoresMap.get(user)); // 100

let markers = new WeakMap;
marker = new Marker(10, 20);
markers.set(marker, “Ann”);
console.log(weakMap.get(marker)); // “Ann”

delete marker; // if marker is GC’ed, it’s removed from WeakMap too!
Destructuring assignment
Destructuring: arrays

// for arrays
let [x, y] = [10, 20, 30];

console.log(x, y); // 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);
Eliminating of arguments:
     ...rest operator
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
Complicated 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
...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
Proxy objects : meta level
Proxy-objects

/* target – original object
 * handler – meta-handler */
Proxy(target, handler)
See: http://wiki.ecmascript.org/doku.php?id=harmony:direct_proxies



Note: old semantics (currently is implemented in Firefox) will not longer be available:
Proxy.create(handler, [proto]), Proxy.createFunction(handler, [call, [consruct]])
See: http://wiki.ecmascript.org/doku.php?id=harmony:proxies
Proxy-objects
 // original object       // proxied object
 let point = {            let loggedPoint = Proxy(point, {
    x: 10,                    get: function (point, name, rcvr) {
    y: 20                        console.log(“get: ”, name);
 };                              return point[name];
                              },
                              set: function (point, name, value, rcvr) {
Trap of getting of               console.log(“set: ”, name, value);
   properties
                                 point[name] = value;
                              }
Trap of setting the       });
    properties
Proxy-objects
                                    // proxied object
    Meta-handler                    let loggedPoint = Proxy(point, {
                                        get: function (point, name, rcvr) {
// reading trap                            console.log(“get: ”, name);
loggedPoint.x; // get: x, 10               return point[name];
                                        },
// writing trap                         set: function (point, name, value, rcvr) {
loggedPoint.x = 20; // set: x, 20          console.log(“set: ”, name, value);
                                           point[name] = value;
// reflected on the original object     }
point.x; // 20                      });
Struct types
Struct types
// struct types
let Point2D = new StructType({ x: uint32, y: uint32 });
let Color = new StructType({ r: uint8, g: uint8, b: uint8 });
let Pixel = new StructType({ point: Point2D, color: Color });

// array types
let Triangle = new ArrayType(Pixel, 3);

// dense-objects, based on struct binary types
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 } }
]);
Struct types : example

// struct types
let IODataBlock = new StructType( /* attributes */ );

stream.read(IODataBlock, function (block) {
    // partial handling
});
Thanks for your attention


     Dmitry Soshnikov

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

      @DmitrySoshnikov

More Related Content

PDF
FalsyValues. Dmitry Soshnikov - ECMAScript 6
ODP
EcmaScript 6
PDF
Planet-HTML5-Game-Engine Javascript Performance Enhancement
PPTX
ES6 in Real Life
PDF
Explaining ES6: JavaScript History and What is to Come
PDF
ES6 - Next Generation Javascript
PDF
ECMAScript 6
PPTX
Academy PRO: ES2015
FalsyValues. Dmitry Soshnikov - ECMAScript 6
EcmaScript 6
Planet-HTML5-Game-Engine Javascript Performance Enhancement
ES6 in Real Life
Explaining ES6: JavaScript History and What is to Come
ES6 - Next Generation Javascript
ECMAScript 6
Academy PRO: ES2015

What's hot (19)

PDF
Apache Commons - Don\'t re-invent the wheel
ODP
ES6 PPT FOR 2016
PDF
Javascript
PDF
JavaScript ES6
PDF
Rust ⇋ JavaScript
PDF
ES2015 (ES6) Overview
PDF
4. Обработка ошибок, исключения, отладка
PDF
An Intro To ES6
PDF
Elm: give it a try
PDF
5. Ввод-вывод, доступ к файловой системе
PDF
3. Объекты, классы и пакеты в Java
PDF
Cycle.js: Functional and Reactive
PDF
Building fast interpreters in Rust
KEY
連邦の白いヤツ 「Objective-C」
PDF
Mongoskin - Guilin
PDF
Proxies are Awesome!
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
PDF
EcmaScript 6 - The future is here
PDF
Symfony 2.0
Apache Commons - Don\'t re-invent the wheel
ES6 PPT FOR 2016
Javascript
JavaScript ES6
Rust ⇋ JavaScript
ES2015 (ES6) Overview
4. Обработка ошибок, исключения, отладка
An Intro To ES6
Elm: give it a try
5. Ввод-вывод, доступ к файловой системе
3. Объекты, классы и пакеты в Java
Cycle.js: Functional and Reactive
Building fast interpreters in Rust
連邦の白いヤツ 「Objective-C」
Mongoskin - Guilin
Proxies are Awesome!
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
EcmaScript 6 - The future is here
Symfony 2.0
Ad

Viewers also liked (20)

PDF
ttyrecからGIFアニメを作る話
PPT
Подробная презентация JavaScript 6 в 1
PDF
AddConf. Дмитрий Сошников - Будущее ECMAScript
PPT
доклад
PDF
"Готовим промисы правильно", Андрей Яманов, MoscowJS 24
PDF
Обзор ES2015(ES6)
PDF
DevConf. Дмитрий Сошников - ECMAScript 6
PPTX
JavaScript-модули "из прошлого в будущее"
PDF
Ecma script 6 in action
PDF
"Как написать компилятор за 15 минут", Андрей Гершун, MoscowJS 24
PDF
Дэвид Флэнаган — Javascript (5 издание)
PDF
altJSの選び方
PDF
Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)
PDF
Keypoints html5
PPTX
base.network — пиринговый веб на JavaScript / Денис Глазков (Lazada Rus)
PPT
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
PDF
Александр Русаков - TypeScript 2 in action
PPTX
altJS勉強会「Haxeすごいからみんな使え!」
PDF
1億5000万円欲しい (ロト6のデータで遊ぶ)
PDF
ES2015 / ES6: Basics of modern Javascript
ttyrecからGIFアニメを作る話
Подробная презентация JavaScript 6 в 1
AddConf. Дмитрий Сошников - Будущее ECMAScript
доклад
"Готовим промисы правильно", Андрей Яманов, MoscowJS 24
Обзор ES2015(ES6)
DevConf. Дмитрий Сошников - ECMAScript 6
JavaScript-модули "из прошлого в будущее"
Ecma script 6 in action
"Как написать компилятор за 15 минут", Андрей Гершун, MoscowJS 24
Дэвид Флэнаган — Javascript (5 издание)
altJSの選び方
Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)
Keypoints html5
base.network — пиринговый веб на JavaScript / Денис Глазков (Lazada Rus)
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
Александр Русаков - TypeScript 2 in action
altJS勉強会「Haxeすごいからみんな使え!」
1億5000万円欲しい (ロト6のデータで遊ぶ)
ES2015 / ES6: Basics of modern Javascript
Ad

Similar to HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6 (20)

PDF
TypeScript Introduction
PDF
Functional programming using underscorejs
PPTX
ES6 Overview
PDF
JavaScript - Agora nervoso
PDF
The Beauty of Java Script
PDF
The Beauty Of Java Script V5a
KEY
Node js mongodriver
PPTX
Javascript Basics
PDF
Exploring ES6
PPSX
What's New In C# 7
PDF
The state of your own hypertext preprocessor
PPTX
A topology of memory leaks on the JVM
PDF
Say It With Javascript
PPTX
ES6 is Nigh
PDF
Workshop 10: ECMAScript 6
PDF
Orlando BarCamp Why Javascript Doesn't Suck
PDF
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
PDF
Bindings: the zen of montage
PDF
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
PPTX
Thinking Functionally with JavaScript
TypeScript Introduction
Functional programming using underscorejs
ES6 Overview
JavaScript - Agora nervoso
The Beauty of Java Script
The Beauty Of Java Script V5a
Node js mongodriver
Javascript Basics
Exploring ES6
What's New In C# 7
The state of your own hypertext preprocessor
A topology of memory leaks on the JVM
Say It With Javascript
ES6 is Nigh
Workshop 10: ECMAScript 6
Orlando BarCamp Why Javascript Doesn't Suck
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Bindings: the zen of montage
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Thinking Functionally with JavaScript

Recently uploaded (20)

PDF
Collective Mining | Corporate Presentation - August 2025
PDF
Probe Gold Corporate Presentation Aug 2025 Final.pdf
PDF
North Arrow Minerals Corporate and Kraaipan Project Update
PPTX
HealthIllnessSociety.pptxjjjjjjjjjjjjjjjjj
PDF
Methanex Investor Presentation - July 2025
PPTX
TTL1_LMS-Presenfdufgdfgdgduhfudftation.pptx
DOCX
The Future of Investment Advice in a Tokenized World.docx
PPTX
North Arrow Corporate Update for August 5, 2025
PPTX
CCA文凭办理|加利福尼亚艺术学院毕业证海牙认证网上可查学历文凭
PDF
Cyberagent_For New Investors_EN_250808.pdf
PDF
How to Analyze Market Trends in Precious Metal.pdf
PDF
OR Royalties Inc. - Q2 2025 Results, August 6, 2025
PDF
Deutsche EuroShop | Company Presentation | 08/25
PDF
OR Royalties Inc. - Corporate Presentation, August 2025
PDF
202507_Sansan presentation materials FY2024
PPTX
The Future of Philanthropy - AI & Donor Engagement
PPTX
Chemistry.pptxjhghjgghgyughgyghhhvhbhghjbjb
PDF
TIM Group - Results Presentation H1 '25.pdf
PPTX
investment-opportunities-in-rajasthan.pptx
PDF
Investor Presentation - Q2 FY 25 - 6 November 2024.pdf
Collective Mining | Corporate Presentation - August 2025
Probe Gold Corporate Presentation Aug 2025 Final.pdf
North Arrow Minerals Corporate and Kraaipan Project Update
HealthIllnessSociety.pptxjjjjjjjjjjjjjjjjj
Methanex Investor Presentation - July 2025
TTL1_LMS-Presenfdufgdfgdgduhfudftation.pptx
The Future of Investment Advice in a Tokenized World.docx
North Arrow Corporate Update for August 5, 2025
CCA文凭办理|加利福尼亚艺术学院毕业证海牙认证网上可查学历文凭
Cyberagent_For New Investors_EN_250808.pdf
How to Analyze Market Trends in Precious Metal.pdf
OR Royalties Inc. - Q2 2025 Results, August 6, 2025
Deutsche EuroShop | Company Presentation | 08/25
OR Royalties Inc. - Corporate Presentation, August 2025
202507_Sansan presentation materials FY2024
The Future of Philanthropy - AI & Donor Engagement
Chemistry.pptxjhghjgghgyughgyghhhvhbhghjbjb
TIM Group - Results Presentation H1 '25.pdf
investment-opportunities-in-rajasthan.pptx
Investor Presentation - Q2 FY 25 - 6 November 2024.pdf

HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6

  • 1. @HelsinkiJS meet-up December 12, 2011 ECMAScript, 6 Dmitry Soshnikov http://dmitrysoshnikov.com
  • 2. Function parameter default values
  • 3. Function parameter default values function handleRequest(data, method) { method = method || “GET”; ... }
  • 4. Function parameter default values function handleRequest(data, method) { method = method || “GET”; ... } function handleRequest(data, method = “GET”) { ... }
  • 6. 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);
  • 7. 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);
  • 8. Modules in ES6 module DBLayer { export function query(s) { ... } export function connection(...args) { ... } } import * from DBLayer; // import all // import only needed exports import {query, connection: attachTo} from DBLayer query(“SELECT * FROM books”).format(“escape | split”); attachTo(“/books/store”, { onSuccess: function (response) { ... } })
  • 10. Quasis : string templates let content = “<a href=‘” + url + “’ title=‘” + title + “’>” + text+ “</a>”; $(“#bar”).html(content);
  • 11. Quasis : string templates let content = “<a href=‘” + url + “’ title=‘” + title + “’>” + text+ “</a>”; $(“#bar”).html(content); let content = safeHtml `<a href=“${url} “ title=“${title}”>${text}</a>`; $(“#bar”).html(content); See: http://wiki.ecmascript.org/doku.php?id=harmony:quasis
  • 13. 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]
  • 14. 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)];
  • 16. Map and WeakMap let user = {name: “Ann”, x: 10, y: 20}; // Keys in a map are objects let scoresMap = new Map; map.set(user, 100); console.log(scoresMap.get(user)); // 100
  • 17. Map and WeakMap let user = {name: “Ann”, x: 10, y: 20}; // Keys in a map are objects let scoresMap = new Map; map.set(user, 100); console.log(scoresMap.get(user)); // 100 let markers = new WeakMap; marker = new Marker(10, 20); markers.set(marker, “Ann”); console.log(weakMap.get(marker)); // “Ann” delete marker; // if marker is GC’ed, it’s removed from WeakMap too!
  • 19. Destructuring: arrays // for arrays let [x, y] = [10, 20, 30]; console.log(x, y); // 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. Eliminating of arguments: ...rest operator
  • 23. 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
  • 24. Complicated 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
  • 25. ...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
  • 26. Proxy objects : meta level
  • 27. Proxy-objects /* target – original object * handler – meta-handler */ Proxy(target, handler) See: http://wiki.ecmascript.org/doku.php?id=harmony:direct_proxies Note: old semantics (currently is implemented in Firefox) will not longer be available: Proxy.create(handler, [proto]), Proxy.createFunction(handler, [call, [consruct]]) See: http://wiki.ecmascript.org/doku.php?id=harmony:proxies
  • 28. Proxy-objects // original object // proxied object let point = { let loggedPoint = Proxy(point, { x: 10, get: function (point, name, rcvr) { y: 20 console.log(“get: ”, name); }; return point[name]; }, set: function (point, name, value, rcvr) { Trap of getting of console.log(“set: ”, name, value); properties point[name] = value; } Trap of setting the }); properties
  • 29. Proxy-objects // proxied object Meta-handler let loggedPoint = Proxy(point, { get: function (point, name, rcvr) { // reading trap console.log(“get: ”, name); loggedPoint.x; // get: x, 10 return point[name]; }, // writing trap set: function (point, name, value, rcvr) { loggedPoint.x = 20; // set: x, 20 console.log(“set: ”, name, value); point[name] = value; // reflected on the original object } point.x; // 20 });
  • 31. Struct types // struct types let Point2D = new StructType({ x: uint32, y: uint32 }); let Color = new StructType({ r: uint8, g: uint8, b: uint8 }); let Pixel = new StructType({ point: Point2D, color: Color }); // array types let Triangle = new ArrayType(Pixel, 3); // dense-objects, based on struct binary types 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 } } ]);
  • 32. Struct types : example // struct types let IODataBlock = new StructType( /* attributes */ ); stream.read(IODataBlock, function (block) { // partial handling });
  • 33. Thanks for your attention Dmitry Soshnikov dmitry.soshnikov@gmail.com http://dmitrysoshnikov.com @DmitrySoshnikov