Install node using nvm
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.29.0/install.sh | bash
nvm install 5.1
nvm alias default 5.1
Add 'use strict;'
directive at the top of the file to enable ES6 features.
- ES7 in 7 Days
- Exploring ES6 (Book)
- ES6 - explanation of ES6 features by Nick Justice
Objects and Prototypes
var foo = {} // is the same as...
var foo = new Object()
function Car(model, miles) {
this.model = model
this.miles = miles
}
var x = new Car("Tesla Model X", 0)
x.model // Tesla Model X
x.miles // 0
x.miles += 10
// Can also access like a hash
x["miles"] // 10
Functions on an object can be declared in two ways:
function Car(...) { ... }
function Car.prototype.drive(distance) {
this.miles += distance
}
// Or...
function Car(model, miles) {
this.model = model
this.miles = miles
this.drive = function(distance) {
this.miles += distance
}
}
Arrays
var a = ["a", "b", "c"]
a.length // 3
// length is 1 more that highest index
a[4] = "e"
a // ['a', 'b', 'c', , 'e']
a.length // 5
a[3] //undefined
Destructuring in ES6
var [a, b, c] = [1, 2, 3]
var x = { foo: 2, bar: 4, baz: 8 }
var { foo: a, bar: b } = x
// Now a = 2, b = 4. Wow!
(ES6 and 7, the future of JS - Brendan Eich)
Class syntax
class Employee {
constructor(fName, lName) {
this.fName = fName;
this.lName = lName;
}
fullName() {
return `${this.fName} ${this.lName}`;
}
calculateSalary() {
return 10000;
}
}
// Inheritance
class Manager extends Employee {
constructor(fName, lName, bonus) {
this.fName = fName;
this.lName = lName;
this.bonus = bonus;
}
calculateSalary() {
super.calculateSalary() + this.bonus;
}
}
Iterators
let powersOfTwo = {
[Symbol.iterator]() {
let power = -1;
return {
next() {
return { done: false, value: Math.pow(2, ++power) }
}
}
}
}
for(let n of powersOfTwo) {
if (n > 1024) break;
console.log(n);
}
Generators
// Similar to iterators
let powersOfTwo = {
*[Symbol.iterator]() {
let power = -1;
while(true) yield Math.pow(2, ++power);
}
}
for(let n of powersOfTwo) {
if (n > 1024) break;
console.log(n);
}