SlideShare a Scribd company logo
1 of 26
Download to read offline
The Beautiful Simplicity
of ES2015
Brandon Belvin
What is ES2015?
● Code-named "Harmony;" contains many improvements that were slated for
the fourth edition of ECMAScript (commonly known as JavaScript)
● Began in 2008, but was scaled back and delayed after dissent
● Re-emerged in 2011 to become the sixth edition, known as ES6
● Finalized in June 2015, renamed to ES2015
● Annual updates planned with ES2016 and ES2017 roadmapped
But what makes
ES2015 so great?...
Arrow Functions
Features
● Terse, yet expressive
● Bound to lexical scope
● Make great sense when following
functional programming
What They Solve
● Perfect for small, in-line anonymous
functions
● Less var self = this;and
.bind(this)
[1,2,3].reduce((acc,val) => acc + val);
[1,2,3].reduce(function(acc, val) {
return acc + val;
});
Arrow Functions
ES6
ES5
[1,2,3].reduce((acc,val) => acc + val);
Arrow Functions
[1,2,3,4,5,6].filter(val => val !== 5) //[1,2,3,4,6]
.map((val, i) => val * i) //[0,2,6,12,24]
.reduce((prev, cur) => prev + cur); //44
(This is in no way a contrived example… It's completely serious.)
Template Strings
Features
● Native interpolation
● Multi-line strings
● Custom template processors
What They Solve
● No need to escape tick or quote
● No more:
'Looped ' + count + ' times'
'foon' +
'barn' +
'baz'
`The time and date is ${ new Date().toLocaleString() }`
var apples = 5;
var text = 'Bob ate ' + apples + ' of his apples!';
console.log(text);
// Bob ate 5 of his apples!
Template Strings
ES5
ES6
var howMany = apples => apples > 4 ? 'so many' : 'a few';
var apples = 5;
var text = `Bob ate ${ howMany(apples) } apples!`;
console.log(text);
// Bob ate so many apples!
Template Strings
Multi-line
var multiLineText = `This is
multi-line and continues
until the next
backtick`;
// This is
// multi-line and continues
// until the next
// backtick
Function Interpolation
var list = [ 1, 2, 3 ];
var template = `<div><ul>
${list.map(num =>
`<li>${num}</li>`).join('n')}
</ul></div>`;
// <div><ul>
// <li>1</li>
// <li>2</li>
// <li>3</li>
// </ul></div>
Assignment Destructuring
Features
● Easier variable assignment
● Can access deep properties in
objects
● Assignment and index skipping for
arrays
What They Solve
● No more huge blocks of assignment
boilerplate
● Destructuring as a parameter list
var { baseUrl, body, params: { id } } = request;
Assignment Destructuring
ES5
var baseUrl = request.baseUrl;
var body = request.body;
var pageId = request.params.id;
ES6
var { baseUrl, body, params: { id: pageId } } = request;
Default and Rest Parameters, Spread Operator
Features
● Can set a default argument value
● Collect multiple arguments into an
array
● Can also destructure arrays
What They Solve
● Set a default value rather than
checking for existence inside the
function
● Can be used instead of the
arguments object (which isn't a real
array)
● Can replace the .apply() function
function foo (bar=12, ...rest) { var ary = [1, 2, ...rest]; }
Default and Rest Parameters
ES5
function sum() {
if (!arguments.length) {
return 0;
}
var args = Array.prototype.slice.call(arguments);
var base = args.shift();
return args.reduce(function (prev, val) {
return prev + val;
}, base);
} // 8 lines inside sum()
sum(); // 0
sum(5); // 5
sum(1,2,3,4,5,6,7); // 28
Default and Rest Parameters
ES5 (Improved)
function sum() {
var args = Array.prototype.slice.call(arguments);
var base = args.shift();
return args.reduce(function (prev, val) {
return prev + val;
}, base || 0);
} // 5 lines inside sum()
sum(); // 0
sum(5); // 5
sum(1,2,3,4,5,6,7); // 28
Default and Rest Parameters
ES6
function sum(base = 0, ...vals) {
return vals.reduce((prev, val) => prev + val, base);
} // 1 line inside sum()
sum(); // 0
sum(5); // 5
sum(1,2,3,4,5,6,7); // 28
var x = new (Date.bind.apply(Date, [null, 2015, 9, 23]));
console.log(x.toDateString());
// Fri Oct 23 2015
Spread Operator
ES5
ES6
var x = new Date(...[2015, 9, 23]);
console.log(x.toDateString());
// Fri Oct 23 2015
(Hat-tip to Nicolas Bevacqua for this example)
Promises
Features
● Allows for more narrative
asynchronous code
● "Proper" exception handling
● Easier to follow for complex
asynchronous interactions through
chaining
What They Solve
● Eliminate "callback spaghetti"
● Can throw exception rather than
return it in callback
fetch('foo').then(res => {}).catch(err => {})
Callback Example
User.findById('bob_appleseed', function(err, user) {
if (err) {
return console.log(`error: ${ err }`);
}
user.apples = user.apples - 5;
user.save(function(err, user) {
if (err) {
return console.log(`error: ${ err }`);
}
console.log(`Bob now has ${ user.apples } apples`);
});
});
Promises
User.findById('bob_appleseed').exec()
.then(user => {
user.apples = user.apples - 5;
return user.save(); // returning a promise here
})
.then(user => {
console.log(`Bob now has ${ user.apples } apples`);
})
.catch(err => {
// Only need one catch for this chain
console.log(`error: ${ err }`);
});
Promises
Extra Features
Promises.all([ fetch('api.random.org'), fetch('api.random.org') ])
.then(randoms =>
randoms.reduce((prev, val) => prev + val, 0) / randoms.length;
})
.catch(err => `Randoms request failed with error: ${ err }`);
Promise.all()- Wraps an array of Promises in a Promise that either resolves when all
the dependencies resolve, or rejects if any of the dependencies reject.
● Useful when a function should only run after a number of parallel async operations are
complete
Promises
Extra Features
Promise.race([
fetch('/resource-that-may-take-a-while'),
new Promise((resolve, reject) =>
setTimeout(() => reject(new Error('request timeout')), 5000)
)
])
.then(response => console.log(response))
.catch(error => console.log(error));
Promise.race()- Accepts an array of Promises and settles with the value of the first to
complete.
● Can be used to handle timeout of a Promise we otherwise have no control over:
(Another very grateful hat-tip to Nicolas Bevacqua for this example)
And this only scratches the surface...
Assignment Destructuring
Spread Operator
Rest Parameters
Arrow Functions
Template Strings
Object Literals
Classes
Let and Const
Symbols
IteratorsGenerators
Promises
Maps/WeakMaps
Sets/WeakSets
Proxies
Reflection
Modules
How to use
ES2015 today
100% support is still a long
way off, but you can use most
of the enhancements today.
Built-in Support:
● Node v4 (more with --harmony
flag)
● Chrome
● Firefox
● Microsoft Edge
Transpiler:
● Babel (babeljs.io)
● Traceur (google/traceur-compiler)
Where to learn
ES2015
Blogs & Writing:
● PonyFoo (ponyfoo.com)
● JavaScript Scene (medium.
com/javascript-scene)
● Babel Docs (babeljs.io/docs/learn-
es2015)
Docs & Resources:
● Mozilla Developer Network (MDN)
● Learn Harmony (learnharmony.org)
Brandon Belvin
@PizzaBrandon
Twitter
GitHub

More Related Content

What's hot

Gravity Forms Hooks & Filters
Gravity Forms Hooks & FiltersGravity Forms Hooks & Filters
Gravity Forms Hooks & Filters
iamdangavin
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
wpnepal
 

What's hot (20)

A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 
PL/SQL
PL/SQLPL/SQL
PL/SQL
 
MariaDB workshop
MariaDB workshopMariaDB workshop
MariaDB workshop
 
Workshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJSWorkshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJS
 
Gravity Forms Hooks & Filters
Gravity Forms Hooks & FiltersGravity Forms Hooks & Filters
Gravity Forms Hooks & Filters
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
 
ZG PHP - Specification
ZG PHP - SpecificationZG PHP - Specification
ZG PHP - Specification
 
Factory Girl
Factory GirlFactory Girl
Factory Girl
 
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Slim RedBeanPHP and Knockout
Slim RedBeanPHP and KnockoutSlim RedBeanPHP and Knockout
Slim RedBeanPHP and Knockout
 
WordPress overloading Gravityforms using hooks, filters and extending classes
WordPress overloading Gravityforms using hooks, filters and extending classes WordPress overloading Gravityforms using hooks, filters and extending classes
WordPress overloading Gravityforms using hooks, filters and extending classes
 
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceMeet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
 
Php Unit With Zend Framework Zendcon09
Php Unit With Zend Framework   Zendcon09Php Unit With Zend Framework   Zendcon09
Php Unit With Zend Framework Zendcon09
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using Codeception
 
RubyConf Bangladesh 2017 - Craft beautiful code with Ruby DSL
RubyConf Bangladesh 2017 - Craft beautiful code with Ruby DSLRubyConf Bangladesh 2017 - Craft beautiful code with Ruby DSL
RubyConf Bangladesh 2017 - Craft beautiful code with Ruby DSL
 
ngMess: AngularJS Dependency Injection
ngMess: AngularJS Dependency InjectionngMess: AngularJS Dependency Injection
ngMess: AngularJS Dependency Injection
 
Intro to GraphQL on Android with Apollo DroidconNYC 2017
Intro to GraphQL on Android with Apollo DroidconNYC 2017Intro to GraphQL on Android with Apollo DroidconNYC 2017
Intro to GraphQL on Android with Apollo DroidconNYC 2017
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016
 

Viewers also liked

Viewers also liked (20)

Web components
Web componentsWeb components
Web components
 
Introduction To Dart (GDG NY Jan 2014 Meetup)
Introduction To Dart (GDG NY Jan 2014 Meetup)Introduction To Dart (GDG NY Jan 2014 Meetup)
Introduction To Dart (GDG NY Jan 2014 Meetup)
 
Workshop de Web Components
Workshop de Web ComponentsWorkshop de Web Components
Workshop de Web Components
 
Battle of Frameworks: Polymer - Meetup Paris Web Components - 2016-09
Battle of Frameworks: Polymer - Meetup Paris Web Components - 2016-09Battle of Frameworks: Polymer - Meetup Paris Web Components - 2016-09
Battle of Frameworks: Polymer - Meetup Paris Web Components - 2016-09
 
Polymer Elements: Tudo que você precisa saber para criar a web
Polymer Elements: Tudo que você precisa saber para criar a webPolymer Elements: Tudo que você precisa saber para criar a web
Polymer Elements: Tudo que você precisa saber para criar a web
 
Polymer and Firebase: Componentizing the Web in Realtime
Polymer and Firebase: Componentizing the Web in RealtimePolymer and Firebase: Componentizing the Web in Realtime
Polymer and Firebase: Componentizing the Web in Realtime
 
Angular js gtg-27feb2013
Angular js gtg-27feb2013Angular js gtg-27feb2013
Angular js gtg-27feb2013
 
Apresentação Google I/O Extended Vitória
Apresentação Google I/O Extended VitóriaApresentação Google I/O Extended Vitória
Apresentação Google I/O Extended Vitória
 
Chrome Dev Summit Highlights (NYC GDG Dec 2013)
Chrome Dev Summit Highlights (NYC GDG Dec 2013)Chrome Dev Summit Highlights (NYC GDG Dec 2013)
Chrome Dev Summit Highlights (NYC GDG Dec 2013)
 
WebApps com Web Components
WebApps com Web ComponentsWebApps com Web Components
WebApps com Web Components
 
Material Design - do smartphone ao desktop
Material Design - do smartphone ao desktopMaterial Design - do smartphone ao desktop
Material Design - do smartphone ao desktop
 
O futuro do Android
O futuro do AndroidO futuro do Android
O futuro do Android
 
Material design
Material designMaterial design
Material design
 
Um salve para evolução! construindo uma nova web com polymer
Um salve para evolução! construindo uma nova web com  polymerUm salve para evolução! construindo uma nova web com  polymer
Um salve para evolução! construindo uma nova web com polymer
 
Polymer Starter Kit
Polymer Starter KitPolymer Starter Kit
Polymer Starter Kit
 
Tech talk polymer
Tech talk polymerTech talk polymer
Tech talk polymer
 
Angular 2 overview workshop
Angular 2 overview workshopAngular 2 overview workshop
Angular 2 overview workshop
 
Angular 2 - a New Hope
Angular 2 - a New HopeAngular 2 - a New Hope
Angular 2 - a New Hope
 
Pensando em UX / UI com o material design
Pensando em UX / UI com o material designPensando em UX / UI com o material design
Pensando em UX / UI com o material design
 
Componentizando a Web com Polymer
Componentizando a Web com PolymerComponentizando a Web com Polymer
Componentizando a Web com Polymer
 

Similar to The Beautiful Simplicity of ES2015

ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015
qmmr
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General Introduction
Thomas Johnston
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan Stefanov
 

Similar to The Beautiful Simplicity of ES2015 (20)

ES6 Simplified
ES6 SimplifiedES6 Simplified
ES6 Simplified
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
 
Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
Dan Shappir: Things you can do in ES6 that can't be done in ES5
Dan Shappir: Things you can do in ES6 that can't be done in ES5Dan Shappir: Things you can do in ES6 that can't be done in ES5
Dan Shappir: Things you can do in ES6 that can't be done in ES5
 
ES6: The future is now
ES6: The future is nowES6: The future is now
ES6: The future is now
 
Modern JavaScript - Modern ES6+ Features
Modern JavaScript - Modern ES6+ FeaturesModern JavaScript - Modern ES6+ Features
Modern JavaScript - Modern ES6+ Features
 
Exploring ES6
Exploring ES6Exploring ES6
Exploring ES6
 
Es6 to es5
Es6 to es5Es6 to es5
Es6 to es5
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015
 
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
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
 
ECMAScript 6 Review
ECMAScript 6 ReviewECMAScript 6 Review
ECMAScript 6 Review
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General Introduction
 
Living in the ES6 Future, Today
Living in the ES6 Future, TodayLiving in the ES6 Future, Today
Living in the ES6 Future, Today
 
Workshop JavaScript ES6+
Workshop JavaScript ES6+Workshop JavaScript ES6+
Workshop JavaScript ES6+
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 

Recently uploaded

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Recently uploaded (20)

How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 

The Beautiful Simplicity of ES2015

  • 1. The Beautiful Simplicity of ES2015 Brandon Belvin
  • 2. What is ES2015? ● Code-named "Harmony;" contains many improvements that were slated for the fourth edition of ECMAScript (commonly known as JavaScript) ● Began in 2008, but was scaled back and delayed after dissent ● Re-emerged in 2011 to become the sixth edition, known as ES6 ● Finalized in June 2015, renamed to ES2015 ● Annual updates planned with ES2016 and ES2017 roadmapped
  • 3. But what makes ES2015 so great?...
  • 4. Arrow Functions Features ● Terse, yet expressive ● Bound to lexical scope ● Make great sense when following functional programming What They Solve ● Perfect for small, in-line anonymous functions ● Less var self = this;and .bind(this) [1,2,3].reduce((acc,val) => acc + val);
  • 5. [1,2,3].reduce(function(acc, val) { return acc + val; }); Arrow Functions ES6 ES5 [1,2,3].reduce((acc,val) => acc + val);
  • 6. Arrow Functions [1,2,3,4,5,6].filter(val => val !== 5) //[1,2,3,4,6] .map((val, i) => val * i) //[0,2,6,12,24] .reduce((prev, cur) => prev + cur); //44 (This is in no way a contrived example… It's completely serious.)
  • 7. Template Strings Features ● Native interpolation ● Multi-line strings ● Custom template processors What They Solve ● No need to escape tick or quote ● No more: 'Looped ' + count + ' times' 'foon' + 'barn' + 'baz' `The time and date is ${ new Date().toLocaleString() }`
  • 8. var apples = 5; var text = 'Bob ate ' + apples + ' of his apples!'; console.log(text); // Bob ate 5 of his apples! Template Strings ES5 ES6 var howMany = apples => apples > 4 ? 'so many' : 'a few'; var apples = 5; var text = `Bob ate ${ howMany(apples) } apples!`; console.log(text); // Bob ate so many apples!
  • 9. Template Strings Multi-line var multiLineText = `This is multi-line and continues until the next backtick`; // This is // multi-line and continues // until the next // backtick Function Interpolation var list = [ 1, 2, 3 ]; var template = `<div><ul> ${list.map(num => `<li>${num}</li>`).join('n')} </ul></div>`; // <div><ul> // <li>1</li> // <li>2</li> // <li>3</li> // </ul></div>
  • 10. Assignment Destructuring Features ● Easier variable assignment ● Can access deep properties in objects ● Assignment and index skipping for arrays What They Solve ● No more huge blocks of assignment boilerplate ● Destructuring as a parameter list var { baseUrl, body, params: { id } } = request;
  • 11. Assignment Destructuring ES5 var baseUrl = request.baseUrl; var body = request.body; var pageId = request.params.id; ES6 var { baseUrl, body, params: { id: pageId } } = request;
  • 12. Default and Rest Parameters, Spread Operator Features ● Can set a default argument value ● Collect multiple arguments into an array ● Can also destructure arrays What They Solve ● Set a default value rather than checking for existence inside the function ● Can be used instead of the arguments object (which isn't a real array) ● Can replace the .apply() function function foo (bar=12, ...rest) { var ary = [1, 2, ...rest]; }
  • 13. Default and Rest Parameters ES5 function sum() { if (!arguments.length) { return 0; } var args = Array.prototype.slice.call(arguments); var base = args.shift(); return args.reduce(function (prev, val) { return prev + val; }, base); } // 8 lines inside sum() sum(); // 0 sum(5); // 5 sum(1,2,3,4,5,6,7); // 28
  • 14. Default and Rest Parameters ES5 (Improved) function sum() { var args = Array.prototype.slice.call(arguments); var base = args.shift(); return args.reduce(function (prev, val) { return prev + val; }, base || 0); } // 5 lines inside sum() sum(); // 0 sum(5); // 5 sum(1,2,3,4,5,6,7); // 28
  • 15. Default and Rest Parameters ES6 function sum(base = 0, ...vals) { return vals.reduce((prev, val) => prev + val, base); } // 1 line inside sum() sum(); // 0 sum(5); // 5 sum(1,2,3,4,5,6,7); // 28
  • 16. var x = new (Date.bind.apply(Date, [null, 2015, 9, 23])); console.log(x.toDateString()); // Fri Oct 23 2015 Spread Operator ES5 ES6 var x = new Date(...[2015, 9, 23]); console.log(x.toDateString()); // Fri Oct 23 2015 (Hat-tip to Nicolas Bevacqua for this example)
  • 17. Promises Features ● Allows for more narrative asynchronous code ● "Proper" exception handling ● Easier to follow for complex asynchronous interactions through chaining What They Solve ● Eliminate "callback spaghetti" ● Can throw exception rather than return it in callback fetch('foo').then(res => {}).catch(err => {})
  • 18. Callback Example User.findById('bob_appleseed', function(err, user) { if (err) { return console.log(`error: ${ err }`); } user.apples = user.apples - 5; user.save(function(err, user) { if (err) { return console.log(`error: ${ err }`); } console.log(`Bob now has ${ user.apples } apples`); }); });
  • 19. Promises User.findById('bob_appleseed').exec() .then(user => { user.apples = user.apples - 5; return user.save(); // returning a promise here }) .then(user => { console.log(`Bob now has ${ user.apples } apples`); }) .catch(err => { // Only need one catch for this chain console.log(`error: ${ err }`); });
  • 20. Promises Extra Features Promises.all([ fetch('api.random.org'), fetch('api.random.org') ]) .then(randoms => randoms.reduce((prev, val) => prev + val, 0) / randoms.length; }) .catch(err => `Randoms request failed with error: ${ err }`); Promise.all()- Wraps an array of Promises in a Promise that either resolves when all the dependencies resolve, or rejects if any of the dependencies reject. ● Useful when a function should only run after a number of parallel async operations are complete
  • 21. Promises Extra Features Promise.race([ fetch('/resource-that-may-take-a-while'), new Promise((resolve, reject) => setTimeout(() => reject(new Error('request timeout')), 5000) ) ]) .then(response => console.log(response)) .catch(error => console.log(error)); Promise.race()- Accepts an array of Promises and settles with the value of the first to complete. ● Can be used to handle timeout of a Promise we otherwise have no control over: (Another very grateful hat-tip to Nicolas Bevacqua for this example)
  • 22. And this only scratches the surface...
  • 23. Assignment Destructuring Spread Operator Rest Parameters Arrow Functions Template Strings Object Literals Classes Let and Const Symbols IteratorsGenerators Promises Maps/WeakMaps Sets/WeakSets Proxies Reflection Modules
  • 24. How to use ES2015 today 100% support is still a long way off, but you can use most of the enhancements today. Built-in Support: ● Node v4 (more with --harmony flag) ● Chrome ● Firefox ● Microsoft Edge Transpiler: ● Babel (babeljs.io) ● Traceur (google/traceur-compiler)
  • 25. Where to learn ES2015 Blogs & Writing: ● PonyFoo (ponyfoo.com) ● JavaScript Scene (medium. com/javascript-scene) ● Babel Docs (babeljs.io/docs/learn- es2015) Docs & Resources: ● Mozilla Developer Network (MDN) ● Learn Harmony (learnharmony.org)