SlideShare a Scribd company logo
1 of 147
Download to read offline
ES6
Next Generation Javascript
By Ramesh Nair and Grégoire Charvet
https://github.com/hiddentao/es6-slides
Speakers
Grégoire Charvet (geekingfrog.com)
Full time node.js developper
Passionate about the web
Working on the web for almost 2 years now
Ramesh Nair (hiddentao.com)
Full time Javascript/Node developper
Also worked with PHP, Python, Java, C++
Loves optimizing for performance
Rapid history of javascript
The birth

Created in 10 days in 1995 (by Brendan Eich) at Netscape
Brought to ECMA a year later to standardize it
javaScript has nothing to do with java
Early history

ECMAScript 2 in 98, 3 in 99
War with Microsoft -> ES4 has never been adopted
In 2005, Microsoft introduced ajax
In 2009, all parties agreed to move forward with ES5 +
harmony process
Now

Javascript most well known implementation of ECMAScript
(with ActionScript)
Javascript is the assembly of the web
Confusing version number, JS 1.8 correspond to ES6
ES6

ES6 work started in 2011
As of now (Feb 2014), ES6 is not yet adopted (but it's almost
there)
Major milestone
Not 'production ready' yet
What we will cover today
Support
Scope and control
Iterators and Generators
Collections
Typed objects
Direct proxies
Template strings
API improvements
Modularity
Support
24

30

✗

For chrome, need to enable the experimental js features
full table
Node.js support
Node.js: get the latest 0.11 and add the flag --harmony
Support is the same as chrome (V8)
Safari support
Almost the same as IE (so quasi inexistant)
Scoping
24

30

11
Block scoping
Finally !
Before
for(var i=10; i>0 ; i--) {
// do stuff with i
}
console.log(i); // 0
let
for(let i=10; i>10; i--) {
}
console.log(i); // `i is not defined`
Works with if too
var log = function(msg) {};
if(someCond) {
let log = Math.log;
// do some stuff
}
log("I'm done here");
Easier closures
broken example
var a = ['rhum', 'banana', 'nutella'];
for(var i = 0, n=a.length; i<n; i++) {
var nomnom = a[i];
setTimeout(function() {
console.log(nomnom);
}, 500*(i+1))
}
Easy fix
var a = ['rhum', 'banana', 'nutella'];
for(var i = 0, n=a.length; i<n; i++) {
let nomnom = a[i];
setTimeout(function() {
console.log(nomnom);
}, 500*(i+1))
}
let('s) recap

works like var
scope is defined by the current block ({ })
const
Like let , but define read-only constant declarations.
'use strict';
const i = 10;
i = 5; // throw error
Destructuration
24

✗

✗
With array
// Assignment
var [day, month, year] = [19, 02, 2014];
// Swap two values.
var x=3, y=4;
[x, y] = [y, x];
Array with functions
var now = function() { return [19, 02, 2014]; }
var [day, month] = now();
var [, , year] = now();
With objects
var now = function() { return {
d: 19,
m: 2,
y: 2014
}}
var {d: day, m: month} = now();
// day: 19
// month: 2
As argument of a function
recipes = [
{ name: 'burger', calorie: 215 },
{ name: 'pizza', calorie: 266 } ];
recipes.forEach(function
({ name: name, calorie: calorie }) {
console.log(name, calorie);
}
);
Default function parameters
24

30

✗
Ability to define default value for functions
paramaters.
No more:
function(a) {
if(!a) { a = 10; }
// do stuff with a
}
Now
function(a=10) {
// do stuff with a
}
Undefined and null
undefined will trigger the evaluation of the default value,
not null
function point (x, y=1, z=1) {
return console.log(x, y, z);
}
point(10, null); // 10, null, 1
Arity
Number of parameters without default value
(function(a){}).length // 1
(function(a=10){}).length // 0
(function(a=10, b){}).length // 1
Rest parameters
24

✗

✗
Better than arguments
function(name) {
console.log(name);
arguments[0] = 'ME !';
console.log(name); // ME !
Array.isArray(arguments); // false
}
Now
function(...args) {
Array.isArray(args); // true
// do some stuff
}
function(name, ...more) {
}
Example
var humblify = function(name, ...qualities) {
console.log('Hello %s', name);
console.log('You are '+qualities.join(' and '));
}
humblify('Greg', 'awesome', 'the master of the universe');
// Hello Greg
// You are awesome and the master of the universe
Restrictions
Rest parameters can only be the last parameter
// incorrect
function(...args, callback) {
}
Details
Rest parameter is always an array
function f(name, ...more) {
Array.isArray(more); // always true
return more.length;
}
f(); // returns 0
Arity
Does not include the rest parameter
(function(a) {}).length // 1
(function(a, ...rest) {}).length // 1
Spread
24 (with array)
27-28 (with functions)

✗

✗
Expand expression where multiple
arguments or multiple element are needed
More powerful array
manipulation
Usecase: create new array with an existing one inside it:
var from = [1, 2];
// wants: [0, 1, 2, 3] ie [0, from, 3]
With es5
a.unshift(0);
a.push(3);
// and splice is here also

With es6

var total = [0, ...from, 3];
Converting any array-like
Array like ???

Object with a length property
Can access elements with []
var fake = {
0: 'I am',
1: 'not',
2: 'an aray',
length: 3
};
Array like in the wild
Function's arguments
All nodeList from the DOM
Before:
var nodes = document.querySelectorAll('p');
var nodes = [].slice.call(nodes);
And now:
nodes = [...nodes];
Array conversion
Better way:
Array.from(document.querySelectorAll('p'));
Out of the scope of the talk.
Spread with functions
A better apply

var f = function(one, two, three) {}
var a = [1, 2, 3];
f.apply(null, a);
Apply ?
Function.prototype.apply
fun.apply(thisArg, [argsArray])
Apply example
function f() {
for(let i=0; i<arguments.length; ++i)
console.log(arguments[i]);
}
f.apply(this, ['one', 2, 'foo']);
// one
// 2
// foo
With es6's spread
var f = function(one, two, three) {}
var a = [1, 2, 3];
f(...a);
Sweet syntax
var f = function(a, b, c, d, e, f) {};
var a = [1, 2];
f(-1, ...a, 3, ...[-3, -4]);
Apply for new
With es5, one cannot use apply with new .
var Constructor = function() {
// do some stuff
}
var c = new Constructor.apply({}, []); //invalid

But now:
var dataFields = readDateFields(database);
var d = new Date(...dateFields);
Better push
To push multiple elements:
var a = [];
var toPush = [1, 2, 3];
a.push.apply(a, toPush);
And now:
a.push(...toPush);
Next...

Iterators
24

✗

✗
An iterator lets you iterate over the contents of an object.
In ES6, an iterator is an object with a next() method which
returns {done, value} tuples.
An iterable is an object which can return an iterator.
Arrays are iterable:
var a = [1,2,3],
i = a.iterator();
console.log(i.next());
console.log(i.next());
console.log(i.next());
console.log(i.next());

//
//
//
//

{done:
{done:
{done:
{done:

false, value: 1}
false, value: 2}
false, value: 3}
true, value: undefined}
The for-of loop can be used to simplify iterations:
var a = [1,2,3];
for (var num of a) {
console.log(num); // 1, 2, 3
}
Array comprehensions:
var a = [
{ color: 'red' },
{ color: 'blue' }
];
[ x.color for (x of a) if ('blue' === x.color) ]
// [ 'blue' ]
We can make any object iterable:

function ClassA() {
this.elements = [1, 2, 3];
}
By adding the @@iterator method:
ClassA.prototype['@@iterator'] = function() {
return {
elements: this.elements,
index: 0,
next: function() {
if (this.index >= this.elements.length)
return {
done: true,
value: undefined
};
else
return {
done: false,
value: this.elements[this.index++]
};
}}};
We can iterate over the Object:

var col = new ClassA();
for (var num of col) {
console.log(num); // 1, 2, 3
}
Generators
27

30

✗
A generator is a special type of iterator.
A generator provides a throw() method. Its next()
method accepts a parameter.
A generator function acts as a constructor for a generator.
Generators offer a clean way of doing asynchronous
programming!
Simple example:
var helloWorld = function*() {
yield 'hello';
yield 'world';
}
var hw = helloWorld();
console.log( hw.next() ); // { value: 'hello', done: false }
console.log( hw.next() ); // { value: 'world', done: false }
console.log( hw.next() ); // { value: undefined, done: true }
Passing values back to generator:
var helloWorld = function*() {
var nextWord = yield 'hello';
yield nextWord;
}
var hw = helloWorld();
console.log( hw.next() );
// { value: 'hello', done: false }
console.log( hw.next('world') ); // { value: 'world', done: false }
console.log( hw.next() );
// { value: undefined, done: true }
Let's take it step-by-step to see how code gets suspended...
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.next('world') );
console.log( hw.next() );
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.next('world') );
console.log( hw.next() );
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.next('world') );
console.log( hw.next() );
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.next('world') );
console.log( hw.next() );
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.next('world') );
console.log( hw.next() );
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.next('world') );
console.log( hw.next() );

Yield 1...
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.next('world') );
console.log( hw.next() );

Yield 1...
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.next('world') );
console.log( hw.next() );

Yield 1...
{ done: false, value: 'hello'
}
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.next('world') );
console.log( hw.next() );

Yield 1...
{ done: false, value: 'hello'
}
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.next('world') );
console.log( hw.next() );

Yield 1...
{ done: false, value: 'hello'
}
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.next('world') );
console.log( hw.next() );

Yield 1...
{ done: false, value: 'hello'
}
Yield 2...
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.next('world') );
console.log( hw.next() );

Yield 1...
{ done: false, value: 'hello'
}
Yield 2...
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.next('world') );
console.log( hw.next() );

Yield 1...
{ done: false, value: 'hello'
}
Yield 2...
{ done: false, value: 'world'
}
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.next('world') );
console.log( hw.next() );

Yield 1...
{ done: false, value: 'hello'
}
Yield 2...
{ done: false, value: 'world'
}
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.next('world') );
console.log( hw.next() );

Yield 1...
{ done: false, value: 'hello'
}
Yield 2...
{ done: false, value: 'world'
}
No more yields...
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}

Yield 1...
{ done: false, value: 'hello'
}
Yield 2...
{ done: false, value: 'world'
}
No more yields...
{ done: true, value: undefined
}

var hw = helloWorld();
console.log( hw.next() );
console.log( hw.next('world') );
console.log( hw.next() );
The code in the generator doesn't start executing until you say
so.
When the yield statement is encountered it suspends
execution until you tell it to resume.
What about throw() -ing errors?
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.throw('Voldemort')
);
console.log( hw.next() );
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.throw('Voldemort')
);
console.log( hw.next() );
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.throw('Voldemort')
);
console.log( hw.next() );
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.throw('Voldemort')
);
console.log( hw.next() );
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.throw('Voldemort')
);
console.log( hw.next() );

Yield 1...
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.throw('Voldemort')
);
console.log( hw.next() );

Yield 1...
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.throw('Voldemort')
);
console.log( hw.next() );

Yield 1...
{ done: false, value: 'hello'
}
var helloWorld = function*() {
console.log('Yield 1...');
var nextWord = yield 'hello';
console.log('Yield 2...');
yield nextWord;
console.log('No more yields...');
}
var hw = helloWorld();
console.log( hw.next() );
console.log( hw.throw('Voldemort')
);
console.log( hw.next() );

Yield 1...
{ done: false, value: 'hello'
}
Error: Voldemort
How do Generators make asynchronous programming easier?
The old-school way:
var readFile = function(fileName, cb) { ... };
var main = function(cb) {
readFile('file1', function(err, contents1) {
if (err) return cb(err);
console.log(contents1);
readFile('file2', function(err, contents2) {
if (err) return cb(err);
console.log(contents2);
cb();
});
});
}
main(console.error);
Improved using Promises:
var readFile = Promise.promisify(function(fileName, cb) { ... });
var main = function() {
return readFile('file1')
.then(function(contents) {
console.log(contents);
return readFile('file2');
})
.then(function(contents) {
console.log(contents);
})
.catch(console.error);
}
main();
We can do better with generators.
But first we need a function which will automatically handle
the yield -ed values and call next() on the generator...
Automatically resolve Promises and call next() :
var runGenerator = function(generatorFunction) {
var gen = generatorFunction();
var gNext = function(err, answer) {
if (err) return gen.throw(err);
var res = gen.next(answer);
if (!res.done) {
Promise.resolve(res.value)
.then(function(newAnswer) {
gNext(null, newAnswer);
})
.catch(gNext);
}
};
gNext();
}
Now we can rewrite main() as a generator function:
var readFile = Promise.promisify(function(fileName, cb) { ... });
var main = function*() {
try {
console.log( yield readFile('file1') );
console.log( yield readFile('file2') );
} catch (err) {
console.error(err);
}
}
runGenerator(main);
You don't need to write runGenerator() yourself.
https://github.com/visionmedia/co - similar to
runGenerator but more powerful.
https://github.com/petkaantonov/bluebird - kick-ass
Promise library and provides runGenerator-like methods.
Generator delegation:
var inner = function*() {
try {
yield callServer1();
yield callServer2();
} catch (e) {
console.error(e);
}
};

var outer = function*() {
try {
yield callServer1();
yield callServer2();
} catch (e) {
console.error(e);
}
};

var outer = function*() {
yield* inner();
};

runGenerator(outer);

runGenerator(outer);
Generator comprehension:
(for (x of a)
for (y of b)
x * y)

(function* () {
for (x of a) {
for (y of b) {
yield x * y;
}
}
}())
Generators = future of JS asynchronous programming.
...and ES6 also has Promises!
http://spion.github.io/posts/why-i-am-switching-topromises.html
Next...

Collections
24

30

11
Set - no duplicates allowed
var items = new Set();
items.add(5);
items.add("5");
items.add(5);
console.log(items.size);

// 2

var items = new Set([1,2,3,4,5,5,5]);
console.log(items.size);
// 5
Modifying a Set
var items = new Set([1,2,3,4,4]);
console.log( items.has(4) ); // true
console.log( items.has(5) ); // false
items.delete(4);
console.log( items.has(4) ); // false
console.log( items.size ); // 3
items.clear();
console.log( items.size ); // 0
Iterate over a Set using for-of
var items = new Set([1,2,3,4,4]);
for (let num of items) {
console.log( num );
}

// 1, 2, 3, 4
Map - map from key to value
var map = new Map();
map.set("name", "John");
map.set(23, "age");
console.log( map.has(23); ) // true
console.log( map.get(23) ); // "age"
console.log( map.size );
// 2
Map vs Object
Maps can have non-string keys
Maps don't have prototype leakage issues, i.e. no need to
use hasOwnProperty()
But
Modifying a Map
var map = new Map([ ['name', 'John'], [23, 'age'] ]);
console.log( map.size );
// 2
map.delete(23);
console.log( map.get(23) ); // undefined
map.clear();
console.log( map.size ); // 0
Iterating over a Map
var map = new Map([ ['name', 'John'], [23, 'age'] ]);
for (var value of map.values()) { ... }
for (var key of map.keys()) { ... }
for (var item of map.items()) {
console.log('key: ' + item[0] + ', value: ' + item[1]);
}
for (var item of map) { // same as iterating map.items() }
map.forEach(function(value, key, map) { ... });
WeakMap - similar to Map , but...
Only allows Object keys
Only holds a reference to the Object used as a key, so it
doesn't prevent garbage collection
Do no provide a size
Cannot be iterated over
var weakMap = new WeakMap();
var key = {
stuff: true
};
weakMap.set(key, 123); // weakMap contains 1 item
delete key;

// weakMap is now empty
Next...

Typed objects
✗

✗

✗
Typed objects are similar to struct objects in C
They provide memory-safe, structured access to contiguous
data
They can expose a binary representation, making
serialization/de-serialization easy
Example: represent a 2D point
const Point2D = new StructType({
x: uint32,
y: uint32
});
Can access the underlying storage of the struct
let p = Point2D({x : 0, y : 0});
p.x = 5;
let arrayBuffer = Point.storage(p).buffer;
typeof arrayBuffer // ArrayBuffer
arrayBuffer.byteLength // 8
Hierarchy of typed objects
const Corner = new StructType({ point: Point2D });
const Triangle = Corner.dim(3);
let t = Triangle([{ point: { x: 0, y: 0 } },
{ point: { x: 5, y: 5 } },
{ point: { x: 10, y: 0 } }]);
t[0].point.x = 5;
A type object and all of its sub objects share the same memory

let t = Triangle([{ point: { x: 0, y: 0 } },
{ point: { x: 5, y: 5 } },
{ point: { x: 10, y: 0 } }]);
Triangle.storage(t).buffer.byteLength; // 24
Typed objects use copy-on-write
const Corner = new StructType({
point: Point2D
});
let p = Point2D({ x: 1, y: 1 });
let c = Corner({ point: {x: 2, y: 2} });
c.point = p; // p gets copied
c.point.x = 5;
p.x; // 1
Built-in value types
uint8, uint8Clamped
uint16
uint32
int8
int16
int32
float32
float64
boolean
string
Next...

Direct proxies
24

✗

✗
Direct proxies allows you to intercept calls made to a regular
object
They can wrap any Object , including Date ,
Function , etc.
Proxies are meant to work 'transparently'
var target = [];
var handler = { get: function() {...} };
var p = Proxy(target, handler);
Object.prototype.toString.call(p) // "[object Array]"
Object.getPrototypeOf(p) // Array.prototype
typeof p // "object"
Array.isArray(p) // true
p[0] // triggers handler.get(target, "0", p)
p === target // false
Proxy handler can choose what to intercept
getOwnPropertyDescriptor
getOwnPropertyNames
getPrototypeOf
defineProperty
deleteProperty
freeze
seal
preventExtensions
isFrozen
isExtensible

isSealed
has
hasOwn
get
set
enumerate
keys
apply
construct
Next...

Template strings
✗

✗

✗
What template strings allow
Multi-line strings
String formatting - think printf from C
HTML escaping
Localization/internationalization
Basic substitution
var name = "Tom",
msg = `Hello, ${name}!`;
console.log(msg);

// "Hello, Tom!"
Expressions
var total = 30,
msg = `The total is ${total * 2} units`;
console.log(msg);

// "The total is 60 units"
Multi-line
var total = 30,
var msg = `The total is
${total * 2}
units`;
Functions
// Gets called with:
//
['Total is ', ' units']
//
60
var myFunc = function(literals) {
var str = '', i = 0;
while (i < literals.length) {
str += literals[i++];
if (i < arguments.length) { str += '[' + arguments[i] + ']'; }
}
return str;
};
var total = 30;
console.log( myFunc`Total is ${total * 2} units` );
// Total is [60] units
Next...

API improvements
24

✗

✗

with a few exceptions (full details)
New Math functions

log10 , log2 , log1p , expm1 , cosh , sinh , tanh ,
acosh , asinh , atanh , hypot , trunc , sign
Number
.isFinite()
.isNaN() - better than isNaN()
.isInteger()
.EPSILON - smallest values such that 1 +
Number.EPSILON > 1
String
.repeat(n) - copy current string n times
.startsWith(str)
.endsWith(str)
.contains(str)
.toArray() - same as .split('')
Next...

Modularity
✗

✗

✗
Classes
In es5

Classes doesn't exist natively
Prototype based inheritance
Framework and libraries implement their own class system
New keyword
class Laptop {
constructor() {
this.brand = 'asus';
}
on() { ... }
off() { ... }
}
Call the parent
class SmashedLaptop extend Laptop {
constructor() {
super();
this.pieces = [];
}
}
Key points

constructor replace the function definition in es5
No access to the prototype of the class
Methods are defined the same way as objects
Can call the parent with super (and perform initialization
within the constructor)
Modules
• import the default export of a module
import $ from "jquery";
• binding an external module to a variable
module crypto from "crypto";
• binding a module's exports to variables
import { encrypt, decrypt } from "crypto";
Modules
• binding & renaming one of a module's exports
import { encrypt as enc } from "crypto";
• re-exporting another module's exports
export * from "crypto";
• re-exporting specified exports
from another module
export { foo, bar } from "crypto";
Why ?

No need for the global object anymore
Works well with existing modules system (AMD,
CommonJS and node)
Simplicity and usability
Compatibility with browser and non-browser environments
Easy asynchronous external loading
Exporting and importing
module "chocolate" {
export let cocoa = 75;
}
In another file:
import { cocoa } from "chocolate";
// or
import { cocoa as c} from "chocolate";
Default export
module "foo" {
export default function() {console.log("Hi")}
}
import foo from "foo"; // no brackets
foo(); // Hi
Internals

Top-level variables stay inside the module
export make variables visible to the other modules
Can be read (get)
Cannot be changed (set)
Cannot be dynamically changed at runtime
Modules are recursively instantiated before evaluation
Modules' body is run after all dependencies are instantiated
That's all for
today!

See http://kangax.github.io/es5-compat-table/es6/ for more
Useful links

http://www.ecmascript.org/
http://www.esdiscuss.org/
https://developer.mozilla.org/en/docs/Web/JavaScript/ECMAScript

More Related Content

What's hot

JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6Solution4Future
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Nilesh Jayanandana
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.boyney123
 
ES6 in Production [JSConfUY2015]
ES6 in Production [JSConfUY2015]ES6 in Production [JSConfUY2015]
ES6 in Production [JSConfUY2015]Guillermo Paz
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generatorsRamesh Nair
 
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
 
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
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!Brendan Eich
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScriptGarth Gilmour
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftGiordano Scalzo
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchainedEduard Tomàs
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in RustIngvar Stepanyan
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Datagreenwop
 
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵Wanbok Choi
 

What's hot (20)

JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
 
ES6 in Production [JSConfUY2015]
ES6 in Production [JSConfUY2015]ES6 in Production [JSConfUY2015]
ES6 in Production [JSConfUY2015]
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generators
 
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
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
 
Modern JS with ES6
Modern JS with ES6Modern JS with ES6
Modern JS with ES6
 
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
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 
Rust ⇋ JavaScript
Rust ⇋ JavaScriptRust ⇋ JavaScript
Rust ⇋ JavaScript
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in Swift
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in Rust
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
 

Viewers also liked

ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptWojciech Dzikowski
 
Lecture 3 - ES6 Script Advanced for React-Native
Lecture 3 - ES6 Script Advanced for React-NativeLecture 3 - ES6 Script Advanced for React-Native
Lecture 3 - ES6 Script Advanced for React-NativeKobkrit Viriyayudhakorn
 
Real World Windows 8 Apps in JavaScript
Real World Windows 8 Apps in JavaScriptReal World Windows 8 Apps in JavaScript
Real World Windows 8 Apps in JavaScriptDomenic Denicola
 
The ES6 Conundrum - All Things Open 2015
The ES6 Conundrum - All Things Open 2015The ES6 Conundrum - All Things Open 2015
The ES6 Conundrum - All Things Open 2015Christian Heilmann
 
Creating Truly RESTful APIs
Creating Truly RESTful APIsCreating Truly RESTful APIs
Creating Truly RESTful APIsDomenic Denicola
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was BornDomenic Denicola
 
Canvas de shooting 制作のポイント
Canvas de shooting 制作のポイントCanvas de shooting 制作のポイント
Canvas de shooting 制作のポイントYohei Munesada
 
小規模案件で作られた秘伝のタレ
小規模案件で作られた秘伝のタレ小規模案件で作られた秘伝のタレ
小規模案件で作られた秘伝のタレMuyuu Fujita
 
ノンゲーム系スマホアプリ制作 First Step
ノンゲーム系スマホアプリ制作 First Stepノンゲーム系スマホアプリ制作 First Step
ノンゲーム系スマホアプリ制作 First StepYohei Munesada
 
今こそCSS 今こそfor you
今こそCSS 今こそfor you 今こそCSS 今こそfor you
今こそCSS 今こそfor you Tatsuya Kosuge
 
最近、実務に導入してみたフロントエンドの技術8つの良かった点と反省点
最近、実務に導入してみたフロントエンドの技術8つの良かった点と反省点最近、実務に導入してみたフロントエンドの技術8つの良かった点と反省点
最近、実務に導入してみたフロントエンドの技術8つの良かった点と反省点Horiguchi Seito
 

Viewers also liked (20)

ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern Javascript
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
Lecture 2: ES6 / ES2015 Slide
Lecture 2: ES6 / ES2015 SlideLecture 2: ES6 / ES2015 Slide
Lecture 2: ES6 / ES2015 Slide
 
Lecture 3 - ES6 Script Advanced for React-Native
Lecture 3 - ES6 Script Advanced for React-NativeLecture 3 - ES6 Script Advanced for React-Native
Lecture 3 - ES6 Script Advanced for React-Native
 
Real World Windows 8 Apps in JavaScript
Real World Windows 8 Apps in JavaScriptReal World Windows 8 Apps in JavaScript
Real World Windows 8 Apps in JavaScript
 
The ES6 Conundrum - All Things Open 2015
The ES6 Conundrum - All Things Open 2015The ES6 Conundrum - All Things Open 2015
The ES6 Conundrum - All Things Open 2015
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 
Creating Truly RESTful APIs
Creating Truly RESTful APIsCreating Truly RESTful APIs
Creating Truly RESTful APIs
 
The Final Frontier
The Final FrontierThe Final Frontier
The Final Frontier
 
Client-Side Packages
Client-Side PackagesClient-Side Packages
Client-Side Packages
 
JavaScript on the Desktop
JavaScript on the DesktopJavaScript on the Desktop
JavaScript on the Desktop
 
Async Frontiers
Async FrontiersAsync Frontiers
Async Frontiers
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
 
Canvas de shooting 制作のポイント
Canvas de shooting 制作のポイントCanvas de shooting 制作のポイント
Canvas de shooting 制作のポイント
 
小規模案件で作られた秘伝のタレ
小規模案件で作られた秘伝のタレ小規模案件で作られた秘伝のタレ
小規模案件で作られた秘伝のタレ
 
ノンゲーム系スマホアプリ制作 First Step
ノンゲーム系スマホアプリ制作 First Stepノンゲーム系スマホアプリ制作 First Step
ノンゲーム系スマホアプリ制作 First Step
 
Domains!
Domains!Domains!
Domains!
 
Promises, Promises
Promises, PromisesPromises, Promises
Promises, Promises
 
今こそCSS 今こそfor you
今こそCSS 今こそfor you 今こそCSS 今こそfor you
今こそCSS 今こそfor you
 
最近、実務に導入してみたフロントエンドの技術8つの良かった点と反省点
最近、実務に導入してみたフロントエンドの技術8つの良かった点と反省点最近、実務に導入してみたフロントエンドの技術8つの良かった点と反省点
最近、実務に導入してみたフロントエンドの技術8つの良かった点と反省点
 

Similar to ES6 - Next Generation Javascript

JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineMovel
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6Nitay Neeman
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest UpdatesIftekhar Eather
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the mastersAra Pehlivanian
 
ES6, 잘 쓰고 계시죠?
ES6, 잘 쓰고 계시죠?ES6, 잘 쓰고 계시죠?
ES6, 잘 쓰고 계시죠?장현 한
 
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
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Troy Miles
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General IntroductionThomas Johnston
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervosoLuis Vendrame
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 

Similar to ES6 - Next Generation Javascript (20)

ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy Cresine
 
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
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
ES6, 잘 쓰고 계시죠?
ES6, 잘 쓰고 계시죠?ES6, 잘 쓰고 계시죠?
ES6, 잘 쓰고 계시죠?
 
Groovy
GroovyGroovy
Groovy
 
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...
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 
Internal workshop es6_2015
Internal workshop es6_2015Internal workshop es6_2015
Internal workshop es6_2015
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General Introduction
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 

More from Ramesh Nair

solUI Introduction (2019)
solUI Introduction (2019)solUI Introduction (2019)
solUI Introduction (2019)Ramesh Nair
 
Kickback - incentivizing event attendance through crypto economics
Kickback - incentivizing event attendance through crypto economicsKickback - incentivizing event attendance through crypto economics
Kickback - incentivizing event attendance through crypto economicsRamesh Nair
 
Introduction to Blockchains
Introduction to BlockchainsIntroduction to Blockchains
Introduction to BlockchainsRamesh Nair
 
Introduction to PhoneGap
Introduction to PhoneGapIntroduction to PhoneGap
Introduction to PhoneGapRamesh Nair
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to DartRamesh Nair
 
Javascript Update May 2013
Javascript Update May 2013Javascript Update May 2013
Javascript Update May 2013Ramesh Nair
 

More from Ramesh Nair (6)

solUI Introduction (2019)
solUI Introduction (2019)solUI Introduction (2019)
solUI Introduction (2019)
 
Kickback - incentivizing event attendance through crypto economics
Kickback - incentivizing event attendance through crypto economicsKickback - incentivizing event attendance through crypto economics
Kickback - incentivizing event attendance through crypto economics
 
Introduction to Blockchains
Introduction to BlockchainsIntroduction to Blockchains
Introduction to Blockchains
 
Introduction to PhoneGap
Introduction to PhoneGapIntroduction to PhoneGap
Introduction to PhoneGap
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to Dart
 
Javascript Update May 2013
Javascript Update May 2013Javascript Update May 2013
Javascript Update May 2013
 

Recently uploaded

UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7DianaGray10
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
Spring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfSpring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfAnna Loughnan Colquhoun
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
RAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIRAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIUdaiappa Ramachandran
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServicePicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServiceRenan Moreira de Oliveira
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
Things you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceThings you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceMartin Humpolec
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?SANGHEE SHIN
 
Introduction to Quantum Computing
Introduction to Quantum ComputingIntroduction to Quantum Computing
Introduction to Quantum ComputingGDSC PJATK
 

Recently uploaded (20)

UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
Spring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfSpring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdf
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
RAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIRAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AI
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServicePicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
Things you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceThings you didn't know you can use in your Salesforce
Things you didn't know you can use in your Salesforce
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?
 
Introduction to Quantum Computing
Introduction to Quantum ComputingIntroduction to Quantum Computing
Introduction to Quantum Computing
 

ES6 - Next Generation Javascript

  • 1. ES6 Next Generation Javascript By Ramesh Nair and Grégoire Charvet https://github.com/hiddentao/es6-slides
  • 2. Speakers Grégoire Charvet (geekingfrog.com) Full time node.js developper Passionate about the web Working on the web for almost 2 years now Ramesh Nair (hiddentao.com) Full time Javascript/Node developper Also worked with PHP, Python, Java, C++ Loves optimizing for performance
  • 3. Rapid history of javascript
  • 4. The birth Created in 10 days in 1995 (by Brendan Eich) at Netscape Brought to ECMA a year later to standardize it javaScript has nothing to do with java
  • 5. Early history ECMAScript 2 in 98, 3 in 99 War with Microsoft -> ES4 has never been adopted In 2005, Microsoft introduced ajax In 2009, all parties agreed to move forward with ES5 + harmony process
  • 6. Now Javascript most well known implementation of ECMAScript (with ActionScript) Javascript is the assembly of the web Confusing version number, JS 1.8 correspond to ES6
  • 7. ES6 ES6 work started in 2011 As of now (Feb 2014), ES6 is not yet adopted (but it's almost there) Major milestone Not 'production ready' yet
  • 8. What we will cover today Support Scope and control Iterators and Generators Collections Typed objects Direct proxies Template strings API improvements Modularity
  • 9. Support 24 30 ✗ For chrome, need to enable the experimental js features full table
  • 10. Node.js support Node.js: get the latest 0.11 and add the flag --harmony Support is the same as chrome (V8)
  • 11. Safari support Almost the same as IE (so quasi inexistant)
  • 14. Before for(var i=10; i>0 ; i--) { // do stuff with i } console.log(i); // 0
  • 15. let for(let i=10; i>10; i--) { } console.log(i); // `i is not defined`
  • 16. Works with if too var log = function(msg) {}; if(someCond) { let log = Math.log; // do some stuff } log("I'm done here");
  • 17. Easier closures broken example var a = ['rhum', 'banana', 'nutella']; for(var i = 0, n=a.length; i<n; i++) { var nomnom = a[i]; setTimeout(function() { console.log(nomnom); }, 500*(i+1)) }
  • 18. Easy fix var a = ['rhum', 'banana', 'nutella']; for(var i = 0, n=a.length; i<n; i++) { let nomnom = a[i]; setTimeout(function() { console.log(nomnom); }, 500*(i+1)) }
  • 19. let('s) recap works like var scope is defined by the current block ({ })
  • 20. const Like let , but define read-only constant declarations. 'use strict'; const i = 10; i = 5; // throw error
  • 22. With array // Assignment var [day, month, year] = [19, 02, 2014]; // Swap two values. var x=3, y=4; [x, y] = [y, x];
  • 23. Array with functions var now = function() { return [19, 02, 2014]; } var [day, month] = now(); var [, , year] = now();
  • 24. With objects var now = function() { return { d: 19, m: 2, y: 2014 }} var {d: day, m: month} = now(); // day: 19 // month: 2
  • 25. As argument of a function recipes = [ { name: 'burger', calorie: 215 }, { name: 'pizza', calorie: 266 } ]; recipes.forEach(function ({ name: name, calorie: calorie }) { console.log(name, calorie); } );
  • 27. Ability to define default value for functions paramaters. No more: function(a) { if(!a) { a = 10; } // do stuff with a }
  • 28. Now function(a=10) { // do stuff with a }
  • 29. Undefined and null undefined will trigger the evaluation of the default value, not null function point (x, y=1, z=1) { return console.log(x, y, z); } point(10, null); // 10, null, 1
  • 30. Arity Number of parameters without default value (function(a){}).length // 1 (function(a=10){}).length // 0 (function(a=10, b){}).length // 1
  • 32. Better than arguments function(name) { console.log(name); arguments[0] = 'ME !'; console.log(name); // ME ! Array.isArray(arguments); // false }
  • 33. Now function(...args) { Array.isArray(args); // true // do some stuff } function(name, ...more) { }
  • 34. Example var humblify = function(name, ...qualities) { console.log('Hello %s', name); console.log('You are '+qualities.join(' and ')); } humblify('Greg', 'awesome', 'the master of the universe'); // Hello Greg // You are awesome and the master of the universe
  • 35. Restrictions Rest parameters can only be the last parameter // incorrect function(...args, callback) { }
  • 36. Details Rest parameter is always an array function f(name, ...more) { Array.isArray(more); // always true return more.length; } f(); // returns 0
  • 37. Arity Does not include the rest parameter (function(a) {}).length // 1 (function(a, ...rest) {}).length // 1
  • 38. Spread 24 (with array) 27-28 (with functions) ✗ ✗
  • 39. Expand expression where multiple arguments or multiple element are needed
  • 40. More powerful array manipulation Usecase: create new array with an existing one inside it: var from = [1, 2]; // wants: [0, 1, 2, 3] ie [0, from, 3]
  • 41. With es5 a.unshift(0); a.push(3); // and splice is here also With es6 var total = [0, ...from, 3];
  • 43. Array like ??? Object with a length property Can access elements with [] var fake = { 0: 'I am', 1: 'not', 2: 'an aray', length: 3 };
  • 44. Array like in the wild Function's arguments All nodeList from the DOM
  • 45. Before: var nodes = document.querySelectorAll('p'); var nodes = [].slice.call(nodes); And now: nodes = [...nodes];
  • 47. Spread with functions A better apply var f = function(one, two, three) {} var a = [1, 2, 3]; f.apply(null, a);
  • 49. Apply example function f() { for(let i=0; i<arguments.length; ++i) console.log(arguments[i]); } f.apply(this, ['one', 2, 'foo']); // one // 2 // foo
  • 50. With es6's spread var f = function(one, two, three) {} var a = [1, 2, 3]; f(...a);
  • 51. Sweet syntax var f = function(a, b, c, d, e, f) {}; var a = [1, 2]; f(-1, ...a, 3, ...[-3, -4]);
  • 52. Apply for new With es5, one cannot use apply with new . var Constructor = function() { // do some stuff } var c = new Constructor.apply({}, []); //invalid But now: var dataFields = readDateFields(database); var d = new Date(...dateFields);
  • 53. Better push To push multiple elements: var a = []; var toPush = [1, 2, 3]; a.push.apply(a, toPush); And now: a.push(...toPush);
  • 55. An iterator lets you iterate over the contents of an object. In ES6, an iterator is an object with a next() method which returns {done, value} tuples. An iterable is an object which can return an iterator.
  • 56. Arrays are iterable: var a = [1,2,3], i = a.iterator(); console.log(i.next()); console.log(i.next()); console.log(i.next()); console.log(i.next()); // // // // {done: {done: {done: {done: false, value: 1} false, value: 2} false, value: 3} true, value: undefined}
  • 57. The for-of loop can be used to simplify iterations: var a = [1,2,3]; for (var num of a) { console.log(num); // 1, 2, 3 }
  • 58. Array comprehensions: var a = [ { color: 'red' }, { color: 'blue' } ]; [ x.color for (x of a) if ('blue' === x.color) ] // [ 'blue' ]
  • 59. We can make any object iterable: function ClassA() { this.elements = [1, 2, 3]; }
  • 60. By adding the @@iterator method: ClassA.prototype['@@iterator'] = function() { return { elements: this.elements, index: 0, next: function() { if (this.index >= this.elements.length) return { done: true, value: undefined }; else return { done: false, value: this.elements[this.index++] }; }}};
  • 61. We can iterate over the Object: var col = new ClassA(); for (var num of col) { console.log(num); // 1, 2, 3 }
  • 63. A generator is a special type of iterator. A generator provides a throw() method. Its next() method accepts a parameter. A generator function acts as a constructor for a generator. Generators offer a clean way of doing asynchronous programming!
  • 64. Simple example: var helloWorld = function*() { yield 'hello'; yield 'world'; } var hw = helloWorld(); console.log( hw.next() ); // { value: 'hello', done: false } console.log( hw.next() ); // { value: 'world', done: false } console.log( hw.next() ); // { value: undefined, done: true }
  • 65. Passing values back to generator: var helloWorld = function*() { var nextWord = yield 'hello'; yield nextWord; } var hw = helloWorld(); console.log( hw.next() ); // { value: 'hello', done: false } console.log( hw.next('world') ); // { value: 'world', done: false } console.log( hw.next() ); // { value: undefined, done: true }
  • 66. Let's take it step-by-step to see how code gets suspended...
  • 67. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.next('world') ); console.log( hw.next() );
  • 68. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.next('world') ); console.log( hw.next() );
  • 69. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.next('world') ); console.log( hw.next() );
  • 70. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.next('world') ); console.log( hw.next() );
  • 71. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.next('world') ); console.log( hw.next() );
  • 72. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.next('world') ); console.log( hw.next() ); Yield 1...
  • 73. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.next('world') ); console.log( hw.next() ); Yield 1...
  • 74. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.next('world') ); console.log( hw.next() ); Yield 1... { done: false, value: 'hello' }
  • 75. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.next('world') ); console.log( hw.next() ); Yield 1... { done: false, value: 'hello' }
  • 76. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.next('world') ); console.log( hw.next() ); Yield 1... { done: false, value: 'hello' }
  • 77. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.next('world') ); console.log( hw.next() ); Yield 1... { done: false, value: 'hello' } Yield 2...
  • 78. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.next('world') ); console.log( hw.next() ); Yield 1... { done: false, value: 'hello' } Yield 2...
  • 79. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.next('world') ); console.log( hw.next() ); Yield 1... { done: false, value: 'hello' } Yield 2... { done: false, value: 'world' }
  • 80. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.next('world') ); console.log( hw.next() ); Yield 1... { done: false, value: 'hello' } Yield 2... { done: false, value: 'world' }
  • 81. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.next('world') ); console.log( hw.next() ); Yield 1... { done: false, value: 'hello' } Yield 2... { done: false, value: 'world' } No more yields...
  • 82. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } Yield 1... { done: false, value: 'hello' } Yield 2... { done: false, value: 'world' } No more yields... { done: true, value: undefined } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.next('world') ); console.log( hw.next() );
  • 83. The code in the generator doesn't start executing until you say so. When the yield statement is encountered it suspends execution until you tell it to resume. What about throw() -ing errors?
  • 84. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.throw('Voldemort') ); console.log( hw.next() );
  • 85. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.throw('Voldemort') ); console.log( hw.next() );
  • 86. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.throw('Voldemort') ); console.log( hw.next() );
  • 87. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.throw('Voldemort') ); console.log( hw.next() );
  • 88. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.throw('Voldemort') ); console.log( hw.next() ); Yield 1...
  • 89. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.throw('Voldemort') ); console.log( hw.next() ); Yield 1...
  • 90. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.throw('Voldemort') ); console.log( hw.next() ); Yield 1... { done: false, value: 'hello' }
  • 91. var helloWorld = function*() { console.log('Yield 1...'); var nextWord = yield 'hello'; console.log('Yield 2...'); yield nextWord; console.log('No more yields...'); } var hw = helloWorld(); console.log( hw.next() ); console.log( hw.throw('Voldemort') ); console.log( hw.next() ); Yield 1... { done: false, value: 'hello' } Error: Voldemort
  • 92. How do Generators make asynchronous programming easier?
  • 93. The old-school way: var readFile = function(fileName, cb) { ... }; var main = function(cb) { readFile('file1', function(err, contents1) { if (err) return cb(err); console.log(contents1); readFile('file2', function(err, contents2) { if (err) return cb(err); console.log(contents2); cb(); }); }); } main(console.error);
  • 94. Improved using Promises: var readFile = Promise.promisify(function(fileName, cb) { ... }); var main = function() { return readFile('file1') .then(function(contents) { console.log(contents); return readFile('file2'); }) .then(function(contents) { console.log(contents); }) .catch(console.error); } main();
  • 95. We can do better with generators. But first we need a function which will automatically handle the yield -ed values and call next() on the generator...
  • 96. Automatically resolve Promises and call next() : var runGenerator = function(generatorFunction) { var gen = generatorFunction(); var gNext = function(err, answer) { if (err) return gen.throw(err); var res = gen.next(answer); if (!res.done) { Promise.resolve(res.value) .then(function(newAnswer) { gNext(null, newAnswer); }) .catch(gNext); } }; gNext(); }
  • 97. Now we can rewrite main() as a generator function: var readFile = Promise.promisify(function(fileName, cb) { ... }); var main = function*() { try { console.log( yield readFile('file1') ); console.log( yield readFile('file2') ); } catch (err) { console.error(err); } } runGenerator(main);
  • 98. You don't need to write runGenerator() yourself. https://github.com/visionmedia/co - similar to runGenerator but more powerful. https://github.com/petkaantonov/bluebird - kick-ass Promise library and provides runGenerator-like methods.
  • 99. Generator delegation: var inner = function*() { try { yield callServer1(); yield callServer2(); } catch (e) { console.error(e); } }; var outer = function*() { try { yield callServer1(); yield callServer2(); } catch (e) { console.error(e); } }; var outer = function*() { yield* inner(); }; runGenerator(outer); runGenerator(outer);
  • 100. Generator comprehension: (for (x of a) for (y of b) x * y) (function* () { for (x of a) { for (y of b) { yield x * y; } } }())
  • 101. Generators = future of JS asynchronous programming. ...and ES6 also has Promises! http://spion.github.io/posts/why-i-am-switching-topromises.html
  • 103. Set - no duplicates allowed var items = new Set(); items.add(5); items.add("5"); items.add(5); console.log(items.size); // 2 var items = new Set([1,2,3,4,5,5,5]); console.log(items.size); // 5
  • 104. Modifying a Set var items = new Set([1,2,3,4,4]); console.log( items.has(4) ); // true console.log( items.has(5) ); // false items.delete(4); console.log( items.has(4) ); // false console.log( items.size ); // 3 items.clear(); console.log( items.size ); // 0
  • 105. Iterate over a Set using for-of var items = new Set([1,2,3,4,4]); for (let num of items) { console.log( num ); } // 1, 2, 3, 4
  • 106. Map - map from key to value var map = new Map(); map.set("name", "John"); map.set(23, "age"); console.log( map.has(23); ) // true console.log( map.get(23) ); // "age" console.log( map.size ); // 2
  • 107. Map vs Object Maps can have non-string keys Maps don't have prototype leakage issues, i.e. no need to use hasOwnProperty() But
  • 108. Modifying a Map var map = new Map([ ['name', 'John'], [23, 'age'] ]); console.log( map.size ); // 2 map.delete(23); console.log( map.get(23) ); // undefined map.clear(); console.log( map.size ); // 0
  • 109. Iterating over a Map var map = new Map([ ['name', 'John'], [23, 'age'] ]); for (var value of map.values()) { ... } for (var key of map.keys()) { ... } for (var item of map.items()) { console.log('key: ' + item[0] + ', value: ' + item[1]); } for (var item of map) { // same as iterating map.items() } map.forEach(function(value, key, map) { ... });
  • 110. WeakMap - similar to Map , but... Only allows Object keys Only holds a reference to the Object used as a key, so it doesn't prevent garbage collection Do no provide a size Cannot be iterated over
  • 111. var weakMap = new WeakMap(); var key = { stuff: true }; weakMap.set(key, 123); // weakMap contains 1 item delete key; // weakMap is now empty
  • 113. Typed objects are similar to struct objects in C They provide memory-safe, structured access to contiguous data They can expose a binary representation, making serialization/de-serialization easy
  • 114. Example: represent a 2D point const Point2D = new StructType({ x: uint32, y: uint32 });
  • 115. Can access the underlying storage of the struct let p = Point2D({x : 0, y : 0}); p.x = 5; let arrayBuffer = Point.storage(p).buffer; typeof arrayBuffer // ArrayBuffer arrayBuffer.byteLength // 8
  • 116. Hierarchy of typed objects const Corner = new StructType({ point: Point2D }); const Triangle = Corner.dim(3); let t = Triangle([{ point: { x: 0, y: 0 } }, { point: { x: 5, y: 5 } }, { point: { x: 10, y: 0 } }]); t[0].point.x = 5;
  • 117. A type object and all of its sub objects share the same memory let t = Triangle([{ point: { x: 0, y: 0 } }, { point: { x: 5, y: 5 } }, { point: { x: 10, y: 0 } }]); Triangle.storage(t).buffer.byteLength; // 24
  • 118. Typed objects use copy-on-write const Corner = new StructType({ point: Point2D }); let p = Point2D({ x: 1, y: 1 }); let c = Corner({ point: {x: 2, y: 2} }); c.point = p; // p gets copied c.point.x = 5; p.x; // 1
  • 119. Built-in value types uint8, uint8Clamped uint16 uint32 int8 int16 int32 float32 float64 boolean string
  • 121. Direct proxies allows you to intercept calls made to a regular object They can wrap any Object , including Date , Function , etc.
  • 122. Proxies are meant to work 'transparently' var target = []; var handler = { get: function() {...} }; var p = Proxy(target, handler); Object.prototype.toString.call(p) // "[object Array]" Object.getPrototypeOf(p) // Array.prototype typeof p // "object" Array.isArray(p) // true p[0] // triggers handler.get(target, "0", p) p === target // false
  • 123. Proxy handler can choose what to intercept getOwnPropertyDescriptor getOwnPropertyNames getPrototypeOf defineProperty deleteProperty freeze seal preventExtensions isFrozen isExtensible isSealed has hasOwn get set enumerate keys apply construct
  • 125. What template strings allow Multi-line strings String formatting - think printf from C HTML escaping Localization/internationalization
  • 126. Basic substitution var name = "Tom", msg = `Hello, ${name}!`; console.log(msg); // "Hello, Tom!"
  • 127. Expressions var total = 30, msg = `The total is ${total * 2} units`; console.log(msg); // "The total is 60 units"
  • 128. Multi-line var total = 30, var msg = `The total is ${total * 2} units`;
  • 129. Functions // Gets called with: // ['Total is ', ' units'] // 60 var myFunc = function(literals) { var str = '', i = 0; while (i < literals.length) { str += literals[i++]; if (i < arguments.length) { str += '[' + arguments[i] + ']'; } } return str; }; var total = 30; console.log( myFunc`Total is ${total * 2} units` ); // Total is [60] units
  • 130. Next... API improvements 24 ✗ ✗ with a few exceptions (full details)
  • 131. New Math functions log10 , log2 , log1p , expm1 , cosh , sinh , tanh , acosh , asinh , atanh , hypot , trunc , sign
  • 132. Number .isFinite() .isNaN() - better than isNaN() .isInteger() .EPSILON - smallest values such that 1 + Number.EPSILON > 1
  • 133. String .repeat(n) - copy current string n times .startsWith(str) .endsWith(str) .contains(str) .toArray() - same as .split('')
  • 136. In es5 Classes doesn't exist natively Prototype based inheritance Framework and libraries implement their own class system
  • 137. New keyword class Laptop { constructor() { this.brand = 'asus'; } on() { ... } off() { ... } }
  • 138. Call the parent class SmashedLaptop extend Laptop { constructor() { super(); this.pieces = []; } }
  • 139. Key points constructor replace the function definition in es5 No access to the prototype of the class Methods are defined the same way as objects Can call the parent with super (and perform initialization within the constructor)
  • 140. Modules • import the default export of a module import $ from "jquery"; • binding an external module to a variable module crypto from "crypto"; • binding a module's exports to variables import { encrypt, decrypt } from "crypto";
  • 141. Modules • binding & renaming one of a module's exports import { encrypt as enc } from "crypto"; • re-exporting another module's exports export * from "crypto"; • re-exporting specified exports from another module export { foo, bar } from "crypto";
  • 142. Why ? No need for the global object anymore Works well with existing modules system (AMD, CommonJS and node) Simplicity and usability Compatibility with browser and non-browser environments Easy asynchronous external loading
  • 143. Exporting and importing module "chocolate" { export let cocoa = 75; } In another file: import { cocoa } from "chocolate"; // or import { cocoa as c} from "chocolate";
  • 144. Default export module "foo" { export default function() {console.log("Hi")} } import foo from "foo"; // no brackets foo(); // Hi
  • 145. Internals Top-level variables stay inside the module export make variables visible to the other modules Can be read (get) Cannot be changed (set) Cannot be dynamically changed at runtime Modules are recursively instantiated before evaluation Modules' body is run after all dependencies are instantiated
  • 146. That's all for today! See http://kangax.github.io/es5-compat-table/es6/ for more