SlideShare une entreprise Scribd logo
1  sur  41
Télécharger pour lire hors ligne
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.

Contenu connexe

Tendances

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
 

Tendances (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
 

Similaire à 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
 

Similaire à 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
 

Plus de Domenic Denicola

Plus 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
 

Dernier

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 

Dernier (20)

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

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.