SlideShare una empresa de Scribd logo
1 de 41
Descargar para leer sin conexión
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.

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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 a 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 a 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
 

Más de Domenic Denicola

Más de 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
 

Último

A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Jeffrey Haguewood
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Mark Simos
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Nikki Chapple
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Français Patch Tuesday - Avril
Français Patch Tuesday - AvrilFrançais Patch Tuesday - Avril
Français Patch Tuesday - AvrilIvanti
 
QMMS Lesson 2 - Using MS Excel Formula.pdf
QMMS Lesson 2 - Using MS Excel Formula.pdfQMMS Lesson 2 - Using MS Excel Formula.pdf
QMMS Lesson 2 - Using MS Excel Formula.pdfROWELL MARQUINA
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...amber724300
 

Último (20)

A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Français Patch Tuesday - Avril
Français Patch Tuesday - AvrilFrançais Patch Tuesday - Avril
Français Patch Tuesday - Avril
 
QMMS Lesson 2 - Using MS Excel Formula.pdf
QMMS Lesson 2 - Using MS Excel Formula.pdfQMMS Lesson 2 - Using MS Excel Formula.pdf
QMMS Lesson 2 - Using MS Excel Formula.pdf
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
 

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.