SlideShare a Scribd company logo
import * as $ from 'jQuery';
import svg from 'svglib';
import Chart from 'Chart';
class LineChart extends Chart {
constructor(series, canvas = document.body){
super(series, canvas);
this.draw();
}
draw() {
var plot = svg.buildLineChart(this.series);
this.$canvas.append(plot);
this.series.forEach(x => {
var { max, average: avg } = LineChart.getSerieData(x);
super.addStats(max, avg);
});
}
static getSerieData(serie) {
if (serie.length > 0){
let sum = serie.reduce((x, y) => x+y);
return { max: Math.max(...series), average: sum/serie.length };
}
return null;
}
}
export default LineChart;
ECMAScript 2015
Overview
ECMAScript 6
@brunoscopelliti
in the browser and on the server, too
in a not too far future …
Object Literals Shorthand
It’s just syntactic sugar for Object literals.
var v = 42, propertyName = "count";
function fn() { console.log(v); };
// the old way
var obj = { v: v, fn: fn, fn2: function() { /*...*/ } };
obj[propertyName] = 10;
// es6 shorthand O/
var obj = {
v,
fn,
fn2() { /*...*/ },
[propertyName]: 10
}
Destructuring
Allows to extract values from object and array using patterns.
// ... and support default values
var [name, extension = ""] = "LICENSE".split(".");
console.log(extension) // ""
// it works with array too!
var [name, extension] = "me.jpeg".split(".");
console.log(extension); // jpeg
// destructuring + object literal shorthand
var { v, fn } = obj;
console.log(v); // 42
var { v: value, fn: log } = obj;
console.log(value); // 42
Rest & Spread Operator
The Spread operator turns an array into consecutive arguments in a function call. The Rest
operator binds trailing parameters to an array.
var arr = [1, 2]; arr.concat([3, 4]); // [1, 2, [3, 4]] FAIL! ಥ_ಥ
[3, 4].forEach(function(x) { arr.push(x) }); // [1, 2, 3, 4] At least it works ¯_(ツ)_/¯
// spread to the rescue!
arr.concat(...[3, 4]); // [1, 2, 3, 4] 0/
// rest
var [winner, ...theOthers] = ["a", "b", "c"];
console.log(theOthers instanceof Array); // true
console.log(theOthers.length); // 2
Super-powered functions
Varargs and default parameters.
// default value for function’s arguments
repeat("yo"); // yoyo
function repeat(msg, time = 2) {
return msg.repeat(time);
}
// rest parameters
function resize(width, height, ...elems){ console.log(elems); }
resize(100, 100, "#box", "#photo"); // ["#box", "#photo"]
function fn(...args){ console.log(args); }
fn(); // []
fn(42, "bho!"); // [42, "bho!"]
Block Scoped variables
Block scoped variable assignments with let and const.
> Organized code!
if(true){
let v = 42;
}
console.log(v); // ReferenceError: v is not defined
// constants
const pi = 3.14156;
pi = 3.14; // SyntaxError: invalid assignment to const pi
Arrow Functions
Function shorthand with arrow syntax, and more…
[1,2,3].reduce(function(a, b) { return a+b; });
// the syntax
[1,2,3].reduce((a,b) => { console.log("oO"); return a+b; }); // 6
// and even shorter
[1,2,3].reduce((a,b) => a+b);
Arrow Functions
… arrow functions share the same context with their surrounding code;
the context can’t be modified via call, apply nor bind.
var team = {
n: "Justice League",
people: ["Batman", "..."],
logMember() {
// arrows have the same context (this) of their surrounding code.
this.people.forEach(p => console.log(p + " is member of the " + this.n));
}
}
team.logMember(); // Batman is member of the Justice League
Class sugar
ES6 classes are a simple sugar over the prototype-based OO pattern.
class Animal {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
var pet = new Animal("foo");
pet instanceof Animal // true
pet.getName(); // foo
Fish.canSwim(); // true
var fish = new Fish("nemo");
fish instanceof Animal; // true
fish instanceof Fish; // true
fish.getName(); // nemo, the fish.
class Fish extends Animal {
constructor(name){
// execute Animal's constructor
super(name);
this.domain = "water";
}
getName() {
return super.getName() + ", the fish.";
}
static canSwim() {
return true;
}
}
Modules
A standard module system for JavaScript.
// utils.js
export function decode(str) { /*...*/ }
export function encode(str) { /*...*/ }
// main.js
import * as helper from 'utils';
utils.encode("foo");
Template Strings
A decent string interpolation feature.
// welcome template string
var str = `<p class="${cssClass}">${content}</p>`;
// backtick is ALT+96
// progressive enhancement -_-
var cssClass = "visible";
var content = "Hello, world!";
// old
var str = "<p class='"+cssClass+"'>"+content+"</p>";
JavaScript has not private object property.
ECMAScript 6 proposal:
Object can have non-string property.
* At the end, the requisite of privateness for Symbol properties was dropped.
Symbolic properties are just non-enumerable.
A new primitive type was created for this purpose, Symbol.
Symbols
A new primitive type.
var s = Symbol(); // Symbol()
typeof s === "symbol" // true
var s1 = Symbol("s1");
var s2 = Symbol("s1");
s1 === s2 // false
For ... Of is a new loop construct.
It allows to loop over the values of an Iterable collection.
A collection is Iterable if has a Symbol property Symbol.iterator
that returns an Iterator.
An Iterator is an object with a next method
that returns a { done, value } tuple.
Iterators & For ... Of loop
For ... Of loop over values of an iterable collection.
var collection = ["a", "b", "c", "d", "e", "f", "g"];
for(value of collection){
console.log(value);
}
// "a", "b", "c", "d", "e", "f", "g"
// custom iteration
collection[Symbol.iterator] = function() {
var index = 0;
return {
next: () => {
if (index < this.length) {
let obj = { done: false, value: this[index] };
index = index + 2;
return obj;
} else {
return { done: true };
}
}
}
}
for(value of collection){ console.log(value); }
// "a", "c", "e", "g"
Generator Functions
Are functions which can be interrupted, and then resumed, used to create Iterators.
The yield operator is used to interrupt the execution.
The generator execution resumes when the iterator’s next method is called.
collection[Symbol.iterator] = function* () {
for (let i=0; i<this.length; i++) {
if (i%2 === 0) yield this[i];
}
};
for(value of collection){ console.log(value); }
// "a", "c", "e", "g"
Set
An ordered collection with no duplicates.
* Set has a rich prototype that expose method to work with the set instance.
var arr = [1, 2, 2, 3, 3, 3, 4];
var set = new Set(arr);
set; // Set {1, 2, 3, 4}
Map
An ordered collection of {key, value} tuples, without duplicated keys.
* Map has a rich prototype that expose method to work with the map instance.
var arr = [ [1, "first"], [1, "one"], [2, "two"] ];
var map = new Map(arr);
map; // Map { 1: "one", 2: "two" }
Proxies
Allows to intercept, and re-implement, operations executed over an object.
var obj = { v: 42 };
var traps = {
set(target, propKey, value, receiver) {
console.log('SET '+propKey+'='+value);
target[propKey] = value;
}
};
var proxy = new Proxy(obj, traps);
proxy.v = 0;
// SET v=0
Promises
Execute asynchronous code like if it’s synchronous
function getJSON() {
return new Promise(function(resolve, reject) {
setTimeout(function() { resolve('{"value": 42}'); }, 500);
});
}
getJSON().then(function(resp) {
console.log("success", resp);
});
Reflection
Reflect is a built-in object that provides methods for interceptable JavaScript operations
var obj = { v: 42 };
var proxy = new Proxy(obj, {
set(target, propKey, value, receiver) {
console.log('SET '+propKey+'='+value);
Reflect.set(target, propKey, value, receiver);
}
});
Did you like this?
... what about the browser support?
//kangax.github.io/compat-table/es6/
2015:
This is no more a problem!
var team = {
name: "Justice League",
members: [
{ name: "Batman", gender: "M" },
{ name: "Wonder woman", gender: "F" }
],
add(...members) {
this.members.push(...members)
},
remove(name) {
let memberIndex = this.members.findIndex(x => x.name
=== name);
if (memberIndex >= 0){
this.members.splice(memberIndex, 1);
}
},
log(gender = "M") {
this.members
.filter(x => x.gender === gender)
.forEach(h => console.log(`${h.name} is member of the
${this.name}`)); }
}
team.add({ name: "Gipsy", gender: "F" });
team.add({ name: "Flash", gender: "M" }, { name: "Green
Lantern", gender: "M" });
team.remove("Batman")
team.log("M");
team.log("F");
var team = {
name: "Justice League",
members: [
{ name: "Batman", gender: "M" },
{ name: "Wonder woman", gender: "F" }
],
add: function add() {
var _members, _len = arguments.length;
for (var members = _len, _key = 0; _key < _len; _key++){
members[_key] = arguments[_key];
}
(_members = this.members).push.apply(_members, members);
},
remove: function remove(name) {
var memberIndex = this.members.findIndex(function (x){
return x.name === name;
});
if (memberIndex >= 0) {
this.members.splice(memberIndex, 1);
}
},
log: function log() {
var _this = this;
var gender = arguments[0] === undefined ? "M" :
arguments[0];
this.members
.filter(function (x) { return x.gender === gender; })
.forEach(function (h) { return console.log("" + h.name
+ " is member of the " + _this.name); });
}
};
Grazie!

More Related Content

What's hot

EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
Sebastiano Armeli
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
Cory Forsyth
 
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
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
Santosh Wadghule
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
FITC
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
Mastering Kotlin Standard Library
Mastering Kotlin Standard LibraryMastering Kotlin Standard Library
Mastering Kotlin Standard Library
Nelson Glauber Leal
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
Han Lee
 
Advanced python
Advanced pythonAdvanced python
Advanced pythonEU Edge
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
Manoj Kumar
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
hesher
 
Pyimproved again
Pyimproved againPyimproved again
Pyimproved again
rik0
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
Manoj Kumar
 
AST - the only true tool for building JavaScript
AST - the only true tool for building JavaScriptAST - the only true tool for building JavaScript
AST - the only true tool for building JavaScriptIngvar Stepanyan
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
Eugene Zharkov
 
Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and Reactive
Eugene Zharkov
 
Exhibition of Atrocity
Exhibition of AtrocityExhibition of Atrocity
Exhibition of Atrocity
Michael Pirnat
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
Leo Hernandez
 
Aplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e JetpackAplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e Jetpack
Nelson Glauber Leal
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python Tricks
Bryan Helmig
 

What's hot (20)

EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
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
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Mastering Kotlin Standard Library
Mastering Kotlin Standard LibraryMastering Kotlin Standard Library
Mastering Kotlin Standard Library
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
 
Advanced python
Advanced pythonAdvanced python
Advanced python
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
Pyimproved again
Pyimproved againPyimproved again
Pyimproved again
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
AST - the only true tool for building JavaScript
AST - the only true tool for building JavaScriptAST - the only true tool for building JavaScript
AST - the only true tool for building JavaScript
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and Reactive
 
Exhibition of Atrocity
Exhibition of AtrocityExhibition of Atrocity
Exhibition of Atrocity
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
Aplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e JetpackAplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e Jetpack
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python Tricks
 

Viewers also liked

Primero 2015-cambridge-house-final v001-f69ux4
Primero 2015-cambridge-house-final v001-f69ux4Primero 2015-cambridge-house-final v001-f69ux4
Primero 2015-cambridge-house-final v001-f69ux4
primero_mining
 
Mauro powerrrr
Mauro powerrrrMauro powerrrr
Mauro powerrrr
Skaterooo
 
English presentation!!!
English presentation!!!English presentation!!!
English presentation!!!carlagrizi
 
Počátky anglického působení v severní americe
Počátky anglického působení v severní americePočátky anglického působení v severní americe
Počátky anglického působení v severní americedsmrz
 
Crawl, Walk, Run - Evolve Your Project Management in 2015!
Crawl, Walk, Run - Evolve Your Project Management in 2015!Crawl, Walk, Run - Evolve Your Project Management in 2015!
Crawl, Walk, Run - Evolve Your Project Management in 2015!
BrightWork
 
Primero Corporate Presentation December 2014
Primero Corporate Presentation December 2014Primero Corporate Presentation December 2014
Primero Corporate Presentation December 2014
primero_mining
 
Tugas kimia dasar 2 pengertian ikatan kimia
Tugas kimia dasar 2 pengertian ikatan kimiaTugas kimia dasar 2 pengertian ikatan kimia
Tugas kimia dasar 2 pengertian ikatan kimiaSylvester Saragih
 
Poinsettia & Red Box - The Office Party
Poinsettia & Red Box - The Office PartyPoinsettia & Red Box - The Office Party
Poinsettia & Red Box - The Office Party
hbwmike
 
Primero november corporate presentation v2
Primero november corporate presentation v2Primero november corporate presentation v2
Primero november corporate presentation v2primero_mining
 
Presupuesto de un Servidor de una empresa
Presupuesto de un Servidor de una empresaPresupuesto de un Servidor de una empresa
Presupuesto de un Servidor de una empresa
Alfredo Aguayo
 
Resume_Vasin Lerdmongkon_20170119
Resume_Vasin Lerdmongkon_20170119Resume_Vasin Lerdmongkon_20170119
Resume_Vasin Lerdmongkon_20170119Horn Le
 
Picnic Time
Picnic TimePicnic Time
Picnic Time
hbwmike
 
10remarkableentrepreneurshipthoughts 131008125313-phpapp01
10remarkableentrepreneurshipthoughts 131008125313-phpapp0110remarkableentrepreneurshipthoughts 131008125313-phpapp01
10remarkableentrepreneurshipthoughts 131008125313-phpapp01Gina Gu
 
36kr no.94
36kr no.9436kr no.94
36kr no.94Gina Gu
 
задачи управления академическими знаниями
задачи управления академическими знаниямизадачи управления академическими знаниями
задачи управления академическими знаниямиArmen Bagdasaryan
 
Warm up and warm down22
Warm up and warm down22Warm up and warm down22
Warm up and warm down22nmcquade
 
ndep.org - A WordPress Case Study
ndep.org - A WordPress Case Studyndep.org - A WordPress Case Study
ndep.org - A WordPress Case Studykeithdevon
 
Tecnología del té
Tecnología del téTecnología del té
Tecnología del té
Abner Terrones
 
PMSight References
PMSight ReferencesPMSight References
PMSight ReferencesPaul Viviers
 

Viewers also liked (20)

Primero 2015-cambridge-house-final v001-f69ux4
Primero 2015-cambridge-house-final v001-f69ux4Primero 2015-cambridge-house-final v001-f69ux4
Primero 2015-cambridge-house-final v001-f69ux4
 
Mauro powerrrr
Mauro powerrrrMauro powerrrr
Mauro powerrrr
 
English presentation!!!
English presentation!!!English presentation!!!
English presentation!!!
 
Počátky anglického působení v severní americe
Počátky anglického působení v severní americePočátky anglického působení v severní americe
Počátky anglického působení v severní americe
 
Crawl, Walk, Run - Evolve Your Project Management in 2015!
Crawl, Walk, Run - Evolve Your Project Management in 2015!Crawl, Walk, Run - Evolve Your Project Management in 2015!
Crawl, Walk, Run - Evolve Your Project Management in 2015!
 
Primero Corporate Presentation December 2014
Primero Corporate Presentation December 2014Primero Corporate Presentation December 2014
Primero Corporate Presentation December 2014
 
Tugas kimia dasar 2 pengertian ikatan kimia
Tugas kimia dasar 2 pengertian ikatan kimiaTugas kimia dasar 2 pengertian ikatan kimia
Tugas kimia dasar 2 pengertian ikatan kimia
 
Poinsettia & Red Box - The Office Party
Poinsettia & Red Box - The Office PartyPoinsettia & Red Box - The Office Party
Poinsettia & Red Box - The Office Party
 
Primero november corporate presentation v2
Primero november corporate presentation v2Primero november corporate presentation v2
Primero november corporate presentation v2
 
Presupuesto de un Servidor de una empresa
Presupuesto de un Servidor de una empresaPresupuesto de un Servidor de una empresa
Presupuesto de un Servidor de una empresa
 
Resume_Vasin Lerdmongkon_20170119
Resume_Vasin Lerdmongkon_20170119Resume_Vasin Lerdmongkon_20170119
Resume_Vasin Lerdmongkon_20170119
 
Picnic Time
Picnic TimePicnic Time
Picnic Time
 
10remarkableentrepreneurshipthoughts 131008125313-phpapp01
10remarkableentrepreneurshipthoughts 131008125313-phpapp0110remarkableentrepreneurshipthoughts 131008125313-phpapp01
10remarkableentrepreneurshipthoughts 131008125313-phpapp01
 
Metallurgi 2
Metallurgi 2Metallurgi 2
Metallurgi 2
 
36kr no.94
36kr no.9436kr no.94
36kr no.94
 
задачи управления академическими знаниями
задачи управления академическими знаниямизадачи управления академическими знаниями
задачи управления академическими знаниями
 
Warm up and warm down22
Warm up and warm down22Warm up and warm down22
Warm up and warm down22
 
ndep.org - A WordPress Case Study
ndep.org - A WordPress Case Studyndep.org - A WordPress Case Study
ndep.org - A WordPress Case Study
 
Tecnología del té
Tecnología del téTecnología del té
Tecnología del té
 
PMSight References
PMSight ReferencesPMSight References
PMSight References
 

Similar to ES6 Overview

TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
Javascript
JavascriptJavascript
Javascript
Vlad Ifrim
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
Luis Vendrame
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
kvangork
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
kvangork
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
Adam L Barrett
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
Visual Engineering
 
ECMAScript 6 Review
ECMAScript 6 ReviewECMAScript 6 Review
ECMAScript 6 Review
Sperasoft
 
Internal workshop es6_2015
Internal workshop es6_2015Internal workshop es6_2015
Internal workshop es6_2015
Miguel Ruiz Rodriguez
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
Eduard Tomàs
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
Michael Girouard
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wild
Joe Morgan
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
msemenistyi
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 SpringKiyotaka Oku
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说Ting Lv
 
ES6, WTF?
ES6, WTF?ES6, WTF?
ES6, WTF?
James Ford
 
Groovy
GroovyGroovy
Groovy
Zen Urban
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
cacois
 

Similar to ES6 Overview (20)

TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
ECMAScript 6 Review
ECMAScript 6 ReviewECMAScript 6 Review
ECMAScript 6 Review
 
Internal workshop es6_2015
Internal workshop es6_2015Internal workshop es6_2015
Internal workshop es6_2015
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wild
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
 
ES6, WTF?
ES6, WTF?ES6, WTF?
ES6, WTF?
 
Groovy
GroovyGroovy
Groovy
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 

Recently uploaded

GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 

Recently uploaded (20)

GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 

ES6 Overview

  • 1. import * as $ from 'jQuery'; import svg from 'svglib'; import Chart from 'Chart'; class LineChart extends Chart { constructor(series, canvas = document.body){ super(series, canvas); this.draw(); } draw() { var plot = svg.buildLineChart(this.series); this.$canvas.append(plot); this.series.forEach(x => { var { max, average: avg } = LineChart.getSerieData(x); super.addStats(max, avg); }); } static getSerieData(serie) { if (serie.length > 0){ let sum = serie.reduce((x, y) => x+y); return { max: Math.max(...series), average: sum/serie.length }; } return null; } } export default LineChart;
  • 3. in the browser and on the server, too in a not too far future …
  • 4.
  • 5. Object Literals Shorthand It’s just syntactic sugar for Object literals. var v = 42, propertyName = "count"; function fn() { console.log(v); }; // the old way var obj = { v: v, fn: fn, fn2: function() { /*...*/ } }; obj[propertyName] = 10; // es6 shorthand O/ var obj = { v, fn, fn2() { /*...*/ }, [propertyName]: 10 }
  • 6. Destructuring Allows to extract values from object and array using patterns. // ... and support default values var [name, extension = ""] = "LICENSE".split("."); console.log(extension) // "" // it works with array too! var [name, extension] = "me.jpeg".split("."); console.log(extension); // jpeg // destructuring + object literal shorthand var { v, fn } = obj; console.log(v); // 42 var { v: value, fn: log } = obj; console.log(value); // 42
  • 7. Rest & Spread Operator The Spread operator turns an array into consecutive arguments in a function call. The Rest operator binds trailing parameters to an array. var arr = [1, 2]; arr.concat([3, 4]); // [1, 2, [3, 4]] FAIL! ಥ_ಥ [3, 4].forEach(function(x) { arr.push(x) }); // [1, 2, 3, 4] At least it works ¯_(ツ)_/¯ // spread to the rescue! arr.concat(...[3, 4]); // [1, 2, 3, 4] 0/ // rest var [winner, ...theOthers] = ["a", "b", "c"]; console.log(theOthers instanceof Array); // true console.log(theOthers.length); // 2
  • 8. Super-powered functions Varargs and default parameters. // default value for function’s arguments repeat("yo"); // yoyo function repeat(msg, time = 2) { return msg.repeat(time); } // rest parameters function resize(width, height, ...elems){ console.log(elems); } resize(100, 100, "#box", "#photo"); // ["#box", "#photo"] function fn(...args){ console.log(args); } fn(); // [] fn(42, "bho!"); // [42, "bho!"]
  • 9. Block Scoped variables Block scoped variable assignments with let and const. > Organized code! if(true){ let v = 42; } console.log(v); // ReferenceError: v is not defined // constants const pi = 3.14156; pi = 3.14; // SyntaxError: invalid assignment to const pi
  • 10. Arrow Functions Function shorthand with arrow syntax, and more… [1,2,3].reduce(function(a, b) { return a+b; }); // the syntax [1,2,3].reduce((a,b) => { console.log("oO"); return a+b; }); // 6 // and even shorter [1,2,3].reduce((a,b) => a+b);
  • 11. Arrow Functions … arrow functions share the same context with their surrounding code; the context can’t be modified via call, apply nor bind. var team = { n: "Justice League", people: ["Batman", "..."], logMember() { // arrows have the same context (this) of their surrounding code. this.people.forEach(p => console.log(p + " is member of the " + this.n)); } } team.logMember(); // Batman is member of the Justice League
  • 12. Class sugar ES6 classes are a simple sugar over the prototype-based OO pattern. class Animal { constructor(name) { this.name = name; } getName() { return this.name; } } var pet = new Animal("foo"); pet instanceof Animal // true pet.getName(); // foo
  • 13. Fish.canSwim(); // true var fish = new Fish("nemo"); fish instanceof Animal; // true fish instanceof Fish; // true fish.getName(); // nemo, the fish. class Fish extends Animal { constructor(name){ // execute Animal's constructor super(name); this.domain = "water"; } getName() { return super.getName() + ", the fish."; } static canSwim() { return true; } }
  • 14. Modules A standard module system for JavaScript. // utils.js export function decode(str) { /*...*/ } export function encode(str) { /*...*/ } // main.js import * as helper from 'utils'; utils.encode("foo");
  • 15. Template Strings A decent string interpolation feature. // welcome template string var str = `<p class="${cssClass}">${content}</p>`; // backtick is ALT+96 // progressive enhancement -_- var cssClass = "visible"; var content = "Hello, world!"; // old var str = "<p class='"+cssClass+"'>"+content+"</p>";
  • 16. JavaScript has not private object property. ECMAScript 6 proposal: Object can have non-string property. * At the end, the requisite of privateness for Symbol properties was dropped. Symbolic properties are just non-enumerable. A new primitive type was created for this purpose, Symbol.
  • 17. Symbols A new primitive type. var s = Symbol(); // Symbol() typeof s === "symbol" // true var s1 = Symbol("s1"); var s2 = Symbol("s1"); s1 === s2 // false
  • 18. For ... Of is a new loop construct. It allows to loop over the values of an Iterable collection. A collection is Iterable if has a Symbol property Symbol.iterator that returns an Iterator. An Iterator is an object with a next method that returns a { done, value } tuple.
  • 19. Iterators & For ... Of loop For ... Of loop over values of an iterable collection. var collection = ["a", "b", "c", "d", "e", "f", "g"]; for(value of collection){ console.log(value); } // "a", "b", "c", "d", "e", "f", "g"
  • 20. // custom iteration collection[Symbol.iterator] = function() { var index = 0; return { next: () => { if (index < this.length) { let obj = { done: false, value: this[index] }; index = index + 2; return obj; } else { return { done: true }; } } } } for(value of collection){ console.log(value); } // "a", "c", "e", "g"
  • 21. Generator Functions Are functions which can be interrupted, and then resumed, used to create Iterators. The yield operator is used to interrupt the execution. The generator execution resumes when the iterator’s next method is called. collection[Symbol.iterator] = function* () { for (let i=0; i<this.length; i++) { if (i%2 === 0) yield this[i]; } }; for(value of collection){ console.log(value); } // "a", "c", "e", "g"
  • 22. Set An ordered collection with no duplicates. * Set has a rich prototype that expose method to work with the set instance. var arr = [1, 2, 2, 3, 3, 3, 4]; var set = new Set(arr); set; // Set {1, 2, 3, 4}
  • 23. Map An ordered collection of {key, value} tuples, without duplicated keys. * Map has a rich prototype that expose method to work with the map instance. var arr = [ [1, "first"], [1, "one"], [2, "two"] ]; var map = new Map(arr); map; // Map { 1: "one", 2: "two" }
  • 24. Proxies Allows to intercept, and re-implement, operations executed over an object. var obj = { v: 42 }; var traps = { set(target, propKey, value, receiver) { console.log('SET '+propKey+'='+value); target[propKey] = value; } }; var proxy = new Proxy(obj, traps); proxy.v = 0; // SET v=0
  • 25. Promises Execute asynchronous code like if it’s synchronous function getJSON() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve('{"value": 42}'); }, 500); }); } getJSON().then(function(resp) { console.log("success", resp); });
  • 26. Reflection Reflect is a built-in object that provides methods for interceptable JavaScript operations var obj = { v: 42 }; var proxy = new Proxy(obj, { set(target, propKey, value, receiver) { console.log('SET '+propKey+'='+value); Reflect.set(target, propKey, value, receiver); } });
  • 27. Did you like this?
  • 28.
  • 29. ... what about the browser support? //kangax.github.io/compat-table/es6/
  • 30.
  • 31.
  • 32. 2015: This is no more a problem!
  • 33.
  • 34. var team = { name: "Justice League", members: [ { name: "Batman", gender: "M" }, { name: "Wonder woman", gender: "F" } ], add(...members) { this.members.push(...members) }, remove(name) { let memberIndex = this.members.findIndex(x => x.name === name); if (memberIndex >= 0){ this.members.splice(memberIndex, 1); } }, log(gender = "M") { this.members .filter(x => x.gender === gender) .forEach(h => console.log(`${h.name} is member of the ${this.name}`)); } } team.add({ name: "Gipsy", gender: "F" }); team.add({ name: "Flash", gender: "M" }, { name: "Green Lantern", gender: "M" }); team.remove("Batman") team.log("M"); team.log("F"); var team = { name: "Justice League", members: [ { name: "Batman", gender: "M" }, { name: "Wonder woman", gender: "F" } ], add: function add() { var _members, _len = arguments.length; for (var members = _len, _key = 0; _key < _len; _key++){ members[_key] = arguments[_key]; } (_members = this.members).push.apply(_members, members); }, remove: function remove(name) { var memberIndex = this.members.findIndex(function (x){ return x.name === name; }); if (memberIndex >= 0) { this.members.splice(memberIndex, 1); } }, log: function log() { var _this = this; var gender = arguments[0] === undefined ? "M" : arguments[0]; this.members .filter(function (x) { return x.gender === gender; }) .forEach(function (h) { return console.log("" + h.name + " is member of the " + _this.name); }); } };
  • 35.