Ecmascript 6
Arrows
- A new form for creating anonymous functions
- They share the same scope as the surrounding block
- AKA: 'This' is the same outside and inside
// ES6
odds = evens.map(v => v + 1)
nums = evens.map((v, i) => v + i)
// ES5
odds = evens.map(function (v) { return v + 1; });
nums = evens.map(function (v, i) { return v + i; });Classes
- Classes support prototype-based inheritance, super calls, instance and static methods and constructors.
class SkinnedMesh extends THREE.Mesh {
constructor(geometry, materials) {
super(geometry, materials);
this.idMatrix = SkinnedMesh.defaultMatrix();
}
update(camera) {
//...
super.update();
}
get boneCount() {
return this.bones.length;
}
set matrixType(matrixType) {
this.idMatrix = SkinnedMesh[matrixType]();
}
static defaultMatrix() {
return new THREE.Matrix4();
}
}Block Scoping
- Block scoping are new forms of declaration for defining variables scoped to a single block, as opposed to variables declared with var which have a function-level scope.
Let
- We can use let in-place of var to define block-local variables without having to worry about them clashing with variables defined elsewhere within the same function body.
for (var i = 0; i < 3; i++) {
let j = i * i;
console.log(j);
}
console.log(j); // => error, j is undefinedConst
- const follows the same rules as let, except that the value is immutable so we can only assign to it once.
const PI = 3.14159265359;
PI = 0; // => Error: PI" is read-onlyDefault Args
- It is now possible to set default argument values inline, rather than checking for undefined inside of the function's scope.
function f(x, y=42) {
return x + y;
}
// f(2) === 44Default Spread
- Ruby splat operator
function f(x, y, z) {
return x + y + z;
}
// Pass each elem of array as argument
//f(...[1,2,3]) == 6Template Strings
- Multi Line Strings
// Multiline strings
`In JavaScript this is
not legal.Template Strings
- String Interpolation
// String interpolation
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`Template Strings
- String Interpolation
// Construct an HTTP request prefix is used to interpret
// the replacements and construction
GET`http://foo.org/bar?a=${a}&b=${b}
Content-Type: application/json
X-Credentials: ${credentials}
{ "foo": ${foo},
"bar": ${bar}}`(myOnReadyStateChangeHandler);Destructuring
- Allows assignment of multiple parts of an object to be assigned to different variables at once.
var ball = {
position: [0, 0],
radius: 20,
elasticity: 1,
deflated: false,
};
var [x, y] = ball.position;
var { radius, elasticity, deflated } = ball;
// x === 0
// y === 0
// radius === 20
// elasticity === 1
// deflated === falseLooping
- For..In
for (var n of fibonacci) {
// truncate the sequence at 1000
if (n > 1000)
break;
console.log(n);
}Looping
- Iterator
function RangeIterator(min, max) {
this[Symbol.iterator] = function () {
var current = min;
return {
next: function () {
current++;
return {
done: current == max,
value: current,
};
}
}
};
}Modules
- Implicitly async model – no code executes until requested modules are available and processed.
- Default functions are exported automatically
// lib/math.js
export function sum(x, y) {
return x + y;
}
export var pi = 3.141593;
export default function assert(expression) {
return expression == true;
}
// app.js
import * as math from "lib/math";
alert("2π = " + math.sum(math.pi, math.pi));
// otherApp.js
import {sum, pi} from "lib/math";
alert("2π = " + sum(pi, pi));Data Structures
- Sets
// Sets
var s = new Set();
s.add("hello").add("goodbye").add("hello");
s.size === 2;
s.has("hello") === true;Data Structures
- Maps
// Maps
var m = new Map();
m.set("hello", 42);
m.set(s, 34);
m.get(s) == 34;Helpers
- ECMASCRIPT meet Ruby
"abcde".includes("cd") // true
"abc".repeat(3) // "abcabcabc"
[1, 2, 3].find(x => x == 3) // 3
[1, 2, 3].findIndex(x => x == 2) // 1
["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"]
["a", "b", "c"].keys() // iterator 0, 1, 2
["a", "b", "c"].values() // iterator "a", "b", "c"Promises
- Promises are now in ES6 by default
function timeout(duration = 0) {
return new Promise((resolve, reject) => {
setTimeout(resolve, duration);
})
}
var p = timeout(1000).then(() => {
return timeout(2000);
}).then(() => {
throw new Error("hmm");
}).catch(err => {
return Promise.all([timeout(100), timeout(200)]);
})ES6
By Davide Curletti
ES6
- 784