ES6 NEW FEATURES
- development
- javascript
Scope
/* Lexical scope (this) in arrow is same as surrounding scope,
but function scope is a new scope */
var pets = ['cat', 'dog', 'bird', 'fish'];
var a = pets.map((p) => p.length);
console.log(a);
Classes
ES6 classes are simply syntactical sugar over the prototype-based Object Orientation pattern. Having a single convenient declarative form makes class patterns easier to use. Classes support prototype-based inheritance, super calls, instance and static methods and constructors.
class Vehicle {
name = 'Vehicle';
constructor(doors, wheels) {
this.doors = doors;
this.wheels = wheels;
this.engineState = 'stopped';
console.log(
'Contructed a vehicle with ' +
this.doors +
' doors and ' +
this.wheels +
' wheels.',
);
}
startEngine() {
this.engineState = 'started';
console.log('Engine started ..');
}
stopEngine() {
this.engineState = 'stopped';
console.log('Engine stopped ..');
}
drive() {
if (this.engineState == 'started') {
console.log('driving ..');
} else {
console.log('start the engine first!');
}
}
static showName() {
console.log(this.name);
}
static get instance() {
if (!Vehicle) {
return new Vehicle();
}
return this;
}
}
class Car extends Vehicle {
name = 'car';
constructor(doors, wheels) {
super(doors, wheels);
}
static showName() {
console.log(this.name);
}
}
Vehicle.instance.showName();
var car = new Car(2, 4);
car.startEngine();
Let & Const
They are Block-scoped binding constructs. let has block scope unlike var which has lexical scope.
function run() {
let it = 'be';
// block scope
{
let it = 'go';
console.log(it); // go
}
console.log(it); // be
}
run();
Single Assignment
function run() {
const it = 'be';
it = 'go'; // error: trying to override 'it' constant
console.log(it);
}
run();
Symbols
Symbols enable access control for object state. A symbol is a unique and immutable data type and may be used as an identifier for object properties.
Symbols are a new primitive type. Optional name parameter used in debugging - but is not part of identity. Symbols are unique, but not private since they are exposed via reflection features like Object.getOwnPropertySymbols.
var count = Symbol('count');
class People {
constructor() {
this[count] = 0;
}
add(item) {
this[this[count]] = item;
this[count]++;
}
static sizeOf(instance) {
return instance[count];
}
}
var people = new People();
console.log(Symbol('count') === Symbol('count')); // false
console.log(People.sizeOf(people)); // 0
people.add('John Smith');
console.log(People.sizeOf(people)); // 1
Generators
Generators are functions that can be paused(exit) and resumed(re-enter). Their context (variable bindings) will be saved across re-entrances. These can be helpful for iterators, asynchronous programming, etc.
Execution
var fib = fibonacci();
function* fibonacci() {
let val1 = 0,
val2 = 1,
swap;
yield val1;
yield val2;
while (true) {
swap = val1 + val2;
val1 = val2;
val2 = swap;
yield swap;
}
}
function run() {
let i = 0;
while (i < 10) {
console.log(fib.next().value);
i++;
}
}
run();
Iterators & For..of
Iterator enables JavaScript objects to define custom iteration like CLR IEnumerable or Java Iterable.
This will generalize for..in to custom iterator-based iteration with for..of.
@@iterator
var foo = 'foo',
iter1,
iter2,
iter3,
iter4,
iterator;
iterator = foo[Symbol.iterator]();
iter1 = iterator.next();
iter2 = iterator.next();
iter3 = iterator.next();
iter4 = iterator.next();
console.log(iter1); // done: false, value: "f"
console.log(iter2); // done: false, value: "o"
console.log(iter3); // done: false, value: "o"
console.log(iter4); // done: true, value: undefined
The for...of statement creates a loop Iterating over iterable objects (including Array, Map, Set, arguments object and so on),
invoking a custom iteration hook with statements to be executed for the value of each distinct property.
var fib = fibonacci();
function* fibonacci() {
let val1 = 0,
val2 = 1,
swap;
yield val1;
yield val2;
while (true) {
swap = val1 + val2;
val1 = val2;
val2 = swap;
yield swap;
}
}
for (var n of fib) {
// truncate the sequence at 1000
if (n > 1000) break;
console.log(n);
}
run(); // 1 1 2 3 5 8 13 21 34 55 89 144 233
Promises
Promises are a library for asynchronous programming. Promises are a first-class representation of a value that may be made available in the future. Promises are used in many existing JavaScript libraries.
ES6 Promise API
Promises are a pattern that helps with asynchronous programming, functions that return their results asynchronously.
function timeout(duration = 0) {
return new Promise((resolve, reject) => {
setTimeout(resolve, duration);
console.log('Timed out.. ' + duration);
});
}
var p = timeout(1000)
.then(() => {
return timeout(2000);
})
.then(() => {
throw new Error('uh oh!');
})
.catch((err) => {
return Promise.all([timeout(100), timeout(200)]);
});
Destructuring
The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.
Syntax