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

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

Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
Richard Paul
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
rajivmordani
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom 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 framework
Ben 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

The Final Frontier
The Final FrontierThe Final Frontier
The Final Frontier
Domenic Denicola
 
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
Domenic Denicola
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
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

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
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...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
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)
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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
 

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.