3. in the browser and on the server, too
in a not too far future …
4.
5. Object Literals Shorthand
It’s just syntactic sugar for Object literals.
var v = 42, propertyName = "count";
function fn() { console.log(v); };
// the old way
var obj = { v: v, fn: fn, fn2: function() { /*...*/ } };
obj[propertyName] = 10;
// es6 shorthand O/
var obj = {
v,
fn,
fn2() { /*...*/ },
[propertyName]: 10
}
6. Destructuring
Allows to extract values from object and array using patterns.
// ... and support default values
var [name, extension = ""] = "LICENSE".split(".");
console.log(extension) // ""
// it works with array too!
var [name, extension] = "me.jpeg".split(".");
console.log(extension); // jpeg
// destructuring + object literal shorthand
var { v, fn } = obj;
console.log(v); // 42
var { v: value, fn: log } = obj;
console.log(value); // 42
7. Rest & Spread Operator
The Spread operator turns an array into consecutive arguments in a function call. The Rest
operator binds trailing parameters to an array.
var arr = [1, 2]; arr.concat([3, 4]); // [1, 2, [3, 4]] FAIL! ಥ_ಥ
[3, 4].forEach(function(x) { arr.push(x) }); // [1, 2, 3, 4] At least it works ¯_(ツ)_/¯
// spread to the rescue!
arr.concat(...[3, 4]); // [1, 2, 3, 4] 0/
// rest
var [winner, ...theOthers] = ["a", "b", "c"];
console.log(theOthers instanceof Array); // true
console.log(theOthers.length); // 2
8. Super-powered functions
Varargs and default parameters.
// default value for function’s arguments
repeat("yo"); // yoyo
function repeat(msg, time = 2) {
return msg.repeat(time);
}
// rest parameters
function resize(width, height, ...elems){ console.log(elems); }
resize(100, 100, "#box", "#photo"); // ["#box", "#photo"]
function fn(...args){ console.log(args); }
fn(); // []
fn(42, "bho!"); // [42, "bho!"]
9. Block Scoped variables
Block scoped variable assignments with let and const.
> Organized code!
if(true){
let v = 42;
}
console.log(v); // ReferenceError: v is not defined
// constants
const pi = 3.14156;
pi = 3.14; // SyntaxError: invalid assignment to const pi
10. Arrow Functions
Function shorthand with arrow syntax, and more…
[1,2,3].reduce(function(a, b) { return a+b; });
// the syntax
[1,2,3].reduce((a,b) => { console.log("oO"); return a+b; }); // 6
// and even shorter
[1,2,3].reduce((a,b) => a+b);
11. Arrow Functions
… arrow functions share the same context with their surrounding code;
the context can’t be modified via call, apply nor bind.
var team = {
n: "Justice League",
people: ["Batman", "..."],
logMember() {
// arrows have the same context (this) of their surrounding code.
this.people.forEach(p => console.log(p + " is member of the " + this.n));
}
}
team.logMember(); // Batman is member of the Justice League
12. Class sugar
ES6 classes are a simple sugar over the prototype-based OO pattern.
class Animal {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
var pet = new Animal("foo");
pet instanceof Animal // true
pet.getName(); // foo
13. Fish.canSwim(); // true
var fish = new Fish("nemo");
fish instanceof Animal; // true
fish instanceof Fish; // true
fish.getName(); // nemo, the fish.
class Fish extends Animal {
constructor(name){
// execute Animal's constructor
super(name);
this.domain = "water";
}
getName() {
return super.getName() + ", the fish.";
}
static canSwim() {
return true;
}
}
14. Modules
A standard module system for JavaScript.
// utils.js
export function decode(str) { /*...*/ }
export function encode(str) { /*...*/ }
// main.js
import * as helper from 'utils';
utils.encode("foo");
15. Template Strings
A decent string interpolation feature.
// welcome template string
var str = `<p class="${cssClass}">${content}</p>`;
// backtick is ALT+96
// progressive enhancement -_-
var cssClass = "visible";
var content = "Hello, world!";
// old
var str = "<p class='"+cssClass+"'>"+content+"</p>";
16. JavaScript has not private object property.
ECMAScript 6 proposal:
Object can have non-string property.
* At the end, the requisite of privateness for Symbol properties was dropped.
Symbolic properties are just non-enumerable.
A new primitive type was created for this purpose, Symbol.
17. Symbols
A new primitive type.
var s = Symbol(); // Symbol()
typeof s === "symbol" // true
var s1 = Symbol("s1");
var s2 = Symbol("s1");
s1 === s2 // false
18. For ... Of is a new loop construct.
It allows to loop over the values of an Iterable collection.
A collection is Iterable if has a Symbol property Symbol.iterator
that returns an Iterator.
An Iterator is an object with a next method
that returns a { done, value } tuple.
19. Iterators & For ... Of loop
For ... Of loop over values of an iterable collection.
var collection = ["a", "b", "c", "d", "e", "f", "g"];
for(value of collection){
console.log(value);
}
// "a", "b", "c", "d", "e", "f", "g"
20. // custom iteration
collection[Symbol.iterator] = function() {
var index = 0;
return {
next: () => {
if (index < this.length) {
let obj = { done: false, value: this[index] };
index = index + 2;
return obj;
} else {
return { done: true };
}
}
}
}
for(value of collection){ console.log(value); }
// "a", "c", "e", "g"
21. Generator Functions
Are functions which can be interrupted, and then resumed, used to create Iterators.
The yield operator is used to interrupt the execution.
The generator execution resumes when the iterator’s next method is called.
collection[Symbol.iterator] = function* () {
for (let i=0; i<this.length; i++) {
if (i%2 === 0) yield this[i];
}
};
for(value of collection){ console.log(value); }
// "a", "c", "e", "g"
22. Set
An ordered collection with no duplicates.
* Set has a rich prototype that expose method to work with the set instance.
var arr = [1, 2, 2, 3, 3, 3, 4];
var set = new Set(arr);
set; // Set {1, 2, 3, 4}
23. Map
An ordered collection of {key, value} tuples, without duplicated keys.
* Map has a rich prototype that expose method to work with the map instance.
var arr = [ [1, "first"], [1, "one"], [2, "two"] ];
var map = new Map(arr);
map; // Map { 1: "one", 2: "two" }
24. Proxies
Allows to intercept, and re-implement, operations executed over an object.
var obj = { v: 42 };
var traps = {
set(target, propKey, value, receiver) {
console.log('SET '+propKey+'='+value);
target[propKey] = value;
}
};
var proxy = new Proxy(obj, traps);
proxy.v = 0;
// SET v=0
25. Promises
Execute asynchronous code like if it’s synchronous
function getJSON() {
return new Promise(function(resolve, reject) {
setTimeout(function() { resolve('{"value": 42}'); }, 500);
});
}
getJSON().then(function(resp) {
console.log("success", resp);
});
26. Reflection
Reflect is a built-in object that provides methods for interceptable JavaScript operations
var obj = { v: 42 };
var proxy = new Proxy(obj, {
set(target, propKey, value, receiver) {
console.log('SET '+propKey+'='+value);
Reflect.set(target, propKey, value, receiver);
}
});