SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Downloaden Sie, um offline zu lesen
LEVEL UP YOUR SKILLS
ES6
by Stefano Ceschi BerriniProgrammers In Padua - Nov, 21st 2016
WHO AM I?
Stefano Ceschi Berrini
Software Engineer @ TimeRepublik
~9 yrs relationship w/ JS
In <3 with React
@stecb https://stecb.github.io
Yes. Software Engineer.
I was joking. This is what I actually do
1995/‘96 2006 2009 2015
Nov 21th, 2016
A high-level, dynamic, untyped, and interpreted programming language
dʒævəˌskrɪpt
ES6 is JavaScript
adds to JS a tons of cool features you will love
CONSTANTS &
VARIABLES
// scopes the variable to the nearest **block** {}
// No hoisting
let foo = 'bar';
for (let i = 0; i < 10; i++) {
let y = 'something';
}
// while foo is available, both i and y are not available
console.log(y)
// ReferenceError: y is not defined
// constant reference to the value, we shouldn't redefine it!
// And MUST be initialised. Same scoping rules of let
const pi = 3.14;
const arr = [];
const obj = {};
// we can change referenced value in this case
arr.push('hey');
// but we can't redefine constants i.e.
// arr = []
// or
// pi = 5
obj.str = 'foo';
// also ok!
obj = {};
// ! ok!
STRING
INTERPOLATION
const god = {
name: 'John Petrucci',
instrument: 'guitar',
influences: ['Pink Floyd', 'Metallica', 'Iron Maiden', 'Meshuggah']
};
const domNode =`
<div>
<em>
<b>${god.name}</b> can play ${god.instrument} faster than you!!
</em>
<p>Influences:</p>
<ul>
${god.influences.map(i => `<li>${i}</li>`).join('')}
</ul>
</div>
`;
document.body.innerHTML = domNode;
ARROW
FUNCTIONS
let arr = [1,2,3];
let something = arr.map(n => n * 2).reduce((a, b) => a + b);
let foo = () => () => console.log('heya!');
console.log(something); // ?
console.log(foo()); // ?
let guitars = ['music man', 'ibanez', 'taylor'];
let guitarsShop = {
location: 'Montebelluna',
name: 'EsseMusic',
// shorthand assignment => guitars: guitars
guitars,
// method
listGuitars() {
this.guitars.forEach(guitar => {
console.log(`${this.name} in ${this.location} has ${guitar} guitars`);
});
}
}
guitarsShop.listGuitars(); // ?
OBJECT PROPERTIES
ENHANCEMENTS
let guitars = ['music man', 'ibanez', 'taylor'];
let guitarsShop = {
location: 'Montebelluna',
name: 'EsseMusic',
// shorthand assignment => guitars: guitars
guitars,
// computed properties
[`property_${guitars[1]}`]: guitars[1],
// method
listGuitars() {
this.guitars.forEach(guitar => {
console.log(`${this.name} in ${this.location}
has ${guitar} guitars`);
});
}
}
console.log( guitarsShop[`property_${guitars[1]}`] === guitars[1] );
PARAMETERS
HANDLING
// default params values
const foo = (x, y = 1, z = 2) => x * y * z;
foo(3); // ?
// rest params
const bar = (x, y, ...z) => x * y * z.length;
bar(1, 2, 'some', 'more', 'args'); // ?
// spread syntax
const baz = (x, y, z) => x * y * z;
const arr = [2, 4, 6];
baz(...arr); // ?
DESTRUCTURING
const arr = [1, 2, 3, 4, 5];
const [a, b, ...other] = arr;
console.log(other) // ?
const obj = { x: 1, y: 2 };
const { x, y } = obj;
console.log(x, y); // 1 2
const obj2 = { options: { top: 10, left: 20, bg: '#fff' } };
// destructuring + aliasing
const { options: { bg: background } } = obj2;
console.log(background); // '#fff'
const foo = () => [1, 2, 3];
const [c, ,d] = foo();
console.log(c, d); // 1 3
function draw({ size = 'big', coords = { x: 0, y: 0 } } = {}) {
console.log(size, coords);
}
draw({
coords: { x: 18, y: 30 }
});
CLASSES
// class
class Person {
// default params
constructor(name = 'unknown', age = 0, sex = 'whatever') {
this.age = age;
this.name = name;
this.sex = sex;
}
displayInfo() {
console.log(this.name, this.age, this.sex);
}
}
// subclass
class Female extends Person {
constructor(name, age) {
// super call
super(name, age, 'f');
}
yell(what) {
super.displayInfo();
setInterval(() => console.log(what), 1000);
}
}
const myWife = new Female('Deborah', 29);
myWife.yell('wash your own cup and dishes please!');
MODULES
js
helpers.js
constants.js
app.js
moviesManager.js
// /js/helpers.js
export function isOdd(n) {
return n % 2 !== 0;
}
export const capitalizeFirst = str => str[0].toUpperCase() + str.slice(1);
// /js/constants.js
export const API_ENDPOINT = 'http://my.api.com/';
export const PER_PAGE = 30;
export const MAGIC = 42;
// /js/moviesManager.js
import { API_ENDPOINT, PER_PAGE, MAGIC } from 'constants';
export default class MoviesManager {
constructor(per_page = PER_PAGE) {
this.page = 0;
this.per_page = per_page;
}
fetch(title, cb) {
fetch(`${API_ENDPOINT}?title=${title}&page=${this.page++}
&per_page=${this.per_page}&API_KEY=${MAGIC}`)
.then(response => response.json())
.then(json => cb(json));
}
}
// /js/app.js
import * as lib from 'helpers';
import MoviesManager from 'moviesManager';
const arr = [1, 2, 3, 4, 5];
const oddArr = arr.filter(lib.isOdd);
(new MoviesManager).fetch('spider man', json => {
// I will receive the json
// of all the people who bought spider man.
console.log(lib.capitalizeFirst(json.people[0].firstName));
});
GENERATORS
Generators are new kind of functions that can be
paused/resumed, allowing meanwhile other code to run.
const fetchJson = co.wrap(function* (url) {
try {
let request = yield fetch(url);
let text = yield request.text();
return JSON.parse(text);
}
catch (error) {
console.log(`ERROR: ${error.stack}`);
}
});
function* generatorFunction() {
// paused initally!
console.log('Hey');
yield; // operator to pause the generator!
console.log('there!');
}
const generatorObj = generatorFunction();
generatorObj.next(); // Hey
generatorObj.next(); // there!
// at the end: { value: undefined, done: true }
function *foo(x) {
let y = 2 * (yield (x + 1));
let z = yield (y / 3);
return (x + y + z);
}
const iterator = foo(1);
iterator.next(); // => value === ?, done === ?
iterator.next(3); // => value === ?, done === ?
iterator.next(12); // => value === ?, done === ?
// function declaration
function* generatorFunction() { /* code */ }
// function expression
const generatorFunction = function* () { /* code */ }
// generator method
const obj = {
* myMethod() {
/* code */
}
}
// generator method def in class
class MyClass {
* myMethod() {
/* code */
}
}
RESOURCES
https://github.com/lukehoban/es6features
https://babeljs.io/docs/learn-es2015/
http://exploringjs.com/es6/
Thanks.
Images taken from https://unsplash.com/

Weitere ähnliche Inhalte

Was ist angesagt?

Test driven game development silly, stupid or inspired?
Test driven game development   silly, stupid or inspired?Test driven game development   silly, stupid or inspired?
Test driven game development silly, stupid or inspired?
Eric Smith
 
Beware: Sharp Tools
Beware: Sharp ToolsBeware: Sharp Tools
Beware: Sharp Tools
chrismdp
 
completion_proc and history
completion_proc and historycompletion_proc and history
completion_proc and history
Nobuhiro IMAI
 
Nomethoderror talk
Nomethoderror talkNomethoderror talk
Nomethoderror talk
Jan Berdajs
 

Was ist angesagt? (20)

PHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP LimogesPHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP Limoges
 
Simulator customizing & testing for Xcode 9
Simulator customizing & testing for Xcode 9Simulator customizing & testing for Xcode 9
Simulator customizing & testing for Xcode 9
 
Beware sharp tools
Beware sharp toolsBeware sharp tools
Beware sharp tools
 
Test driven game development silly, stupid or inspired?
Test driven game development   silly, stupid or inspired?Test driven game development   silly, stupid or inspired?
Test driven game development silly, stupid or inspired?
 
The hidden and new parts of JS
The hidden and new parts of JSThe hidden and new parts of JS
The hidden and new parts of JS
 
ES6: The future is now
ES6: The future is nowES6: The future is now
ES6: The future is now
 
Starting out with Ember.js
Starting out with Ember.jsStarting out with Ember.js
Starting out with Ember.js
 
Yahoo! JAPANとKotlin
Yahoo! JAPANとKotlinYahoo! JAPANとKotlin
Yahoo! JAPANとKotlin
 
Beware: Sharp Tools
Beware: Sharp ToolsBeware: Sharp Tools
Beware: Sharp Tools
 
completion_proc and history
completion_proc and historycompletion_proc and history
completion_proc and history
 
システムコールトレーサーの動作原理と実装 (Writing system call tracer for Linux/x86)
システムコールトレーサーの動作原理と実装 (Writing system call tracer for Linux/x86)システムコールトレーサーの動作原理と実装 (Writing system call tracer for Linux/x86)
システムコールトレーサーの動作原理と実装 (Writing system call tracer for Linux/x86)
 
The Art of Command Line (2021)
The Art of Command Line (2021)The Art of Command Line (2021)
The Art of Command Line (2021)
 
Nomethoderror talk
Nomethoderror talkNomethoderror talk
Nomethoderror talk
 
Bologna Developer Zone - About Kotlin
Bologna Developer Zone - About KotlinBologna Developer Zone - About Kotlin
Bologna Developer Zone - About Kotlin
 
De 0 a 100 con Bash Shell Scripting y AWK
De 0 a 100 con Bash Shell Scripting y AWKDe 0 a 100 con Bash Shell Scripting y AWK
De 0 a 100 con Bash Shell Scripting y AWK
 
Java&Script
Java&ScriptJava&Script
Java&Script
 
Xstartup
XstartupXstartup
Xstartup
 
Scroll pHAT HD に美咲フォント
Scroll pHAT HD に美咲フォントScroll pHAT HD に美咲フォント
Scroll pHAT HD に美咲フォント
 
C to perl binding
C to perl bindingC to perl binding
C to perl binding
 
Should I Use CoffeeScript? The Pros and Cons of Working With JavaScript’s Ori...
Should I Use CoffeeScript? The Pros and Cons of Working With JavaScript’s Ori...Should I Use CoffeeScript? The Pros and Cons of Working With JavaScript’s Ori...
Should I Use CoffeeScript? The Pros and Cons of Working With JavaScript’s Ori...
 

Andere mochten auch (6)

[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 1. primitive
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 1. primitive[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 1. primitive
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 1. primitive
 
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 2. functions
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 2. functions[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 2. functions
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 2. functions
 
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 3. generator
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 3. generator[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 3. generator
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 3. generator
 
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 4. promise
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 4. promise[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 4. promise
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 4. promise
 
Int64
Int64Int64
Int64
 
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra  SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
 

Ähnlich wie ES6 - Level up your JavaScript Skills

ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015
qmmr
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
Solution4Future
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan Stefanov
 

Ähnlich wie ES6 - Level up your JavaScript Skills (20)

Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
Groovy
GroovyGroovy
Groovy
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
 
Javascript
JavascriptJavascript
Javascript
 
ECMAScript 6 Review
ECMAScript 6 ReviewECMAScript 6 Review
ECMAScript 6 Review
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
 
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
 
Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.js
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
Sbaw091006
Sbaw091006Sbaw091006
Sbaw091006
 
JavaScript Futures—ES2017 and Beyond
JavaScript Futures—ES2017 and BeyondJavaScript Futures—ES2017 and Beyond
JavaScript Futures—ES2017 and Beyond
 

Kürzlich hochgeladen

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Kürzlich hochgeladen (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

ES6 - Level up your JavaScript Skills

  • 1. LEVEL UP YOUR SKILLS ES6 by Stefano Ceschi BerriniProgrammers In Padua - Nov, 21st 2016
  • 2. WHO AM I? Stefano Ceschi Berrini Software Engineer @ TimeRepublik ~9 yrs relationship w/ JS In <3 with React @stecb https://stecb.github.io
  • 4. I was joking. This is what I actually do
  • 7. A high-level, dynamic, untyped, and interpreted programming language dʒævəˌskrɪpt
  • 8. ES6 is JavaScript adds to JS a tons of cool features you will love
  • 10. // scopes the variable to the nearest **block** {} // No hoisting let foo = 'bar'; for (let i = 0; i < 10; i++) { let y = 'something'; } // while foo is available, both i and y are not available console.log(y) // ReferenceError: y is not defined
  • 11. // constant reference to the value, we shouldn't redefine it! // And MUST be initialised. Same scoping rules of let const pi = 3.14; const arr = []; const obj = {}; // we can change referenced value in this case arr.push('hey'); // but we can't redefine constants i.e. // arr = [] // or // pi = 5 obj.str = 'foo'; // also ok! obj = {}; // ! ok!
  • 13. const god = { name: 'John Petrucci', instrument: 'guitar', influences: ['Pink Floyd', 'Metallica', 'Iron Maiden', 'Meshuggah'] }; const domNode =` <div> <em> <b>${god.name}</b> can play ${god.instrument} faster than you!! </em> <p>Influences:</p> <ul> ${god.influences.map(i => `<li>${i}</li>`).join('')} </ul> </div> `; document.body.innerHTML = domNode;
  • 15. let arr = [1,2,3]; let something = arr.map(n => n * 2).reduce((a, b) => a + b); let foo = () => () => console.log('heya!'); console.log(something); // ? console.log(foo()); // ?
  • 16. let guitars = ['music man', 'ibanez', 'taylor']; let guitarsShop = { location: 'Montebelluna', name: 'EsseMusic', // shorthand assignment => guitars: guitars guitars, // method listGuitars() { this.guitars.forEach(guitar => { console.log(`${this.name} in ${this.location} has ${guitar} guitars`); }); } } guitarsShop.listGuitars(); // ?
  • 18. let guitars = ['music man', 'ibanez', 'taylor']; let guitarsShop = { location: 'Montebelluna', name: 'EsseMusic', // shorthand assignment => guitars: guitars guitars, // computed properties [`property_${guitars[1]}`]: guitars[1], // method listGuitars() { this.guitars.forEach(guitar => { console.log(`${this.name} in ${this.location} has ${guitar} guitars`); }); } } console.log( guitarsShop[`property_${guitars[1]}`] === guitars[1] );
  • 20. // default params values const foo = (x, y = 1, z = 2) => x * y * z; foo(3); // ? // rest params const bar = (x, y, ...z) => x * y * z.length; bar(1, 2, 'some', 'more', 'args'); // ? // spread syntax const baz = (x, y, z) => x * y * z; const arr = [2, 4, 6]; baz(...arr); // ?
  • 22. const arr = [1, 2, 3, 4, 5]; const [a, b, ...other] = arr; console.log(other) // ? const obj = { x: 1, y: 2 }; const { x, y } = obj; console.log(x, y); // 1 2 const obj2 = { options: { top: 10, left: 20, bg: '#fff' } }; // destructuring + aliasing const { options: { bg: background } } = obj2; console.log(background); // '#fff' const foo = () => [1, 2, 3]; const [c, ,d] = foo(); console.log(c, d); // 1 3 function draw({ size = 'big', coords = { x: 0, y: 0 } } = {}) { console.log(size, coords); } draw({ coords: { x: 18, y: 30 } });
  • 24. // class class Person { // default params constructor(name = 'unknown', age = 0, sex = 'whatever') { this.age = age; this.name = name; this.sex = sex; } displayInfo() { console.log(this.name, this.age, this.sex); } } // subclass class Female extends Person { constructor(name, age) { // super call super(name, age, 'f'); } yell(what) { super.displayInfo(); setInterval(() => console.log(what), 1000); } } const myWife = new Female('Deborah', 29); myWife.yell('wash your own cup and dishes please!');
  • 27. // /js/helpers.js export function isOdd(n) { return n % 2 !== 0; } export const capitalizeFirst = str => str[0].toUpperCase() + str.slice(1); // /js/constants.js export const API_ENDPOINT = 'http://my.api.com/'; export const PER_PAGE = 30; export const MAGIC = 42;
  • 28. // /js/moviesManager.js import { API_ENDPOINT, PER_PAGE, MAGIC } from 'constants'; export default class MoviesManager { constructor(per_page = PER_PAGE) { this.page = 0; this.per_page = per_page; } fetch(title, cb) { fetch(`${API_ENDPOINT}?title=${title}&page=${this.page++} &per_page=${this.per_page}&API_KEY=${MAGIC}`) .then(response => response.json()) .then(json => cb(json)); } }
  • 29. // /js/app.js import * as lib from 'helpers'; import MoviesManager from 'moviesManager'; const arr = [1, 2, 3, 4, 5]; const oddArr = arr.filter(lib.isOdd); (new MoviesManager).fetch('spider man', json => { // I will receive the json // of all the people who bought spider man. console.log(lib.capitalizeFirst(json.people[0].firstName)); });
  • 31. Generators are new kind of functions that can be paused/resumed, allowing meanwhile other code to run.
  • 32. const fetchJson = co.wrap(function* (url) { try { let request = yield fetch(url); let text = yield request.text(); return JSON.parse(text); } catch (error) { console.log(`ERROR: ${error.stack}`); } });
  • 33. function* generatorFunction() { // paused initally! console.log('Hey'); yield; // operator to pause the generator! console.log('there!'); } const generatorObj = generatorFunction(); generatorObj.next(); // Hey generatorObj.next(); // there! // at the end: { value: undefined, done: true }
  • 34. function *foo(x) { let y = 2 * (yield (x + 1)); let z = yield (y / 3); return (x + y + z); } const iterator = foo(1); iterator.next(); // => value === ?, done === ? iterator.next(3); // => value === ?, done === ? iterator.next(12); // => value === ?, done === ?
  • 35. // function declaration function* generatorFunction() { /* code */ } // function expression const generatorFunction = function* () { /* code */ } // generator method const obj = { * myMethod() { /* code */ } } // generator method def in class class MyClass { * myMethod() { /* code */ } }
  • 37. Thanks. Images taken from https://unsplash.com/