At the time ES6 was being finalized, the plan was to publish it around late 2014. The draft had been frozen in March 2013, and anything new after that would be pushed to ES7. No browser had implemented the whole specification; Firefox was the most complete. To test the features in Node, you needed 0.11 or newer and the --harmony flag.
JavaScript had been getting richer for years, and ES6 added modules and classes. That makes the language feel less bare than it once did. Whether these additions are a gift or a burden depends on what you want JavaScript to be. Below is a tour of the draft features, with the code kept close to the way it was presented at the time.
Block scope with let and const
let introduces block scope; its lifetime is the {} where it is declared. const creates a constant that cannot be changed or deleted after definition.
> const PI = 3.14;> Object.getOwnPropertyDescriptor(window, PI) Object {value: 3.1415, writable: false, enumerable: true, configurable: false}
Both writable and configurable are false.
Destructuring assignment
CoffeeScript users already know that a value can be assigned like this:
num[1..3] = ["hello", "i'am", "Barret Lee"]
ES6 allows similar multiple-variable assignment:
var [x, y, z] = ["hello", "i'am", "Barret Lee"];
It also works with objects:
var { foo, bar } = { foo: "Barret", bar: "Lee" };
The assignment is pattern-based: as long as the left side corresponds to the right side, the values can be extracted. Newcomers may find this style odd at first.
Array comprehensions
An example:
var a1 = [1, 2, 3, 4];
var a2 = [i * 2 for (i of a1)];
a2 // [2, 4, 6, 8]
This is mostly shorthand. It does not fundamentally add capability; it just simplifies code. CoffeeScript users will probably like it. I still find it awkward. The example above is equivalent to:
var a1 = [1, 2, 3, 4];
var a2 = a1.map(function (i) { return i * 2 });
Unless there is a limit on code length, I would not use the comprehension form.
String extensions
These changes patch JavaScript's handling of double-byte UTF-16 characters. The added functions fix different edge cases. This area matters for ArrayBuffer data types and typed arrays such as Float64Array and Uint32Array.
codePointAt
JavaScript strings are stored as UTF-16 code units. Most characters in common use fall inside Unicode 0x10000 and map directly to their UTF-16 units. Characters outside that range need two UTF-16 units:
alert("𠐀".length); //2
The string length is not a character count; it is the number of UTF-16 units. codePointAt handles characters stored in four bytes correctly:
var s = "𠐀二";
s.codePointAt(0);
It parses both characters in s correctly, effectively switching the storage unit between 2 and 4.
fromCodePoint
String.fromCodePoint is the counterpart to String.fromCharCode for these code points; it can resolve the same range intelligently.
Unicode notation
A Unicode character can normally be written with \u0000-\uFFFF. Characters outside that range, such as \u10000, could not be parsed correctly before. ES6 allows braces:
#\u{10000}
With the braces, code points beyond FFFF can be parsed normally.
The u regular-expression flag
/^.$/.test("𠐀") // false
/^..$/.test("𠐀") // true
/^.$/u.test("𠐀") // true
The three tests show the difference.
Small string helpers
contains(), startsWith(), endsWith(), and repeat() are direct String extensions; their names explain their purpose.
Template strings
// Embedding variables in a string
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
var x = 1;
var y = 2;
console.log(`${ x } + ${ y } = ${ x + y}`) // "1 + 2 = 3"
Template strings are convenient with template tags, although custom tags already make the feature less special. A template tag can work with a <template> element like this:
<div id="test">
<x-from>DOM文档</x-from>
<x-name>test元素</x-name>
</div>
<template id="temp">
我是来自 <strong><content select="x-from"></content></strong> 中的 <strong><content select="x-name"></content></strong> 的数据。
</template>
<script>
var root = test.webkitCreateShadowRoot();
root.appendChild(document.importNode(temp.content));
</script>
Number extensions
0b111110111 === 503 // true
0o767 === 503 // true
The 0b and 0o prefixes represent binary and octal values. ES6 also adds Number.isFinite(), Number.isNaN(), Number.parseInt(), Number.parseFloat(), and Number.isInteger(). Details are available on MDN.
Object extensions
ES5.1 already made Object more flexible with methods such as create, defineProperty, and freeze. ES6 keeps going.
Object.is()
Object.is() compares two arguments strictly. It is close to ===, except that +0 is not equal to -0, and NaN is equal to itself:
+0 === -0 //true
NaN === NaN // false
Object.is(+0, -0) // false
Object.is(NaN, NaN) // true
The proto property
obj.__proto__ = otherObj;
Browsers implemented this long before it was standardized. It was also used to detect Internet Explorer:
var isIE = "__proto__" in {} ? false : true;
Enhanced object literals
var Person = {
name: 'Barret Lee',
// Equivalent to birth: birth
birth,
// Equivalent to hello: function ()...
hello() {
console.log('My Name Is', this.name);
}
};
Computed keys
var name = "my name";
var Me = {
[name]: "Barret Lee",
"name": "李靖"
};
Me[name] // "Barret Lee"
Me["my name"] // "Barret Lee"
Me["name"] // "李靖"
This is convenient, but it is easy to get wrong; the example above can make your head spin.
Symbol
Symbol separates data by type. It is a primitive value, not an object, and works well as an identifier.
Proxy
Proxy is a built-in proxy tool that adds a barrier around object operations:
var plain = { name : "Barret Lee" };
var proxy = new Proxy(plain, {
get: function(target, property) {
return property in target ? target[property] : "我擦";
}
});
proxy.name // "Barret Lee"
proxy.title // "我擦"
Proxy(target, handler) accepts a handler that can define get, set, has, hasOwn, keys, and other methods.
Function extensions
Default parameters
function Point(x = 0, y = 0) {
this.x = x;
this.y = y;
}
var p = new Point(); // p = { x:0, y:0 }
Initializing parameters this way exposes a more flexible interface and makes functions easier to extend.
Rest parameters (...)
function add(...values) {
let sum = 0;
for (var val of values) {
sum += val;
}
return sum;
}
add(1, 2 ,3) // 6
The values collection is traversed with for...of.
Arrow functions (=>)
CoffeeScript users will recognize this:
var f = (a, b) => {return a + b};
Like several other additions here, it is mostly syntax sugar rather than a new capability.
Set, Map, and WeakMap
Set
A Set is roughly an array with no duplicate values, or an array backed by a hash table.
var items = new Set([1,2,3,4,5,5,5,5]);
for (i of s) {console.log(i)} // 2 3 4 5
Iteration uses val of values. A Set does not inherit Array methods. Its own methods include:
size(): returns the total number of members.add(value): adds a value.delete(value): deletes a value.has(value): returns a boolean indicating whether the value is a member.clear(): removes all members.
To turn it into an array:
var items = new Set([1, 2, 3, 4, 5]);
var array = Array.from(items);
Map
A Map is a "super-object": its keys can be strings or other types, including objects.
var m = new Map();
o = {p: "Hello World"};
m.set(o, "content")
console.log(m.get(o)) // "content"
Its methods are similar to Set:
size: returns the total number of members.set(key, value): sets a key-value pair.get(key): reads a key.has(key): returns a boolean indicating whether a key exists in theMap.delete(key): deletes a key.clear(): removes all members.keys(): returns an iterator over keys.values(): returns an iterator over values.entries(): returns an iterator over all members.
WeakMap
If Map is a super-object, WeakMap is a weak super-object. Its keys must be objects other than null. It exists to make garbage collection easier.
Iterators
Compared with an array, an iterator manages data more compactly and offers stronger control. It is likely to become a common JavaScript tool.
function idMaker(){
var index = 0;
return {
next: function(){
return {value: index++, done: false};
}
}
}
var it = idMaker();
it.next().value // '0'
it.next().value // '1'
it.next().value // '2'
Any object with a next method can be traversed with a for...of loop:
for (var n of it) {
if (n > 5) break;
console.log(n);
}
Generator functions
A Generator is a modified Iterator. Each yield adds a next() node. A Generator is declared with a * before the function name:
function * foo( input ) {
var res = yield input;
}
Usage:
function * foo( input ) {
var res = yield input;
}
var g = foo(10);
g.next(); // { value: 10, done: false }
g.next(); // { value: undefined, done: true }
Because every yield adds a next() node, multiple yields behave like this:
function* G() {
yield 'Barret';
yield 'Lee';
}
var g = G();
g.next(); // "Barret"
g.next(); // "Lee"
g.next(); // undefined
g.next(); // Error: Generator has already finished
I prefer Generators to plain Iterators.
Promises
After ES6 included Promises in the specification, many browsers implemented an API based on Promise/A+. A Promise represents asynchronous work in a flat form and avoids callback hell, the deeply nested callback style. Each task has three states: pending, fulfilled, and rejected.
- Pending can move in one direction to fulfilled; this is called resolve, and the corresponding method is
deferred.resolve(promiseOrValue). - Pending can also move in one direction to rejected; this is called reject, and the corresponding method is
deferred.reject(reason). - While pending, a task can report execution information such as progress through
deferred.notify(update). - State transitions happen once. Once a task leaves pending, it moves on to the next task.
Classes and modules
Class
A class is an object template:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '('+this.x+', '+this.y+')';
}
}
It immediately feels like C++ or Java. Classes can use extends for inheritance:
class ColorPoint extends Point {
constructor(x, y, color) {
super(x, y); // same as super.constructor(x, y)
this.color = color;
}
toString() {
return this.color+' '+super();
}
}
Module
ES6 allows independent JavaScript files to act as modules, so one script file can call another. That makes modular programming possible.
// circle.js
export function area(radius) {
return Math.PI * radius * radius;
}
export function circumference(radius) {
return 2 * Math.PI * radius;
}
To import functions from circle.js:
// main.js
import { area, circumference } from 'circle';
console.log("圆面积:" + area(4));
console.log("圆周长:" + circumference(14));
To import the whole module:
// main.js
module circle from 'circle';
console.log("圆面积:" + circle.area(4));
console.log("圆周长:" + circle.circumference(14));
Module inheritance uses this command:
// other.js
export * from 'circle';
This is very useful, but it also means that plain, simple JavaScript is no longer as simple as it used to be.