SlideShare a Scribd company logo
1 of 41
Download to read offline
The Awesome Parts
ES6
Domenic Denicola
• http://domenic.me/ (blog)
• https://github.com/domenic
• https://npmjs.org/~domenic
• http://slideshare.net/domenicdenicola
Things I'm doing:
• @esdiscuss onTwitter
• The Promises/A+ spec
• The Extensible Web Manifesto
Why ES6?
“Stagnation on the web is a social ill.”
—Brendan Eich
http://news.ycombinator.com/item?id=4634735
Why JavaScript?
“It is the one language that every vendor is committed to
shipping compatibly. Evolving JS has the leverage to
add/change the semantics of the platform in a way that
no other strategy credibly can.”
—Alex Russell
http://infrequently.org/2013/07/why-javascript/
Why ShouldYou Care?
•It’s not often that, as a programmer, you get
entirely new tools and capabilities in your toolbox.
•Learning Haskell or a Lisp will do it, but then what
do you build?
•ES6 provides a unique opportunity.
The Awesome Parts
•Generators
•Template strings
•Proxies (no time today )
Generators
function zeroOneTwo() {
return [0, 1, 2];
}
var array = zeroOneTwo();
for (var i of array) {
console.log(i);
}
function* zeroOneTwo() {
yield 0;
yield 1;
yield 2;
}
var generator = zeroOneTwo();
for (var i of generator) {
console.log(i);
}
function* zeroOneTwo() {
yield 0;
yield 1;
yield 2;
}
var generator = zeroOneTwo();
for (var i of generator) {
console.log(i);
}
function* zeroOneTwo() {
yield 0;
yield 1;
yield 2;
}
var generator = zeroOneTwo();
generator.next(); // { value: 0, done: false }
generator.next(); // { value: 1, done: false }
generator.next(); // { value: 2, done: false }
generator.next(); // { value: undefined, done: true }
function* fibonacci() {
var previous = 0, current = 1;
while (true) {
var temp = previous;
previous = current;
current = temp + current;
yield current;
}
}
for (var i of fibonacci()) {
console.log(i);
}
// 1, 2, 3, 5, 8, 13, ..., Infinity!
function* take(iterable, numberToTake) {
var i = 0;
for (var taken of iterable) {
if (i++ === numberToTake) {
return;
}
yield taken;
}
}
for (var i of take(fibonacci(), 5)) {
console.log(i);
}
// 1, 2, 3, 5, 8 (and done!)
Lazy sequences
• You can write lazy versions of everything: filter, map, reduce, all those
Underscore.js methods, …
var awesomeEls = filter(domEls, isAwesome);
var awesomeTexts = map(awesomeEls, el => el.textContent);
var awesomeString = reduce(awesomeTexts, (acc, t) => acc + t);
• Since filter and map return generators, nothing happens until reduce, a
non-generator function, executes: then it's all done in a single pass.
• You get the benefits of declarative functional data manipulation without the
performance and memory downsides of intermediate arrays.
Lazy sequences
• You can write lazy versions of everything: filter, map, reduce, all those
Underscore.js methods, …
var awesomeEls = filter(domEls, isAwesome);
var awesomeTexts = map(awesomeEls, el => el.textContent);
var awesomeString = reduce(awesomeTexts, (acc, t) => acc + t);
• Since filter and map return generators, nothing happens until reduce, a
non-generator function, executes: then it's all done in a single pass.
• You get the benefits of declarative functional data manipulation without the
performance and memory downsides of intermediate arrays.
But wait
• Suspending execution until someone calls next() is a powerful feature.
• What if you suspended execution until an async operation finished?
Lots of people are starting to explore this in Node.js right now, leveraging e.g.
promises to turn yield into a kind of “await.”
function* loadUI() {
showLoadingScreen();
yield loadUIDataAsynchronously();
hideLoadingScreen();
}
spawn(loadUI);
This function returns a promise
Write the function spawn so that:
• It calls next() and thus gets the loading promise.
• It waits for the promise to fulfill before calling next() again.
So we've suspended execution until the async operation finishes!
function* loadAndShowData() {
var data = yield loadData();
showData(data);
}
spawn(loadAndShowData);
This function returns a promise for data
You can actually pass data back in to the generator, causing yield to either
return a value or throw an exception inside the generator body.
• So if the promise fulfills, send back its fulfillment value, so that the data
variable ends up holding it.
• But if the promise rejects, tell the generator to throw the rejection
reason as an exception.
function* loadAndShowData() {
showLoadingIndicator();
try {
var data = yield loadData();
showData(data);
} catch (e) {
showError(e);
} finally {
removeLoadingIndicator();
}
}
spawn(loadAndShowData);
function* loadAndShowData() {
showLoadingIndicator();
try {
var data = yield loadData();
showData(data);
} catch (e) {
showError(e);
} finally {
removeLoadingIndicator();
}
}
spawn(loadAndShowData);
Where Can I UseThis?
• Traceur: yes
• Continuum: yes
• Browsers: Chrome, Firefox*
• Node.js: 0.11.3+
es6ify http://thlorenz.github.io/es6ify/
Template Strings
var someArithmetic = `${x} + ${y} = ${x + y}`;
var longString = `long
string
is
long`;
var someArithmetic = `${x} + ${y} = ${x + y}`;
var longString = `long
string
is
long`;
var someArithmetic = `${x} + ${y} = ${x + y}`;
var longString = `long
string
is
long`;
var whatsThis = func`${x} + ${y}n= ${x + y}`;
// becomes
var whatsThis = func(
{
raw: ['', ' + ', 'n = ', ''],
cooked: ['', ' + ', 'n = ', '']
},
x,
y,
x + y
);
var whatsThis = func`${x} + ${y}n= ${x + y}`;
// becomes
var whatsThis = func(
{
raw: ['', ' + ', 'n = ', ''],
cooked: ['', ' + ', 'n = ', '']
},
x,
y,
x + y
);
var whatsThis = func`${x} + ${y}n= ${x + y}`;
// becomes
var whatsThis = func(
{
raw: ['', ' + ', 'n = ', ''],
cooked: ['', ' + ', 'n = ', '']
},
x,
y,
x + y
);
var whatsThis = func`${x} + ${y}n= ${x + y}`;
// becomes
var whatsThis = func(
{
raw: ['', ' + ', 'n = ', ''],
cooked: ['', ' + ', 'n = ', '']
},
x,
y,
x + y
);
Contextual Auto-Escaping
var els = document.querySelectorAll('.' + className);
// what if className contains "."?
var els = qsa`.${className}`;
// => qsa({ raw: ['.', ''], … }, className);
// if we write qsa well, it can detect the preceding "."
// and escape className!
function qsa({ raw, cooked }, ...vars) {
// `raw[0]` ends in '.'
// so `vars[0]` needs to be escaped like a CSS class
// similar rules for IDs, attribute selectors, etc.
}
Contextual Auto-Escaping In Overdrive
safehtml`<a href="${url}?q=${query}"
onclick="alert('${message}')"
style="color: ${color}">
${message}
</a>`
validate (no "s or such)
filter (e.g. no javascript: URLs)
percent-encode
escape JS (e.g. closing quote)
HTML encode
escape CSS (e.g. ; or :)
censor unsafe CSS (e.g. expression())
HTML encode
HTML encode
Contextual Auto-Escaping In Overdrive
var url = 'http://example.com/', query = 'Hello & Goodbye';
var message = 'Goodbye & Hello', color = 'expression(alert(1337))';
safehtml`<a href="${url}?q=${query}"
onclick="alert('${message}')"
style="color: ${color}">
${message}
</a>`
<a href="http://example.com/?q=Hello%20%26%20Goodbye"
onclick="alert(&#39;Goodbye&#32;x26&#32;Hello&#39;)"
style="color: CENSORED">
Goodbye &amp; Hello
</a>
http://js-quasis-libraries-and-repl.googlecode.com/svn/trunk/safetemplate.html
Localization and Formatting
l10n`Hello ${name}; you are visitor number ${visitor}:n!
You have ${money}:c in your account!`
// Write a l10n function that:
// - if it sees nothing after the var, it does nothing
// - if it sees :n, it uses localized number formatter
// - if it sees :c, it uses localized currency formatter
Dynamic Regular Expressions
/d+,d+/
// But now ',' needs to be configurable, so you do
new RegExp('d+' + separator + 'd+')
// Ick! Instead, write a re function to make this work
re`d+${separator}d+`
Embedded HTML/XML
jsx`<a href="${url}">${text}</a>`
// write a smart jsx function that transforms this into
React.DOM.a({ href: url }, text)
// zomg, no compile-to-JS language required!
DSLs for Code Execution
var childProcess = sh`ps ax | grep ${pid}`;
var xhr = POST`http://example.org/service?a=${a}&b=${b}
Content-Type: application/json
Authorization: ${credentials}
{ "foo": ${foo}, "bar": ${bar} }`;
We Just Solved:
• String interpolation/basic templating
• Multiline strings
• Contextual auto-escaping (giving generic injection protection)
• Localization and formatting
• Dynamic regular expressions
• Embedded HTML
… and opened up a whole new world of DSLs for writing intuitive, readable JS
We Just Solved:
• String interpolation/basic templating
• Multiline strings
• Contextual auto-escaping (giving generic injection protection)
• Localization and formatting
• Dynamic regular expressions
• Embedded HTML
… and opened up a whole new world of DSLs for writing intuitive, readable JS
Where Can I UseThis?
• Traceur: yes
• Continuum: yes
• Browsers: no
• Node.js: no
The Future Now
 The future of JS: it’s important!
 Learn more:
 es6isnigh.com
 harmony:proposals wiki page
 Follow @esdiscuss / read esdiscuss.org.
 Be adventurous; use a transpiler!
 Don't stagnate.

More Related Content

What's hot

What's New in ES6 for Web Devs
What's New in ES6 for Web DevsWhat's New in ES6 for Web Devs
What's New in ES6 for Web DevsRami Sayar
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)Domenic Denicola
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!Brendan Eich
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAnkit Agarwal
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptŁukasz Kużyński
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Ben Lesh
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr Pelczar
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
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
 
ES6 in Production [JSConfUY2015]
ES6 in Production [JSConfUY2015]ES6 in Production [JSConfUY2015]
ES6 in Production [JSConfUY2015]Guillermo Paz
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 
React Native Evening
React Native EveningReact Native Evening
React Native EveningTroy Miles
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaFlorent Pillet
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot CampTroy Miles
 

What's hot (20)

What's New in ES6 for Web Devs
What's New in ES6 for Web DevsWhat's New in ES6 for Web Devs
What's New in ES6 for Web Devs
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 
Domains!
Domains!Domains!
Domains!
 
Effective ES6
Effective ES6Effective ES6
Effective ES6
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
JavaScript Promise
JavaScript PromiseJavaScript Promise
JavaScript Promise
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascript
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Promise pattern
Promise patternPromise pattern
Promise pattern
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
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...
 
ES6 in Production [JSConfUY2015]
ES6 in Production [JSConfUY2015]ES6 in Production [JSConfUY2015]
ES6 in Production [JSConfUY2015]
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
 

Similar to ES6: The Awesome Parts

Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax BasicsRichard Paul
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
Getting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascriptGetting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascriptMohd Saeed
 
Express Presentation
Express PresentationExpress Presentation
Express Presentationaaronheckmann
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScriptChengHui Weng
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
 
ESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. NowESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. NowKrzysztof Szafranek
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonAlex Payne
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 

Similar to ES6: The Awesome Parts (20)

Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
 
Wakanday JS201 Best Practices
Wakanday JS201 Best PracticesWakanday JS201 Best Practices
Wakanday JS201 Best Practices
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 
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 ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
Getting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascriptGetting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascript
 
Express Presentation
Express PresentationExpress Presentation
Express Presentation
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScript
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
CppTutorial.ppt
CppTutorial.pptCppTutorial.ppt
CppTutorial.ppt
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
ESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. NowESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. Now
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 

More from Domenic Denicola

More from Domenic Denicola (17)

The State of JavaScript (2015)
The State of JavaScript (2015)The State of JavaScript (2015)
The State of JavaScript (2015)
 
The jsdom
The jsdomThe jsdom
The jsdom
 
The Final Frontier
The Final FrontierThe Final Frontier
The Final Frontier
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
Streams for the Web
Streams for the WebStreams for the Web
Streams for the Web
 
After Return of the Jedi
After Return of the JediAfter Return of the Jedi
After Return of the Jedi
 
The State of JavaScript
The State of JavaScriptThe State of JavaScript
The State of JavaScript
 
How to Win Friends and Influence Standards Bodies
How to Win Friends and Influence Standards BodiesHow to Win Friends and Influence Standards Bodies
How to Win Friends and Influence Standards Bodies
 
The Extensible Web
The Extensible WebThe Extensible Web
The Extensible Web
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
 
Client-Side Packages
Client-Side PackagesClient-Side Packages
Client-Side Packages
 
Creating Truly RESTful APIs
Creating Truly RESTful APIsCreating Truly RESTful APIs
Creating Truly RESTful APIs
 
Promises, Promises
Promises, PromisesPromises, Promises
Promises, Promises
 
JavaScript on the Desktop
JavaScript on the DesktopJavaScript on the Desktop
JavaScript on the Desktop
 
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
 
Unit Testing for Great Justice
Unit Testing for Great JusticeUnit Testing for Great Justice
Unit Testing for Great Justice
 
Understanding the Node.js Platform
Understanding the Node.js PlatformUnderstanding the Node.js Platform
Understanding the Node.js Platform
 

Recently uploaded

Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesDavid Newbury
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 
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
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
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
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
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
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXTarek Kalaji
 
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 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
 
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
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
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
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 

Recently uploaded (20)

201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond Ontologies
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 
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
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
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
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
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
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBX
 
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 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
 
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™
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
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
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 

ES6: The Awesome Parts

  • 2. Domenic Denicola • http://domenic.me/ (blog) • https://github.com/domenic • https://npmjs.org/~domenic • http://slideshare.net/domenicdenicola Things I'm doing: • @esdiscuss onTwitter • The Promises/A+ spec • The Extensible Web Manifesto
  • 3. Why ES6? “Stagnation on the web is a social ill.” —Brendan Eich http://news.ycombinator.com/item?id=4634735
  • 4. Why JavaScript? “It is the one language that every vendor is committed to shipping compatibly. Evolving JS has the leverage to add/change the semantics of the platform in a way that no other strategy credibly can.” —Alex Russell http://infrequently.org/2013/07/why-javascript/
  • 5. Why ShouldYou Care? •It’s not often that, as a programmer, you get entirely new tools and capabilities in your toolbox. •Learning Haskell or a Lisp will do it, but then what do you build? •ES6 provides a unique opportunity.
  • 6. The Awesome Parts •Generators •Template strings •Proxies (no time today )
  • 8. function zeroOneTwo() { return [0, 1, 2]; } var array = zeroOneTwo(); for (var i of array) { console.log(i); }
  • 9. function* zeroOneTwo() { yield 0; yield 1; yield 2; } var generator = zeroOneTwo(); for (var i of generator) { console.log(i); }
  • 10. function* zeroOneTwo() { yield 0; yield 1; yield 2; } var generator = zeroOneTwo(); for (var i of generator) { console.log(i); }
  • 11. function* zeroOneTwo() { yield 0; yield 1; yield 2; } var generator = zeroOneTwo(); generator.next(); // { value: 0, done: false } generator.next(); // { value: 1, done: false } generator.next(); // { value: 2, done: false } generator.next(); // { value: undefined, done: true }
  • 12. function* fibonacci() { var previous = 0, current = 1; while (true) { var temp = previous; previous = current; current = temp + current; yield current; } } for (var i of fibonacci()) { console.log(i); } // 1, 2, 3, 5, 8, 13, ..., Infinity!
  • 13. function* take(iterable, numberToTake) { var i = 0; for (var taken of iterable) { if (i++ === numberToTake) { return; } yield taken; } } for (var i of take(fibonacci(), 5)) { console.log(i); } // 1, 2, 3, 5, 8 (and done!)
  • 14. Lazy sequences • You can write lazy versions of everything: filter, map, reduce, all those Underscore.js methods, … var awesomeEls = filter(domEls, isAwesome); var awesomeTexts = map(awesomeEls, el => el.textContent); var awesomeString = reduce(awesomeTexts, (acc, t) => acc + t); • Since filter and map return generators, nothing happens until reduce, a non-generator function, executes: then it's all done in a single pass. • You get the benefits of declarative functional data manipulation without the performance and memory downsides of intermediate arrays.
  • 15. Lazy sequences • You can write lazy versions of everything: filter, map, reduce, all those Underscore.js methods, … var awesomeEls = filter(domEls, isAwesome); var awesomeTexts = map(awesomeEls, el => el.textContent); var awesomeString = reduce(awesomeTexts, (acc, t) => acc + t); • Since filter and map return generators, nothing happens until reduce, a non-generator function, executes: then it's all done in a single pass. • You get the benefits of declarative functional data manipulation without the performance and memory downsides of intermediate arrays.
  • 16. But wait • Suspending execution until someone calls next() is a powerful feature. • What if you suspended execution until an async operation finished? Lots of people are starting to explore this in Node.js right now, leveraging e.g. promises to turn yield into a kind of “await.”
  • 17. function* loadUI() { showLoadingScreen(); yield loadUIDataAsynchronously(); hideLoadingScreen(); } spawn(loadUI); This function returns a promise Write the function spawn so that: • It calls next() and thus gets the loading promise. • It waits for the promise to fulfill before calling next() again. So we've suspended execution until the async operation finishes!
  • 18. function* loadAndShowData() { var data = yield loadData(); showData(data); } spawn(loadAndShowData); This function returns a promise for data You can actually pass data back in to the generator, causing yield to either return a value or throw an exception inside the generator body. • So if the promise fulfills, send back its fulfillment value, so that the data variable ends up holding it. • But if the promise rejects, tell the generator to throw the rejection reason as an exception.
  • 19. function* loadAndShowData() { showLoadingIndicator(); try { var data = yield loadData(); showData(data); } catch (e) { showError(e); } finally { removeLoadingIndicator(); } } spawn(loadAndShowData);
  • 20. function* loadAndShowData() { showLoadingIndicator(); try { var data = yield loadData(); showData(data); } catch (e) { showError(e); } finally { removeLoadingIndicator(); } } spawn(loadAndShowData);
  • 21. Where Can I UseThis? • Traceur: yes • Continuum: yes • Browsers: Chrome, Firefox* • Node.js: 0.11.3+
  • 24. var someArithmetic = `${x} + ${y} = ${x + y}`; var longString = `long string is long`;
  • 25. var someArithmetic = `${x} + ${y} = ${x + y}`; var longString = `long string is long`;
  • 26. var someArithmetic = `${x} + ${y} = ${x + y}`; var longString = `long string is long`;
  • 27. var whatsThis = func`${x} + ${y}n= ${x + y}`; // becomes var whatsThis = func( { raw: ['', ' + ', 'n = ', ''], cooked: ['', ' + ', 'n = ', ''] }, x, y, x + y );
  • 28. var whatsThis = func`${x} + ${y}n= ${x + y}`; // becomes var whatsThis = func( { raw: ['', ' + ', 'n = ', ''], cooked: ['', ' + ', 'n = ', ''] }, x, y, x + y );
  • 29. var whatsThis = func`${x} + ${y}n= ${x + y}`; // becomes var whatsThis = func( { raw: ['', ' + ', 'n = ', ''], cooked: ['', ' + ', 'n = ', ''] }, x, y, x + y );
  • 30. var whatsThis = func`${x} + ${y}n= ${x + y}`; // becomes var whatsThis = func( { raw: ['', ' + ', 'n = ', ''], cooked: ['', ' + ', 'n = ', ''] }, x, y, x + y );
  • 31. Contextual Auto-Escaping var els = document.querySelectorAll('.' + className); // what if className contains "."? var els = qsa`.${className}`; // => qsa({ raw: ['.', ''], … }, className); // if we write qsa well, it can detect the preceding "." // and escape className! function qsa({ raw, cooked }, ...vars) { // `raw[0]` ends in '.' // so `vars[0]` needs to be escaped like a CSS class // similar rules for IDs, attribute selectors, etc. }
  • 32. Contextual Auto-Escaping In Overdrive safehtml`<a href="${url}?q=${query}" onclick="alert('${message}')" style="color: ${color}"> ${message} </a>` validate (no "s or such) filter (e.g. no javascript: URLs) percent-encode escape JS (e.g. closing quote) HTML encode escape CSS (e.g. ; or :) censor unsafe CSS (e.g. expression()) HTML encode HTML encode
  • 33. Contextual Auto-Escaping In Overdrive var url = 'http://example.com/', query = 'Hello & Goodbye'; var message = 'Goodbye & Hello', color = 'expression(alert(1337))'; safehtml`<a href="${url}?q=${query}" onclick="alert('${message}')" style="color: ${color}"> ${message} </a>` <a href="http://example.com/?q=Hello%20%26%20Goodbye" onclick="alert(&#39;Goodbye&#32;x26&#32;Hello&#39;)" style="color: CENSORED"> Goodbye &amp; Hello </a> http://js-quasis-libraries-and-repl.googlecode.com/svn/trunk/safetemplate.html
  • 34. Localization and Formatting l10n`Hello ${name}; you are visitor number ${visitor}:n! You have ${money}:c in your account!` // Write a l10n function that: // - if it sees nothing after the var, it does nothing // - if it sees :n, it uses localized number formatter // - if it sees :c, it uses localized currency formatter
  • 35. Dynamic Regular Expressions /d+,d+/ // But now ',' needs to be configurable, so you do new RegExp('d+' + separator + 'd+') // Ick! Instead, write a re function to make this work re`d+${separator}d+`
  • 36. Embedded HTML/XML jsx`<a href="${url}">${text}</a>` // write a smart jsx function that transforms this into React.DOM.a({ href: url }, text) // zomg, no compile-to-JS language required!
  • 37. DSLs for Code Execution var childProcess = sh`ps ax | grep ${pid}`; var xhr = POST`http://example.org/service?a=${a}&b=${b} Content-Type: application/json Authorization: ${credentials} { "foo": ${foo}, "bar": ${bar} }`;
  • 38. We Just Solved: • String interpolation/basic templating • Multiline strings • Contextual auto-escaping (giving generic injection protection) • Localization and formatting • Dynamic regular expressions • Embedded HTML … and opened up a whole new world of DSLs for writing intuitive, readable JS
  • 39. We Just Solved: • String interpolation/basic templating • Multiline strings • Contextual auto-escaping (giving generic injection protection) • Localization and formatting • Dynamic regular expressions • Embedded HTML … and opened up a whole new world of DSLs for writing intuitive, readable JS
  • 40. Where Can I UseThis? • Traceur: yes • Continuum: yes • Browsers: no • Node.js: no
  • 41. The Future Now  The future of JS: it’s important!  Learn more:  es6isnigh.com  harmony:proposals wiki page  Follow @esdiscuss / read esdiscuss.org.  Be adventurous; use a transpiler!  Don't stagnate.