SlideShare a Scribd company logo
1 of 46
Download to read offline
ECMAScript 6
Review
Introduction
● Name “JavaScript” is a licensed trademark by Sun
Microsystems
● JavaScript is described in ECMA-262 specification
by the name “ECMAScript”
● Current ECMAScript version is 5.1
● ECMAScript 6 will be released in December 2014
JavaScript and ECMAScript 6
Introduction
● Name “JavaScript” is a licensed trademark by Sun
Microsystems
● JavaScript is described in ECMA-262 specification
by the name “ECMAScript”
● Current ECMAScript version is 5.1
● ECMAScript 6 will be released in December 2014
JavaScript and ECMAScript 6
Introduction
let fibonacci = { max: 1000, *[Symbol.iterator]() { let pre =
0, cur = 1; do { [pre, cur] = [cur, pre + cur];
yield cur; } while (cur < this.max); }
}for (let n of fibonacci) { console.log(n);}
JavaScript and ECMAScript 6
New syntax constructions
● new declarators (let & const)
● arrow functions
● parameters in functions (default + rest + spread)
● object literals
● destructing assignment
● comprehensions
● for..of loop
We are talking about:
/*
* ECMAScript 6: variables declared with a let statement are created as
* bindings on the lexical environment.
* Each block has its own lexical environment.
*/
function foo(param) {
if (param) {
let bar = 5; // block scope declaration
}
console.log(bar); // ReferenceError: bar is not defined
}
/**
* without closure
*/
for (var i = 0; i < 10; i++) {
let j = i; // reassign counter with let
setTimeout(function () {
console.log(i, j);
}, 300 * j); // 10 0 10 1 10 2 10 3 .. 10 9
}
New syntax constructions
Let declarations
New syntax constructions
const declarations
/*
* const has the same block scoped binding semantics as let,
* but its value is a read-only constant
*/
const z; // SyntaxError: const declarations must have an
initializerconst y = 10; // y === 10y = 20; // SyntaxError:
Assignment to constant variable
New syntax constructions
Arrow functions
let simple = a => a > 15 ? 15 : a;simple(16); //
15simple(10); // 10let complex = (a, b) => { if (a > b)
{ return a; } else { return b; }}
New syntax constructions
Arrow functions
● Not newable - cannot be used a constructors.
● No arguments object - must use named arguments or rest arguments.
● Lexical this binding - The value of this inside of the function is
determined by where the arrow function is defined.
● Can’t change this - The value of this inside of the function can’t be
changed.
New syntax constructions
Arrow functions (more samples)
function Car() {
this.speed = 0;
//use an arrow function
setInterval(() => {
this.speed += 5; //this is from Car
console.log(this.speed);
}, 1000);
}
let car = new Car(); //5 10 15..
New syntax constructions
Parameters in function (default arguments)
/**
* ECMAScript 6 makes easier to provide default values for
* parameters by providing initializations that are used
* when the parameter isn’t formally passed.
*/
function multiply(x, y = 1) {
return x * y;
}
(function example(x, y = x * 2) {
console.log(x, y); // 2, 4
}(2));
New syntax constructions
Parameters in function (rest)
/**
* Rest parameters are indicated by three dots (...)
* preceding a named parameter. That named parameter
* then becomes an Array containing the rest of the
parameters
*
* Note: no other named arguments can follow in the function
* declaration after rest parameter
*/
function logEach(...things) {
things.forEach(function (thing) {
console.log(thing);
});
}
logEach("a", "b", "c"); //a b c
New syntax constructions
Parameters in function (spread)
/**
* Instead of calling apply(), you can pass in the
* array and prefix it with the same ... pattern that
* is used with rest parameters.
* The JavaScript engine then splits up the array into
* individual arguments
*/
let example = (a, b, c) => {console.log(a, b, c)};
let arg = 1;
let args = [2, 3];
example(arg, ...args);// 1 2 3
//used with array literals
let parts = ["shoulder", "knees"];
let lyrics = ["head", ...parts, "and", "toes"];
New syntax constructions
Object literals (property & method Initializer)
// ECMAScript 5
{
name: name,
sayName: function() {
console.log(this.name);
}
};
// ECMAScript 6
{
name,
sayName() {
console.log(this.name);
}
};
New syntax constructions
Object literals (computed property names)
/**
* The square brackets inside of the object literal
* indicate that the property name is computed, so
* its contents are evaluated as a string.
* That means you can also include expressions
*/
let lastName = "last name";
let suffix = " name";
let person = {
["first" + suffix]: "Nicholas",
[lastName]: "Zakas"
};
console.log(person["first name"]); // "Nicholas"
console.log(person[lastName]); // "Zakas"
New syntax constructions
Destructing assignment (objects)
let options = {
repeat: true,
save: false,
rules: {
custom: 10
}
};
let { repeat, save, rules: { custom }} = options;
console.log(repeat); // true
console.log(save); // false
console.log(custom); // 10
// syntax error without let, var, const
{ repeat, save, rules: { custom }} = options;
// works fine
({ repeat, save, rules: { custom }}) = options;
New syntax constructions
Destructing assignment (array)
let colors = [ "red", [ "green", "lightgreen" ], "blue" ];
let [ firstColor, [ secondColor ] ] = colors;
console.log(firstColor); // "red"
console.log(secondColor); // "green"
// mixed
let options = {
repeat: true,
save: false,
colors: [ "red", "green", "blue" ]
};
let { repeat, save, colors: [ firstColor, secondColor ]} = options;
console.log(repeat); // true
console.log(save); // false
console.log(firstColor); // "red"
console.log(secondColor); // "green"
New syntax constructions
let arr = [ 3, 5, 7 ];arr.foo = "hello";// ECMAScript 5for (var i in arr) {
console.log(i); // logs "0", "1", "2", "foo"}// ECMAScript 6for (let i of
arr) { console.log(i); // logs "3", "5", "7"}
/**
* for...of uses iterators for iteration, thus it doesn't * iterate through
regular object
*/
for...of loop
New features
● Iterators
● Symbol
● Map
● WeakMap
● Set
● Generators
New features
New features
var iterator = function () {
var base = 2, count = 3, current = 1;
return {
next: function () {
return {
done: (count--) <= 0,
value: current *= base
}
}
};
};
var i = iterator();
i.next(); // { done: false, value: 2 }
i.next(); // { done: false, value: 4 }
i.next(); // { done: false, value: 8 }
i.next(); // { done: true, value: 16 }
Iterators
New features
collection.iterator = function () { var that = this, currentIndex = 0;
return { next: function () { return {
value: that.models[currentIndex++], done: currentIndex >
that.models.length
}; } }
}; for (var iterator = collection.iterator(), next = iterator.next();
!next.done; next = iterator.next()) { console.log(next.value);}
Iterators (ECMAScript 5)
Have a question?
Like this deck?
Just follow us on twitter
@Sperasoft
New features
collection[Symbol.iterator] = function () { var that = this, currentIndex
= 0; return { next: function () { return {
value: that.models[currentIndex++], done: currentIndex >
that.models.length
}; } }
};for (let model of collection) { console.log(model);}
Iterators (ECMAScript 6)
New features
collection[Symbol.iterator] = function* () { for (let modelKey in
this.models) { yield this.models[modelKey]; }
}; for (let model of collection) { console.log(model);}
Generators
New features
me.hunt = function* (dragons) { let fails = 0; for (let dragon of
dragons) { let result = dragon.hunt(); yield [dragon, result];
if (!result) { fails++; } if (fails >= 3) { return; } }
};let dragons = [ , , ,
];for (let [dragon, result] of me.hunt(dragons)) { console.log("Hunt on "
+ dragon + " was " + (result ? "successful!" : "failed."));}
Generators
New features
let map = new Map();map.set('key', 'Primitive string key');map.set(NaN,
'Watman');map.get('key'); // 'Primitive string key'map.get(Number('foo'));
// 'Watman'let a1 = [], a2 = [], a3 = function () { };map.set(a1,
'array');map.set(a2, 'yet another array');map.set(a3, 'not an
array');map.get([]); // undefinedmap.get(a1); // 'array'map.get(a3); // 'not
an array'
Map
New features
let map = new Map([['key1', 'value1'], ['key2',
'value2']]);console.log([...map]); // [['key1', 'value1'], ['key2',
'value2']]
console.log([...map.keys()]); // ['key1', 'key2']
console.log([...map.values()]); // ['value1', 'value2']for (let [key, value]
of map) { console.log('map[' + key + '] = ' + value);
}for (let key of map.keys()) { console.log('map[' + key + '] = ' +
map.get(key)); // The same as above}
Map (continue)
New features
/**
* WeakMap is a version of Map with improved memory leak control.
* It doesn't support primitive keys or enumerators.
*/let map = new WeakMap();map.set('key', 'Primitive string key'); //
TypeError - WeakMap doesn't support primitive keysmap.set(NaN, 'Watman'); //
TypeErrorlet div = document.createElement('div');map.set(div, 'dom
element');map.get(div); // 'dom element'for (let key of map); // TypeError -
WeakMap doesn't support enumeration
WeakMap
New features
let set = new Set([1, 1, 2, 3, 5]);set.has(1); //
trueset.delete(1);set.has(1); // false
set.has(8); // falseset.add(8);
set.add(document.querySelector('body'));
let a1 = [], a2 = [];set.add(a1);set.add(a2);set.has(a1); //
trueset.delete(a1);set.has(a2); // true
Set
New features
let Publisher = (function () { function Publisher () {
this._callbacks = new Set(); }; Publisher.prototype.subscribe =
function (callback) { this._callbacks.add(callback); };
Publisher.prototype.publish = function (data) { for (let callback of
this._callbacks) callback(data); }; return Publisher;
})();
Private properties (without Symbol)
New features
let Publisher = (function () { let callbacks = Symbol('callbacks');
function Publisher () { this[callbacks] = new Set(); };
Publisher.prototype.subscribe = function (callback) {
this[callbacks].add(callback); }; Publisher.prototype.publish =
function (data) { for (let callback of this[callbacks])
callback(data); }; return Publisher;
})();
Private properties (with Symbol)
New features
let callbacks = Symbol('callbacks');Symbol('callbacks') ===
Symbol('callbacks'); // falseString('callbacks') === String('callbacks'); //
truecallbacks.toString(); // Symbol(callbacks)typeof callbacks; // symbol
Well-known symbols:
● Symbol.create
● Symbol.iterator
● Symbol.toStringTag
● etc.
Symbols
Even more new features
● Proxy
● Classes
● Modules
● Template strings
● Array comprehension
● New methods (Object.assign, Array.from, String, Math.*)
Long story short:
Even more new features
getOwnPropertyDescriptor // Object.getOwnPropertyDescriptor(proxy,name)
getOwnPropertyNames // Object.getOwnPropertyNames(proxy)
getPrototypeOf // Object.getPrototypeOf(proxy)
defineProperty //Object.defineProperty(proxy,name,desc)
deleteProperty // delete proxy[name]
freeze // Object.freeze(proxy)
seal // Object.seal(proxy)
preventExtensions // Object.preventExtensions(proxy)
isFrozen // Object.isFrozen(proxy)
isSealed // Object.isSealed(proxy)
isExtensible // Object.isExtensible(proxy)
has // name in proxy
hasOwn // ({}).hasOwnProperty.call(proxy,name)
get // receiver[name]
set // receiver[name] = val
enumerate // for (name in proxy)
keys // Object.keys(proxy)
apply // proxy(...args)
construct // new proxy(...args)
Proxy
Even more new features
let p = Proxy.create({
get: function (proxy, name) {
return (name in this) ? this[name] : 'Unknown property '
+ name;
},
set: function(proxy, name, value) {
if (name === 'age') {
if (!Number.isInteger(value)) {
throw new TypeError('The age is not an integer');
}
if (value > 150) {
throw new RangeError('The age seems invalid');
}
}
//provide default behaviour
this[name] = value;
}
});
p.age = 100;
p.age = 300; //RangeError: The age seems invalid
console.log(p.age); //100
console.log(p.height); //Unknown property height
Proxy
Even more new features
class Polygon {
constructor(height, width) { //class constructor
this.name = 'Polygon';
this.height = height;
this.width = width;
}
sayName() { //class method
console.log('Hi, I am a', this.name + '.');
}
}
class Square extends Polygon {
constructor(length) {
super(length, length); //call the parent method with super
this.name = 'Square';
}
get area() { //calculated attribute getter
return this.height * this.width;
}
}
let s = new Square(5);
s.sayName(); //Hi, I am a Square.
console.log(s.area); //25
Classes
Even more new features
Modules has two main advantages:
● You could get compile time errors if you try to import something that
has not been exported.
● You can easily load ES6 modules asynchronously.
The ES6 module standard has two parts:
● Declarative syntax (for importing and exporting).
● Programmatic loader API: to configure how modules are loaded and to
conditionally load modules.
Modules
Even more new features
// point.js
module "point" {
export class Point {
constructor (x, y) {
public x = x;
public y = y;
}
}
}
// myapp.js
module point from "/point.js";
import Point from "point";
var origin = new Point(0, 0);
Modules
Even more new features
let name = "John", surname = "Doe";
let template1 = `Hello! My name is ${name} ${surname}!`;
console.log(template1); // Hello! My name is John Doe!
let salutation = 'Hello';
let greeting = `
${salutation},
this
crazy
world!`;
console.log(greeting);
/*
Hello,
this
crazy
world!
*/
Template strings
Even more new features
//ECMAScript 5
[1, 2, 3].map(function (i) { return i * i }); // [1, 4, 9]
[1,4,2,3,-8].filter(function(i) { return i < 3 }); // [1, 2, -8]
//ECMAScript 6
[for (i of [1, 2, 3]) i * i]; // [1, 4, 9]
[for (i of [1,4,2,3,-8]) if (i < 3) i]; // [1, 2, -8]
// generator
function* range(start, end) {
while (start < end) {
yield start;
start++;
}
}
var ten_squares = [i * i for each (i in range(0, 10))];
Array comprehension
Even more new features
Number.EPSILON
Number.isInteger(Infinity) // false
Number.isNaN("NaN") // false
Math.acosh(3) // 1.762747174039086
Math.hypot(3, 4) // 5
Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2
"abcde".contains("cd") // true
"abc".repeat(3) // "abcabcabc"
Array.from(document.querySelectorAll('*')) // Returns a real Array
Array.of(1, 2, 3) // Similar to new Array(...), but without special one-arg
behavior
[0, 0, 0].fill(7, 1) // [0,7,7]
[1,2,3].findIndex(x => x == 2) // 1
["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"]
["a", "b", "c"].keys() // iterator 0, 1, 2
["a", "b", "c"].values() // iterator "a", "b", "c"
Object.assign(Point, { origin: new Point(0,0) }) //extend
New methods (Object.assign, Array.from, String, Math.*)
Can you read it now?
let fibonacci = { max: 1000, *[Symbol.iterator]() { let pre =
0, cur = 1; do { [pre, cur] = [cur, pre + cur];
yield cur; } while (cur < this.max); }
}for (let n of fibonacci) { console.log(n);}
JavaScript and ECMAScript 6
Block scoped
declarator
Iterator property
Generator
Destructing assignment
Iterate through values
How to try right now?
● Almost everything supports consts
● IE11 also supports let, Map, Set and WeakMap
● Chrome supports some functions (Number.isNaN,
Number.isInteger, Object.is, etc.)
● Firefox doesn’t support classes, template strings,
computed properties and Object.assign
Browser support
How to try right now?
● harmony-collections provides implementations of
Map, Set and WeakMap
(https://github.com/Benvie/harmony-collections)
● es6-promise provides implementation of Promise
(https://github.com/jakearchibald/es6-promise)
● es6-shim provides a lot of stuff
(https://github.com/paulmillr/es6-shim/)
Polyfills
How to try right now?
● Google Traceur (https://github.com/google/traceur-
compiler)
● TypeScript - supports classes, modules, some
syntax stuff (http://www.typescriptlang.org/)
Compilers
Follow us on Twitter
@Sperasoft
Visit our site:
sperasoft.com

More Related Content

What's hot

An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6FITC
 
Planet-HTML5-Game-Engine Javascript Performance Enhancement
Planet-HTML5-Game-Engine Javascript Performance EnhancementPlanet-HTML5-Game-Engine Javascript Performance Enhancement
Planet-HTML5-Game-Engine Javascript Performance Enhancementup2soul
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.Russell Childs
 
What's New in ES6 for Web Devs
What's New in ES6 for Web DevsWhat's New in ES6 for Web Devs
What's New in ES6 for Web DevsRami Sayar
 
Swift Sequences & Collections
Swift Sequences & CollectionsSwift Sequences & Collections
Swift Sequences & CollectionsCocoaHeads France
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6Solution4Future
 
The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202Mahmoud Samir Fayed
 
Transducers in JavaScript
Transducers in JavaScriptTransducers in JavaScript
Transducers in JavaScriptPavel Forkert
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: ServersidenessWebExpo
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloadingkinan keshkeh
 
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵Wanbok Choi
 

What's hot (20)

ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
Map kit light
Map kit lightMap kit light
Map kit light
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
 
Memory management in c++
Memory management in c++Memory management in c++
Memory management in c++
 
Planet-HTML5-Game-Engine Javascript Performance Enhancement
Planet-HTML5-Game-Engine Javascript Performance EnhancementPlanet-HTML5-Game-Engine Javascript Performance Enhancement
Planet-HTML5-Game-Engine Javascript Performance Enhancement
 
Java script
Java scriptJava script
Java script
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
 
What's New in ES6 for Web Devs
What's New in ES6 for Web DevsWhat's New in ES6 for Web Devs
What's New in ES6 for Web Devs
 
Swift Sequences & Collections
Swift Sequences & CollectionsSwift Sequences & Collections
Swift Sequences & Collections
 
Day 1
Day 1Day 1
Day 1
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
 
C++11
C++11C++11
C++11
 
The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202
 
Transducers in JavaScript
Transducers in JavaScriptTransducers in JavaScript
Transducers in JavaScript
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
 

Similar to ECMAScript 6 Review

Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basicsmsemenistyi
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6Nitay Neeman
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScriptLuis Atencio
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchainedEduard Tomàs
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6WebF
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervosoLuis Vendrame
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)David Atchley
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascriptkvangork
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScriptkvangork
 

Similar to ECMAScript 6 Review (20)

Javascript
JavascriptJavascript
Javascript
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6
 
Internal workshop es6_2015
Internal workshop es6_2015Internal workshop es6_2015
Internal workshop es6_2015
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
 
Lecture5
Lecture5Lecture5
Lecture5
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
"let ECMAScript = 6"
"let ECMAScript = 6" "let ECMAScript = 6"
"let ECMAScript = 6"
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 

More from Sperasoft

особенности работы с Locomotion в Unreal Engine 4
особенности работы с Locomotion в Unreal Engine 4особенности работы с Locomotion в Unreal Engine 4
особенности работы с Locomotion в Unreal Engine 4Sperasoft
 
концепт и архитектура геймплея в Creach: The Depleted World
концепт и архитектура геймплея в Creach: The Depleted Worldконцепт и архитектура геймплея в Creach: The Depleted World
концепт и архитектура геймплея в Creach: The Depleted WorldSperasoft
 
Опыт разработки VR игры для UE4
Опыт разработки VR игры для UE4Опыт разработки VR игры для UE4
Опыт разработки VR игры для UE4Sperasoft
 
Организация работы с UE4 в команде до 20 человек
Организация работы с UE4 в команде до 20 человек Организация работы с UE4 в команде до 20 человек
Организация работы с UE4 в команде до 20 человек Sperasoft
 
Gameplay Tags
Gameplay TagsGameplay Tags
Gameplay TagsSperasoft
 
Data Driven Gameplay in UE4
Data Driven Gameplay in UE4Data Driven Gameplay in UE4
Data Driven Gameplay in UE4Sperasoft
 
Code and Memory Optimisation Tricks
Code and Memory Optimisation Tricks Code and Memory Optimisation Tricks
Code and Memory Optimisation Tricks Sperasoft
 
The theory of relational databases
The theory of relational databasesThe theory of relational databases
The theory of relational databasesSperasoft
 
Automated layout testing using Galen Framework
Automated layout testing using Galen FrameworkAutomated layout testing using Galen Framework
Automated layout testing using Galen FrameworkSperasoft
 
Sperasoft talks: Android Security Threats
Sperasoft talks: Android Security ThreatsSperasoft talks: Android Security Threats
Sperasoft talks: Android Security ThreatsSperasoft
 
Sperasoft Talks: RxJava Functional Reactive Programming on Android
Sperasoft Talks: RxJava Functional Reactive Programming on AndroidSperasoft Talks: RxJava Functional Reactive Programming on Android
Sperasoft Talks: RxJava Functional Reactive Programming on AndroidSperasoft
 
Sperasoft‬ talks j point 2015
Sperasoft‬ talks j point 2015Sperasoft‬ talks j point 2015
Sperasoft‬ talks j point 2015Sperasoft
 
Effective Мeetings
Effective МeetingsEffective Мeetings
Effective МeetingsSperasoft
 
Unreal Engine 4 Introduction
Unreal Engine 4 IntroductionUnreal Engine 4 Introduction
Unreal Engine 4 IntroductionSperasoft
 
JIRA Development
JIRA DevelopmentJIRA Development
JIRA DevelopmentSperasoft
 
Introduction to Elasticsearch
Introduction to ElasticsearchIntroduction to Elasticsearch
Introduction to ElasticsearchSperasoft
 
MOBILE DEVELOPMENT with HTML, CSS and JS
MOBILE DEVELOPMENT with HTML, CSS and JSMOBILE DEVELOPMENT with HTML, CSS and JS
MOBILE DEVELOPMENT with HTML, CSS and JSSperasoft
 
Quick Intro Into Kanban
Quick Intro Into KanbanQuick Intro Into Kanban
Quick Intro Into KanbanSperasoft
 
Console Development in 15 minutes
Console Development in 15 minutesConsole Development in 15 minutes
Console Development in 15 minutesSperasoft
 
Database Indexes
Database IndexesDatabase Indexes
Database IndexesSperasoft
 

More from Sperasoft (20)

особенности работы с Locomotion в Unreal Engine 4
особенности работы с Locomotion в Unreal Engine 4особенности работы с Locomotion в Unreal Engine 4
особенности работы с Locomotion в Unreal Engine 4
 
концепт и архитектура геймплея в Creach: The Depleted World
концепт и архитектура геймплея в Creach: The Depleted Worldконцепт и архитектура геймплея в Creach: The Depleted World
концепт и архитектура геймплея в Creach: The Depleted World
 
Опыт разработки VR игры для UE4
Опыт разработки VR игры для UE4Опыт разработки VR игры для UE4
Опыт разработки VR игры для UE4
 
Организация работы с UE4 в команде до 20 человек
Организация работы с UE4 в команде до 20 человек Организация работы с UE4 в команде до 20 человек
Организация работы с UE4 в команде до 20 человек
 
Gameplay Tags
Gameplay TagsGameplay Tags
Gameplay Tags
 
Data Driven Gameplay in UE4
Data Driven Gameplay in UE4Data Driven Gameplay in UE4
Data Driven Gameplay in UE4
 
Code and Memory Optimisation Tricks
Code and Memory Optimisation Tricks Code and Memory Optimisation Tricks
Code and Memory Optimisation Tricks
 
The theory of relational databases
The theory of relational databasesThe theory of relational databases
The theory of relational databases
 
Automated layout testing using Galen Framework
Automated layout testing using Galen FrameworkAutomated layout testing using Galen Framework
Automated layout testing using Galen Framework
 
Sperasoft talks: Android Security Threats
Sperasoft talks: Android Security ThreatsSperasoft talks: Android Security Threats
Sperasoft talks: Android Security Threats
 
Sperasoft Talks: RxJava Functional Reactive Programming on Android
Sperasoft Talks: RxJava Functional Reactive Programming on AndroidSperasoft Talks: RxJava Functional Reactive Programming on Android
Sperasoft Talks: RxJava Functional Reactive Programming on Android
 
Sperasoft‬ talks j point 2015
Sperasoft‬ talks j point 2015Sperasoft‬ talks j point 2015
Sperasoft‬ talks j point 2015
 
Effective Мeetings
Effective МeetingsEffective Мeetings
Effective Мeetings
 
Unreal Engine 4 Introduction
Unreal Engine 4 IntroductionUnreal Engine 4 Introduction
Unreal Engine 4 Introduction
 
JIRA Development
JIRA DevelopmentJIRA Development
JIRA Development
 
Introduction to Elasticsearch
Introduction to ElasticsearchIntroduction to Elasticsearch
Introduction to Elasticsearch
 
MOBILE DEVELOPMENT with HTML, CSS and JS
MOBILE DEVELOPMENT with HTML, CSS and JSMOBILE DEVELOPMENT with HTML, CSS and JS
MOBILE DEVELOPMENT with HTML, CSS and JS
 
Quick Intro Into Kanban
Quick Intro Into KanbanQuick Intro Into Kanban
Quick Intro Into Kanban
 
Console Development in 15 minutes
Console Development in 15 minutesConsole Development in 15 minutes
Console Development in 15 minutes
 
Database Indexes
Database IndexesDatabase Indexes
Database Indexes
 

Recently uploaded

unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate AgentsRyan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate AgentsRyan Mahoney
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 

Recently uploaded (20)

unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate AgentsRyan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 

ECMAScript 6 Review

  • 2. Introduction ● Name “JavaScript” is a licensed trademark by Sun Microsystems ● JavaScript is described in ECMA-262 specification by the name “ECMAScript” ● Current ECMAScript version is 5.1 ● ECMAScript 6 will be released in December 2014 JavaScript and ECMAScript 6
  • 3. Introduction ● Name “JavaScript” is a licensed trademark by Sun Microsystems ● JavaScript is described in ECMA-262 specification by the name “ECMAScript” ● Current ECMAScript version is 5.1 ● ECMAScript 6 will be released in December 2014 JavaScript and ECMAScript 6
  • 4. Introduction let fibonacci = { max: 1000, *[Symbol.iterator]() { let pre = 0, cur = 1; do { [pre, cur] = [cur, pre + cur]; yield cur; } while (cur < this.max); } }for (let n of fibonacci) { console.log(n);} JavaScript and ECMAScript 6
  • 5. New syntax constructions ● new declarators (let & const) ● arrow functions ● parameters in functions (default + rest + spread) ● object literals ● destructing assignment ● comprehensions ● for..of loop We are talking about:
  • 6. /* * ECMAScript 6: variables declared with a let statement are created as * bindings on the lexical environment. * Each block has its own lexical environment. */ function foo(param) { if (param) { let bar = 5; // block scope declaration } console.log(bar); // ReferenceError: bar is not defined } /** * without closure */ for (var i = 0; i < 10; i++) { let j = i; // reassign counter with let setTimeout(function () { console.log(i, j); }, 300 * j); // 10 0 10 1 10 2 10 3 .. 10 9 } New syntax constructions Let declarations
  • 7. New syntax constructions const declarations /* * const has the same block scoped binding semantics as let, * but its value is a read-only constant */ const z; // SyntaxError: const declarations must have an initializerconst y = 10; // y === 10y = 20; // SyntaxError: Assignment to constant variable
  • 8. New syntax constructions Arrow functions let simple = a => a > 15 ? 15 : a;simple(16); // 15simple(10); // 10let complex = (a, b) => { if (a > b) { return a; } else { return b; }}
  • 9. New syntax constructions Arrow functions ● Not newable - cannot be used a constructors. ● No arguments object - must use named arguments or rest arguments. ● Lexical this binding - The value of this inside of the function is determined by where the arrow function is defined. ● Can’t change this - The value of this inside of the function can’t be changed.
  • 10. New syntax constructions Arrow functions (more samples) function Car() { this.speed = 0; //use an arrow function setInterval(() => { this.speed += 5; //this is from Car console.log(this.speed); }, 1000); } let car = new Car(); //5 10 15..
  • 11. New syntax constructions Parameters in function (default arguments) /** * ECMAScript 6 makes easier to provide default values for * parameters by providing initializations that are used * when the parameter isn’t formally passed. */ function multiply(x, y = 1) { return x * y; } (function example(x, y = x * 2) { console.log(x, y); // 2, 4 }(2));
  • 12. New syntax constructions Parameters in function (rest) /** * Rest parameters are indicated by three dots (...) * preceding a named parameter. That named parameter * then becomes an Array containing the rest of the parameters * * Note: no other named arguments can follow in the function * declaration after rest parameter */ function logEach(...things) { things.forEach(function (thing) { console.log(thing); }); } logEach("a", "b", "c"); //a b c
  • 13. New syntax constructions Parameters in function (spread) /** * Instead of calling apply(), you can pass in the * array and prefix it with the same ... pattern that * is used with rest parameters. * The JavaScript engine then splits up the array into * individual arguments */ let example = (a, b, c) => {console.log(a, b, c)}; let arg = 1; let args = [2, 3]; example(arg, ...args);// 1 2 3 //used with array literals let parts = ["shoulder", "knees"]; let lyrics = ["head", ...parts, "and", "toes"];
  • 14. New syntax constructions Object literals (property & method Initializer) // ECMAScript 5 { name: name, sayName: function() { console.log(this.name); } }; // ECMAScript 6 { name, sayName() { console.log(this.name); } };
  • 15. New syntax constructions Object literals (computed property names) /** * The square brackets inside of the object literal * indicate that the property name is computed, so * its contents are evaluated as a string. * That means you can also include expressions */ let lastName = "last name"; let suffix = " name"; let person = { ["first" + suffix]: "Nicholas", [lastName]: "Zakas" }; console.log(person["first name"]); // "Nicholas" console.log(person[lastName]); // "Zakas"
  • 16. New syntax constructions Destructing assignment (objects) let options = { repeat: true, save: false, rules: { custom: 10 } }; let { repeat, save, rules: { custom }} = options; console.log(repeat); // true console.log(save); // false console.log(custom); // 10 // syntax error without let, var, const { repeat, save, rules: { custom }} = options; // works fine ({ repeat, save, rules: { custom }}) = options;
  • 17. New syntax constructions Destructing assignment (array) let colors = [ "red", [ "green", "lightgreen" ], "blue" ]; let [ firstColor, [ secondColor ] ] = colors; console.log(firstColor); // "red" console.log(secondColor); // "green" // mixed let options = { repeat: true, save: false, colors: [ "red", "green", "blue" ] }; let { repeat, save, colors: [ firstColor, secondColor ]} = options; console.log(repeat); // true console.log(save); // false console.log(firstColor); // "red" console.log(secondColor); // "green"
  • 18. New syntax constructions let arr = [ 3, 5, 7 ];arr.foo = "hello";// ECMAScript 5for (var i in arr) { console.log(i); // logs "0", "1", "2", "foo"}// ECMAScript 6for (let i of arr) { console.log(i); // logs "3", "5", "7"} /** * for...of uses iterators for iteration, thus it doesn't * iterate through regular object */ for...of loop
  • 19. New features ● Iterators ● Symbol ● Map ● WeakMap ● Set ● Generators New features
  • 20. New features var iterator = function () { var base = 2, count = 3, current = 1; return { next: function () { return { done: (count--) <= 0, value: current *= base } } }; }; var i = iterator(); i.next(); // { done: false, value: 2 } i.next(); // { done: false, value: 4 } i.next(); // { done: false, value: 8 } i.next(); // { done: true, value: 16 } Iterators
  • 21. New features collection.iterator = function () { var that = this, currentIndex = 0; return { next: function () { return { value: that.models[currentIndex++], done: currentIndex > that.models.length }; } } }; for (var iterator = collection.iterator(), next = iterator.next(); !next.done; next = iterator.next()) { console.log(next.value);} Iterators (ECMAScript 5)
  • 22. Have a question? Like this deck? Just follow us on twitter @Sperasoft
  • 23. New features collection[Symbol.iterator] = function () { var that = this, currentIndex = 0; return { next: function () { return { value: that.models[currentIndex++], done: currentIndex > that.models.length }; } } };for (let model of collection) { console.log(model);} Iterators (ECMAScript 6)
  • 24. New features collection[Symbol.iterator] = function* () { for (let modelKey in this.models) { yield this.models[modelKey]; } }; for (let model of collection) { console.log(model);} Generators
  • 25. New features me.hunt = function* (dragons) { let fails = 0; for (let dragon of dragons) { let result = dragon.hunt(); yield [dragon, result]; if (!result) { fails++; } if (fails >= 3) { return; } } };let dragons = [ , , , ];for (let [dragon, result] of me.hunt(dragons)) { console.log("Hunt on " + dragon + " was " + (result ? "successful!" : "failed."));} Generators
  • 26. New features let map = new Map();map.set('key', 'Primitive string key');map.set(NaN, 'Watman');map.get('key'); // 'Primitive string key'map.get(Number('foo')); // 'Watman'let a1 = [], a2 = [], a3 = function () { };map.set(a1, 'array');map.set(a2, 'yet another array');map.set(a3, 'not an array');map.get([]); // undefinedmap.get(a1); // 'array'map.get(a3); // 'not an array' Map
  • 27. New features let map = new Map([['key1', 'value1'], ['key2', 'value2']]);console.log([...map]); // [['key1', 'value1'], ['key2', 'value2']] console.log([...map.keys()]); // ['key1', 'key2'] console.log([...map.values()]); // ['value1', 'value2']for (let [key, value] of map) { console.log('map[' + key + '] = ' + value); }for (let key of map.keys()) { console.log('map[' + key + '] = ' + map.get(key)); // The same as above} Map (continue)
  • 28. New features /** * WeakMap is a version of Map with improved memory leak control. * It doesn't support primitive keys or enumerators. */let map = new WeakMap();map.set('key', 'Primitive string key'); // TypeError - WeakMap doesn't support primitive keysmap.set(NaN, 'Watman'); // TypeErrorlet div = document.createElement('div');map.set(div, 'dom element');map.get(div); // 'dom element'for (let key of map); // TypeError - WeakMap doesn't support enumeration WeakMap
  • 29. New features let set = new Set([1, 1, 2, 3, 5]);set.has(1); // trueset.delete(1);set.has(1); // false set.has(8); // falseset.add(8); set.add(document.querySelector('body')); let a1 = [], a2 = [];set.add(a1);set.add(a2);set.has(a1); // trueset.delete(a1);set.has(a2); // true Set
  • 30. New features let Publisher = (function () { function Publisher () { this._callbacks = new Set(); }; Publisher.prototype.subscribe = function (callback) { this._callbacks.add(callback); }; Publisher.prototype.publish = function (data) { for (let callback of this._callbacks) callback(data); }; return Publisher; })(); Private properties (without Symbol)
  • 31. New features let Publisher = (function () { let callbacks = Symbol('callbacks'); function Publisher () { this[callbacks] = new Set(); }; Publisher.prototype.subscribe = function (callback) { this[callbacks].add(callback); }; Publisher.prototype.publish = function (data) { for (let callback of this[callbacks]) callback(data); }; return Publisher; })(); Private properties (with Symbol)
  • 32. New features let callbacks = Symbol('callbacks');Symbol('callbacks') === Symbol('callbacks'); // falseString('callbacks') === String('callbacks'); // truecallbacks.toString(); // Symbol(callbacks)typeof callbacks; // symbol Well-known symbols: ● Symbol.create ● Symbol.iterator ● Symbol.toStringTag ● etc. Symbols
  • 33. Even more new features ● Proxy ● Classes ● Modules ● Template strings ● Array comprehension ● New methods (Object.assign, Array.from, String, Math.*) Long story short:
  • 34. Even more new features getOwnPropertyDescriptor // Object.getOwnPropertyDescriptor(proxy,name) getOwnPropertyNames // Object.getOwnPropertyNames(proxy) getPrototypeOf // Object.getPrototypeOf(proxy) defineProperty //Object.defineProperty(proxy,name,desc) deleteProperty // delete proxy[name] freeze // Object.freeze(proxy) seal // Object.seal(proxy) preventExtensions // Object.preventExtensions(proxy) isFrozen // Object.isFrozen(proxy) isSealed // Object.isSealed(proxy) isExtensible // Object.isExtensible(proxy) has // name in proxy hasOwn // ({}).hasOwnProperty.call(proxy,name) get // receiver[name] set // receiver[name] = val enumerate // for (name in proxy) keys // Object.keys(proxy) apply // proxy(...args) construct // new proxy(...args) Proxy
  • 35. Even more new features let p = Proxy.create({ get: function (proxy, name) { return (name in this) ? this[name] : 'Unknown property ' + name; }, set: function(proxy, name, value) { if (name === 'age') { if (!Number.isInteger(value)) { throw new TypeError('The age is not an integer'); } if (value > 150) { throw new RangeError('The age seems invalid'); } } //provide default behaviour this[name] = value; } }); p.age = 100; p.age = 300; //RangeError: The age seems invalid console.log(p.age); //100 console.log(p.height); //Unknown property height Proxy
  • 36. Even more new features class Polygon { constructor(height, width) { //class constructor this.name = 'Polygon'; this.height = height; this.width = width; } sayName() { //class method console.log('Hi, I am a', this.name + '.'); } } class Square extends Polygon { constructor(length) { super(length, length); //call the parent method with super this.name = 'Square'; } get area() { //calculated attribute getter return this.height * this.width; } } let s = new Square(5); s.sayName(); //Hi, I am a Square. console.log(s.area); //25 Classes
  • 37. Even more new features Modules has two main advantages: ● You could get compile time errors if you try to import something that has not been exported. ● You can easily load ES6 modules asynchronously. The ES6 module standard has two parts: ● Declarative syntax (for importing and exporting). ● Programmatic loader API: to configure how modules are loaded and to conditionally load modules. Modules
  • 38. Even more new features // point.js module "point" { export class Point { constructor (x, y) { public x = x; public y = y; } } } // myapp.js module point from "/point.js"; import Point from "point"; var origin = new Point(0, 0); Modules
  • 39. Even more new features let name = "John", surname = "Doe"; let template1 = `Hello! My name is ${name} ${surname}!`; console.log(template1); // Hello! My name is John Doe! let salutation = 'Hello'; let greeting = ` ${salutation}, this crazy world!`; console.log(greeting); /* Hello, this crazy world! */ Template strings
  • 40. Even more new features //ECMAScript 5 [1, 2, 3].map(function (i) { return i * i }); // [1, 4, 9] [1,4,2,3,-8].filter(function(i) { return i < 3 }); // [1, 2, -8] //ECMAScript 6 [for (i of [1, 2, 3]) i * i]; // [1, 4, 9] [for (i of [1,4,2,3,-8]) if (i < 3) i]; // [1, 2, -8] // generator function* range(start, end) { while (start < end) { yield start; start++; } } var ten_squares = [i * i for each (i in range(0, 10))]; Array comprehension
  • 41. Even more new features Number.EPSILON Number.isInteger(Infinity) // false Number.isNaN("NaN") // false Math.acosh(3) // 1.762747174039086 Math.hypot(3, 4) // 5 Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2 "abcde".contains("cd") // true "abc".repeat(3) // "abcabcabc" Array.from(document.querySelectorAll('*')) // Returns a real Array Array.of(1, 2, 3) // Similar to new Array(...), but without special one-arg behavior [0, 0, 0].fill(7, 1) // [0,7,7] [1,2,3].findIndex(x => x == 2) // 1 ["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"] ["a", "b", "c"].keys() // iterator 0, 1, 2 ["a", "b", "c"].values() // iterator "a", "b", "c" Object.assign(Point, { origin: new Point(0,0) }) //extend New methods (Object.assign, Array.from, String, Math.*)
  • 42. Can you read it now? let fibonacci = { max: 1000, *[Symbol.iterator]() { let pre = 0, cur = 1; do { [pre, cur] = [cur, pre + cur]; yield cur; } while (cur < this.max); } }for (let n of fibonacci) { console.log(n);} JavaScript and ECMAScript 6 Block scoped declarator Iterator property Generator Destructing assignment Iterate through values
  • 43. How to try right now? ● Almost everything supports consts ● IE11 also supports let, Map, Set and WeakMap ● Chrome supports some functions (Number.isNaN, Number.isInteger, Object.is, etc.) ● Firefox doesn’t support classes, template strings, computed properties and Object.assign Browser support
  • 44. How to try right now? ● harmony-collections provides implementations of Map, Set and WeakMap (https://github.com/Benvie/harmony-collections) ● es6-promise provides implementation of Promise (https://github.com/jakearchibald/es6-promise) ● es6-shim provides a lot of stuff (https://github.com/paulmillr/es6-shim/) Polyfills
  • 45. How to try right now? ● Google Traceur (https://github.com/google/traceur- compiler) ● TypeScript - supports classes, modules, some syntax stuff (http://www.typescriptlang.org/) Compilers
  • 46. Follow us on Twitter @Sperasoft Visit our site: sperasoft.com