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
Ad

More Related Content

What's hot (20)

Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
tcurdt
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
Manoj Kumar
 
Javascript
JavascriptJavascript
Javascript
Vlad Ifrim
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
Leo Hernandez
 
Rust ⇋ JavaScript
Rust ⇋ JavaScriptRust ⇋ JavaScript
Rust ⇋ JavaScript
Ingvar Stepanyan
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
hesher
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка
DEVTYPE
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
FITC
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with Slick
Hermann Hueck
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
Eugene Zharkov
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе
DEVTYPE
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
DEVTYPE
 
Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and Reactive
Eugene Zharkov
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in Rust
Ingvar Stepanyan
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」
matuura_core
 
Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - Guilin
Jackson Tian
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
Brendan Eich
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
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
 
Symfony 2.0
Symfony 2.0Symfony 2.0
Symfony 2.0
GrUSP
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
tcurdt
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
Manoj Kumar
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
hesher
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка
DEVTYPE
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
FITC
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with Slick
Hermann Hueck
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе
DEVTYPE
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
DEVTYPE
 
Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and Reactive
Eugene Zharkov
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in Rust
Ingvar Stepanyan
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」
matuura_core
 
Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - Guilin
Jackson Tian
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
Brendan Eich
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
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
 
Symfony 2.0
Symfony 2.0Symfony 2.0
Symfony 2.0
GrUSP
 

Viewers also liked (20)

ttyrecからGIFアニメを作る話
ttyrecからGIFアニメを作る話ttyrecからGIFアニメを作る話
ttyrecからGIFアニメを作る話
Yoshihiro Sugi
 
Подробная презентация JavaScript 6 в 1
Подробная презентация JavaScript 6 в 1Подробная презентация JavaScript 6 в 1
Подробная презентация JavaScript 6 в 1
Vasya Petrov
 
AddConf. Дмитрий Сошников - Будущее ECMAScript
AddConf. Дмитрий Сошников  - Будущее ECMAScriptAddConf. Дмитрий Сошников  - Будущее ECMAScript
AddConf. Дмитрий Сошников - Будущее ECMAScript
Dmitry Soshnikov
 
"Готовим промисы правильно", Андрей Яманов, MoscowJS 24
"Готовим промисы правильно", Андрей Яманов, MoscowJS 24"Готовим промисы правильно", Андрей Яманов, MoscowJS 24
"Готовим промисы правильно", Андрей Яманов, MoscowJS 24
MoscowJS
 
Обзор ES2015(ES6)
Обзор ES2015(ES6)Обзор ES2015(ES6)
Обзор ES2015(ES6)
Alex Filatov
 
DevConf. Дмитрий Сошников - ECMAScript 6
DevConf. Дмитрий Сошников - ECMAScript 6DevConf. Дмитрий Сошников - ECMAScript 6
DevConf. Дмитрий Сошников - ECMAScript 6
Dmitry Soshnikov
 
JavaScript-модули "из прошлого в будущее"
JavaScript-модули "из прошлого в будущее"JavaScript-модули "из прошлого в будущее"
JavaScript-модули "из прошлого в будущее"
oelifantiev
 
Ecma script 6 in action
Ecma script 6 in actionEcma script 6 in action
Ecma script 6 in action
Yuri Trukhin
 
"Как написать компилятор за 15 минут", Андрей Гершун, MoscowJS 24
"Как написать компилятор за 15 минут", Андрей Гершун, MoscowJS 24"Как написать компилятор за 15 минут", Андрей Гершун, MoscowJS 24
"Как написать компилятор за 15 минут", Андрей Гершун, MoscowJS 24
MoscowJS
 
Дэвид Флэнаган — Javascript (5 издание)
Дэвид Флэнаган — Javascript (5 издание)Дэвид Флэнаган — Javascript (5 издание)
Дэвид Флэнаган — Javascript (5 издание)
mlatushko
 
altJSの選び方
altJSの選び方altJSの選び方
altJSの選び方
terurou
 
Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)
Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)
Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)
Ontico
 
Keypoints html5
Keypoints html5Keypoints html5
Keypoints html5
dynamis
 
base.network — пиринговый веб на JavaScript / Денис Глазков (Lazada Rus)
base.network — пиринговый веб на JavaScript / Денис Глазков (Lazada Rus)base.network — пиринговый веб на JavaScript / Денис Глазков (Lazada Rus)
base.network — пиринговый веб на JavaScript / Денис Глазков (Lazada Rus)
Ontico
 
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
Allen Wirfs-Brock
 
Александр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in actionАлександр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in action
MoscowJS
 
altJS勉強会「Haxeすごいからみんな使え!」
altJS勉強会「Haxeすごいからみんな使え!」altJS勉強会「Haxeすごいからみんな使え!」
altJS勉強会「Haxeすごいからみんな使え!」
政樹 尾野
 
1億5000万円欲しい (ロト6のデータで遊ぶ)
1億5000万円欲しい (ロト6のデータで遊ぶ)1億5000万円欲しい (ロト6のデータで遊ぶ)
1億5000万円欲しい (ロト6のデータで遊ぶ)
Takuma Hatano
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern Javascript
Wojciech Dzikowski
 
ttyrecからGIFアニメを作る話
ttyrecからGIFアニメを作る話ttyrecからGIFアニメを作る話
ttyrecからGIFアニメを作る話
Yoshihiro Sugi
 
Подробная презентация JavaScript 6 в 1
Подробная презентация JavaScript 6 в 1Подробная презентация JavaScript 6 в 1
Подробная презентация JavaScript 6 в 1
Vasya Petrov
 
AddConf. Дмитрий Сошников - Будущее ECMAScript
AddConf. Дмитрий Сошников  - Будущее ECMAScriptAddConf. Дмитрий Сошников  - Будущее ECMAScript
AddConf. Дмитрий Сошников - Будущее ECMAScript
Dmitry Soshnikov
 
"Готовим промисы правильно", Андрей Яманов, MoscowJS 24
"Готовим промисы правильно", Андрей Яманов, MoscowJS 24"Готовим промисы правильно", Андрей Яманов, MoscowJS 24
"Готовим промисы правильно", Андрей Яманов, MoscowJS 24
MoscowJS
 
Обзор ES2015(ES6)
Обзор ES2015(ES6)Обзор ES2015(ES6)
Обзор ES2015(ES6)
Alex Filatov
 
DevConf. Дмитрий Сошников - ECMAScript 6
DevConf. Дмитрий Сошников - ECMAScript 6DevConf. Дмитрий Сошников - ECMAScript 6
DevConf. Дмитрий Сошников - ECMAScript 6
Dmitry Soshnikov
 
JavaScript-модули "из прошлого в будущее"
JavaScript-модули "из прошлого в будущее"JavaScript-модули "из прошлого в будущее"
JavaScript-модули "из прошлого в будущее"
oelifantiev
 
Ecma script 6 in action
Ecma script 6 in actionEcma script 6 in action
Ecma script 6 in action
Yuri Trukhin
 
"Как написать компилятор за 15 минут", Андрей Гершун, MoscowJS 24
"Как написать компилятор за 15 минут", Андрей Гершун, MoscowJS 24"Как написать компилятор за 15 минут", Андрей Гершун, MoscowJS 24
"Как написать компилятор за 15 минут", Андрей Гершун, MoscowJS 24
MoscowJS
 
Дэвид Флэнаган — Javascript (5 издание)
Дэвид Флэнаган — Javascript (5 издание)Дэвид Флэнаган — Javascript (5 издание)
Дэвид Флэнаган — Javascript (5 издание)
mlatushko
 
altJSの選び方
altJSの選び方altJSの選び方
altJSの選び方
terurou
 
Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)
Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)
Классические архитектуры во фронтенде / Александра Шинкевич (LOVATA)
Ontico
 
Keypoints html5
Keypoints html5Keypoints html5
Keypoints html5
dynamis
 
base.network — пиринговый веб на JavaScript / Денис Глазков (Lazada Rus)
base.network — пиринговый веб на JavaScript / Денис Глазков (Lazada Rus)base.network — пиринговый веб на JavaScript / Денис Глазков (Lazada Rus)
base.network — пиринговый веб на JavaScript / Денис Глазков (Lazada Rus)
Ontico
 
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
Allen Wirfs-Brock
 
Александр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in actionАлександр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in action
MoscowJS
 
altJS勉強会「Haxeすごいからみんな使え!」
altJS勉強会「Haxeすごいからみんな使え!」altJS勉強会「Haxeすごいからみんな使え!」
altJS勉強会「Haxeすごいからみんな使え!」
政樹 尾野
 
1億5000万円欲しい (ロト6のデータで遊ぶ)
1億5000万円欲しい (ロト6のデータで遊ぶ)1億5000万円欲しい (ロト6のデータで遊ぶ)
1億5000万円欲しい (ロト6のデータで遊ぶ)
Takuma Hatano
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern Javascript
Wojciech Dzikowski
 
Ad

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

TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
偉格 高
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
Bruno Scopelliti
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
Luis Vendrame
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
Michael Girouard
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
rajivmordani
 
Node js mongodriver
Node js mongodriverNode js mongodriver
Node js mongodriver
christkv
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
msemenistyi
 
Exploring ES6
Exploring ES6Exploring ES6
Exploring ES6
Ximing Dai
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
Paulo Morgado
 
The state of your own hypertext preprocessor
The state of your own hypertext preprocessorThe state of your own hypertext preprocessor
The state of your own hypertext preprocessor
Alessandro Nadalin
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
Rafael Winterhalter
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
Giovanni Scerra ☃
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
Domenic Denicola
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
Visual Engineering
 
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
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Tsuyoshi Yamamoto
 
Bindings: the zen of montage
Bindings: the zen of montageBindings: the zen of montage
Bindings: the zen of montage
Kris Kowal
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
ConFoo
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
Luis Atencio
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
偉格 高
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
Luis Vendrame
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
rajivmordani
 
Node js mongodriver
Node js mongodriverNode js mongodriver
Node js mongodriver
christkv
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
msemenistyi
 
The state of your own hypertext preprocessor
The state of your own hypertext preprocessorThe state of your own hypertext preprocessor
The state of your own hypertext preprocessor
Alessandro Nadalin
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
Rafael Winterhalter
 
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
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Tsuyoshi Yamamoto
 
Bindings: the zen of montage
Bindings: the zen of montageBindings: the zen of montage
Bindings: the zen of montage
Kris Kowal
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
ConFoo
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
Luis Atencio
 
Ad

Recently uploaded (12)

Methanex Investor Presentation - April 2025
Methanex Investor Presentation - April 2025Methanex Investor Presentation - April 2025
Methanex Investor Presentation - April 2025
Methanex Corporation
 
Fundamental Analysis/ SAPM/Module-3/ Bangalore university
Fundamental Analysis/ SAPM/Module-3/ Bangalore universityFundamental Analysis/ SAPM/Module-3/ Bangalore university
Fundamental Analysis/ SAPM/Module-3/ Bangalore university
Sudhakaran T
 
Investment Landscape of Bangladesh. Made by Shopnil Hasan
Investment Landscape of Bangladesh. Made by Shopnil HasanInvestment Landscape of Bangladesh. Made by Shopnil Hasan
Investment Landscape of Bangladesh. Made by Shopnil Hasan
hasanshopnil2004
 
Sue Your Insurance Company After a Car Accident
Sue Your Insurance Company After a Car AccidentSue Your Insurance Company After a Car Accident
Sue Your Insurance Company After a Car Accident
Pandora Insurance
 
Effectively Using Bollinger Bands in Volatile Market Conditions | Skyriss
Effectively Using Bollinger Bands in Volatile Market Conditions | SkyrissEffectively Using Bollinger Bands in Volatile Market Conditions | Skyriss
Effectively Using Bollinger Bands in Volatile Market Conditions | Skyriss
Skyriss
 
Fundamentals-of-Portfolio-Management.pptx
Fundamentals-of-Portfolio-Management.pptxFundamentals-of-Portfolio-Management.pptx
Fundamentals-of-Portfolio-Management.pptx
BiditaHaldar
 
Sysco Fiscal Q3 2025 Earnings Results Presentation
Sysco Fiscal Q3 2025 Earnings Results PresentationSysco Fiscal Q3 2025 Earnings Results Presentation
Sysco Fiscal Q3 2025 Earnings Results Presentation
Sysco_Investors
 
Deutsche EuroShop | Annual Report 2024
Deutsche EuroShop  |  Annual Report 2024Deutsche EuroShop  |  Annual Report 2024
Deutsche EuroShop | Annual Report 2024
Deutsche EuroShop AG
 
LLense, Shad light on media content value
LLense, Shad light on media content valueLLense, Shad light on media content value
LLense, Shad light on media content value
Nicolas Lee
 
Airworthiness diresssssssssssssssssssssssssssvtive.pdf
Airworthiness diresssssssssssssssssssssssssssvtive.pdfAirworthiness diresssssssssssssssssssssssssssvtive.pdf
Airworthiness diresssssssssssssssssssssssssssvtive.pdf
ArishhGholamii
 
Probe Gold Corporate Presentation May 2025 Final.pdf
Probe Gold Corporate Presentation May 2025 Final.pdfProbe Gold Corporate Presentation May 2025 Final.pdf
Probe Gold Corporate Presentation May 2025 Final.pdf
seemasindwani
 
How to Analyze a Company’s Financial Statements? | Skyriss
How to Analyze a Company’s Financial Statements? | SkyrissHow to Analyze a Company’s Financial Statements? | Skyriss
How to Analyze a Company’s Financial Statements? | Skyriss
Skyriss
 
Methanex Investor Presentation - April 2025
Methanex Investor Presentation - April 2025Methanex Investor Presentation - April 2025
Methanex Investor Presentation - April 2025
Methanex Corporation
 
Fundamental Analysis/ SAPM/Module-3/ Bangalore university
Fundamental Analysis/ SAPM/Module-3/ Bangalore universityFundamental Analysis/ SAPM/Module-3/ Bangalore university
Fundamental Analysis/ SAPM/Module-3/ Bangalore university
Sudhakaran T
 
Investment Landscape of Bangladesh. Made by Shopnil Hasan
Investment Landscape of Bangladesh. Made by Shopnil HasanInvestment Landscape of Bangladesh. Made by Shopnil Hasan
Investment Landscape of Bangladesh. Made by Shopnil Hasan
hasanshopnil2004
 
Sue Your Insurance Company After a Car Accident
Sue Your Insurance Company After a Car AccidentSue Your Insurance Company After a Car Accident
Sue Your Insurance Company After a Car Accident
Pandora Insurance
 
Effectively Using Bollinger Bands in Volatile Market Conditions | Skyriss
Effectively Using Bollinger Bands in Volatile Market Conditions | SkyrissEffectively Using Bollinger Bands in Volatile Market Conditions | Skyriss
Effectively Using Bollinger Bands in Volatile Market Conditions | Skyriss
Skyriss
 
Fundamentals-of-Portfolio-Management.pptx
Fundamentals-of-Portfolio-Management.pptxFundamentals-of-Portfolio-Management.pptx
Fundamentals-of-Portfolio-Management.pptx
BiditaHaldar
 
Sysco Fiscal Q3 2025 Earnings Results Presentation
Sysco Fiscal Q3 2025 Earnings Results PresentationSysco Fiscal Q3 2025 Earnings Results Presentation
Sysco Fiscal Q3 2025 Earnings Results Presentation
Sysco_Investors
 
Deutsche EuroShop | Annual Report 2024
Deutsche EuroShop  |  Annual Report 2024Deutsche EuroShop  |  Annual Report 2024
Deutsche EuroShop | Annual Report 2024
Deutsche EuroShop AG
 
LLense, Shad light on media content value
LLense, Shad light on media content valueLLense, Shad light on media content value
LLense, Shad light on media content value
Nicolas Lee
 
Airworthiness diresssssssssssssssssssssssssssvtive.pdf
Airworthiness diresssssssssssssssssssssssssssvtive.pdfAirworthiness diresssssssssssssssssssssssssssvtive.pdf
Airworthiness diresssssssssssssssssssssssssssvtive.pdf
ArishhGholamii
 
Probe Gold Corporate Presentation May 2025 Final.pdf
Probe Gold Corporate Presentation May 2025 Final.pdfProbe Gold Corporate Presentation May 2025 Final.pdf
Probe Gold Corporate Presentation May 2025 Final.pdf
seemasindwani
 
How to Analyze a Company’s Financial Statements? | Skyriss
How to Analyze a Company’s Financial Statements? | SkyrissHow to Analyze a Company’s Financial Statements? | Skyriss
How to Analyze a Company’s Financial Statements? | Skyriss
Skyriss
 

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 [email protected] http://dmitrysoshnikov.com @DmitrySoshnikov