This document discusses ECMAScript 2015 (ES2015) features for JavaScript. It covers new functions like arrow functions and default parameters, string templating with backticks, object destructuring, classes and modules, and new data structures like Sets and Maps. The presentation encourages learning ES2015 features today using transpilation to older browser versions. It concludes that JavaScript has evolved significantly with ES2015 and brings many new options to the language.
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Brand New JavaScript - ECMAScript 2015
1. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Brand New JavaScript –
ECMAScript 2015
Gil Fink
CEO and Senior Consultant, sparXys
Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
2. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Meet the Speaker
• sparXys CEO and Senior consultant
• ASP.NET/IIS Microsoft MVP
• Co-author of Pro Single Page Application
Development (Apress)
• Co-author of 4 Microsoft Official Courses (MOCs)
• ng-conf Israel co-organizer and GDG Rashlatz
Meetup co-organizer
3. Agenda
• What is ECMAScript 2015?
• Function Goodies
• String Templates
• Object Bounties
• Project Structure
• New Data Structures
Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
5. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
JavaScript Evolution
Timeline
1996 1999 2009 2015 ?2016
6. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
ES2015 - Browser Support
• Firefox and Edge already implemented most of
ES2015 spec
• V8 (Chrome, NodeJS) already implemented a
significant part
Consult the following table:
• http://kangax.github.io/es5-compat-table/es6/
7. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Support in Old Browser
Versions?
8. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Transpilers and
Preprocessors
Compile ES2015 to ES5 using Transpilers such as
• Babel – Online REPL
• Traceur – Online Playground
Use ES2015 language features in Preprocessors such as
• TypeScript – Online Playground
9. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Function Goodies
11. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Arrow Functions
Turn this
Into this
[1, 2 ,3, 4, 5].map(function(x) {
return x * x;
});
[1, 2, 3, 4, 5].map(x => x * x);
12. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
No more .bind(this)!
ES5:
ES2015:
Arrow functions handle the this keyword!
Translator.prototype.translate = function(wordlist) {
return wordlist.map(function(word) {
return this.dictionary[word];
}.bind(this));
};
Translator.prototype.translate = function(wordlist) {
return wordlist.map(word => this.dictionary[word]);
};
13. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Old School Default Values
• The use of || adds confusion to your source code!
function eat(fruit) {
var food = fruit || ‘banana’;
console.log('Koko eats: ' + fruit);
}
eat();
// Koko eats: banana
eat('apple');
// Koko eats: apple
14. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
ES2015 Default Values
function eat(fruit = 'banana') {
console.log('Koko eats: ' + fruit);
}
eat();
// Koko eats: banana
eat('apple');
// Koko eats: apple
15. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Rest
• Gets as array parameter the rest of the passed in
arguments
monkeyLog('Kiki', 'banana', 'monkey business');
function monkeyLog(monkeyName, ...stuff) {
stuff.forEach(thing => console.log(monkeyName + ' says ' + thing));
}
// Kiki says banana
// Kiki says monkey business
16. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Spread (inverse Rest)
• Spreads an array into function arguments
o In the order of the array elements
function f (x, y, z) {
return x + y + z;
}
f(...[1,2,3])
// 6
17. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Block Scope
• What would the output of the following code?
var events = ['click', 'dblclick', 'keydown', 'keyup'];
for (var i = 0; i < events.length; i++) {
var event = events[i];
element.addEventListener(event, function() {
console.log('got event: ' + event);
});
}
18. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
let - To The Rescue
• let allows to define a block-scoped variable:
var events = ['click', 'dblclick', 'keydown', 'keyup'];
for (var i = 0; i < events.length; i++) {
let event = events[i];
element.addEventListener(event, function() {
console.log('got event: ' + event);
});
}
19. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Const
• Trying to set a const during runtime will raise an
error!
function calcWeight(lion) {
const pi = 3.14159265359;
if (lion.name === ‘Simba') {
pi = 3.07; // Error! Don’t do that at home kids…
}
return lion.height * lion.age / pi * pi;
}
20. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
String Templates
21. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
String Templates
• Use backticks ( ` ) for defining template strings
• Use curly brackets to embed values inside backticks
// Multiline allowed!
var str = `In older versions of JavaScript this is
not legal.`;
// Easy embedding of values inside strings
var total = 30;
var price = `The monkey costs ${total} dollars`;
var priceWithTax = `The monkey costs ${total*1.18} dollars with tax`;
22. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
String Templates - Tags
function tax(str, price) {
// str === ['This monkey costs ', ' dollars']
const TAX_RATE = 1.07;
return str[0] + price*TAX_RATE + str[1];
}
var price = 25;
var messageWithTax = tax`The monkey costs ${price} dollars`
// The monkey costs 26.75 dollars
23. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Tags for i18n
• An interesting use-case for tags is i18n translations
var name = 'Lucas';
var greeting = locale`Hello, ${name}! How are you today?`;
// Bonjour, Lucas! Ça va comment aujourd'hui?
24. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Tags for HTML Escaping
• We can use tags for escaping HTML content:
var monkey = {
name: 'Charlie',
profession: 'Hacker!!!<script>alert("boo")</script>'
};
safehtml`
<h1>Monkey details: ${monkey.name}</h1>
<div>Works as ${monkey.profession}</div>
`
25. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Object Bounties
26. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Destructuring
• List matching:
• Object Assignment:
let [first, , third] = [1,2,3];
function getMonkey() {
return {name: 'Bobi', age: 25};
}
let {name, age} = getMonkey();
27. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Argument Destructuring
• Works with default values
• Good solution for options parameter
function summonMonkey({name}) {
console.log(`Summoning ${name}`);
}
summonMonkey({name: 'Charlie'});
// Summoning Charlie
28. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Enhanced Object Literals
function getZoo(zooKeeper, monkeyType) {
return {
zooKeeper,
feedAnimals() {
// ...
},
[monkeyType]: new Monkey()
};
}
29. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Project Structure
classes & modules
30. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Classes
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} is speaking…`);
}
}
var a = new Animal('Yogi');
a.speak();
31. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Inheritance
class Monkey extends Animal {
constructor(name, age) {
super(name);
this.age = age;
}
speak() {
console.log('Give me Banana!');
}
}
var monkey = new Monkey('Kiki', 4);
monkey.speak();
32. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Static Methods
class Gorilla extends Monkey {
static averageWeight() {
return 150;
}
}
console.log(Gorilla.averageWeight());
33. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Modules
• math.js
• app.js
export function sum(x, y) {
return x + y;
}
export var pi = 3.141593;
import {sum, pi} from './math';
console.log("2π = " + sum(pi, pi));
34. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
New Data Structures
35. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Sets
var words = new Set();
words.add('hello').add('goodbye').add('hello');
// words.size === 2;
// words.has('hello') === true;
36. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Maps
// Maps
var m = new Map();
m.set('hello', 42);
var monkey = new Monkey();
m.set(monkey, 34); // objects can be keys!
// m.get(monkey) === 34;
37. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Weak Maps
• The keys have weak reference and will not prevent
object from being garbage collected
• There is also WeakSet
• WeakMap and WeekSet are not iterable
var zoo = new WeakMap();
var monkey = { name: 'Kiki' };
zoo.set(monkey, 42);
console.log(zoo.get('monkey'));
38. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
for-of Loop
• The for-of loop iterates over the values
o Of an array
o Of An iteratable object (which isn’t not covered in this session)
let sum = 0;
for(let number of [1, 2, 3]) {
sum += number;
}
39. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Extras
There's much more in ES2015:
• Iterators
• Generators
• Symbols
• Tail recursion
• Promises
• Proxies, Reflection
• Learn more at:
https://github.com/lukehoban/es6features
40. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Should I Use ES2015
Today?
42. Summary
• JavaScript is a dominant language that evolved
through the years
• ECMAScript 2015 brings a lot of new options
into the JavaScript language
• Learn ECMAScript 2015 today!
Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
43. Join the conversation on Twitter:
@SoftArchConf #SoftwareArchitect2015
Resources
• Download the slide deck:
• My Blog – http://www.gilfink.net
• Follow me on Twitter – @gilfink