Some ramblings on ES6.
http://exploringjs.com/es6.html
Block Scoped Variables
let
const
From IIFEs to blocks
Now can just do:
{ // open block
let tmp = ···;
···
} // close block
From concatenating strings to template literals
String interpolation
Instead of concatenation
function printCoord(x, y) {
console.log(`(${x}, ${y})`);
}
Multi-line strings
ES6 template literals can span multiple lines:
const HTML5_SKELETON = `
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
</html>`;
From function expressions to arrow functions
Arrow functions can be used, which don’t shadow this
.
Previously this:
button.addEventListener('click', function () {
console.log('CLICK');
_this.handleClick(); // (B)
});
Now this:
button.addEventListener('click', () => {
console.log('CLICK');
this.handleClick(); // (A)
});
Arrow functions can also be used for callbacks:
Previously this:
var squares = arr.map(function (x) { return x * x });
Now this:
const squares = arr.map(x => x * x);
Handling multiple return values
Multiple return values via arrays
Multiple return values via objects
From for to forEach() to for-of
ES5
arr.forEach(function (elem) {
console.log(elem);
});
ES6 now has for of loop.
Handling parameter default values
ES6 is much better:
function foo(x=0, y=0) {
Handling named parameters
Rest/ Gather
Extra parameters get gathered into an array.
function format(pattern, ...args) {
From function expressions in object literals to method definitions
ES6 has method definitions:
const obj = {
foo() {
···
},
bar() {
this.foo();
},
}
From constructors to classes
This is now possible in ES6
class Person {
constructor(name) {
this.name = name;
}
describe() {
return 'Person called '+this.name;
}
}
Derived classes
You can now subclass:
class Employee extends Person {
From custom error constructors to subclasses of Error
From objects to Maps
New String Methods
New Array Methods
Promises
https://scotch.io/tutorials/javascript-promises-for-dummies
States
1, pending 2, resolved 3, rejected
Analogy, mum promises a new phone.
/* ES5 */
var isMomHappy = false;
// Promise
var willIGetNewPhone = new Promise(
function (resolve, reject) {
if (isMomHappy) {
var phone = {
brand: 'Samsung',
color: 'black'
};
resolve(phone); // fulfilled
} else {
var reason = new Error('mom is not happy');
reject(reason); // reject
}
}
);
You need to call resolve with your success value when the result is succesfull. You need to call reject with your failure value when the result is unsuccesfull.
Promises are asynchronous.