Learn ES2015

Learn ES2015 - 图1es6features

This document was originally taken from Luke Hoban’s excellent es6features repo. Go give it a star on GitHub!

Learn ES2015 - 图2REPL

Be sure to try these features out in the online REPL.

Introduction

ECMAScript 2015 is an ECMAScript standard that was ratified in June 2015.

ES2015 is a significant update to the language, and the first major update to the language since ES5 was standardized in 2009. Implementation of these features in major JavaScript engines is underway now.

See the ES2015 standard for full specification of the ECMAScript 2015 language.

ECMAScript 2015 Features

Arrows and Lexical This

Arrows are a function shorthand using the => syntax. They are syntactically similar to the related feature in C#, Java 8 and CoffeeScript. They support both expression and statement bodies. Unlike functions, arrows share the same lexical this as their surrounding code. If an arrow is inside another function, it shares the “arguments” variable of its parent function.

JavaScript

  1. // Expression bodies
  2. var odds = evens.map(v => v + 1);
  3. var nums = evens.map((v, i) => v + i);
  4. // Statement bodies
  5. nums.forEach(v => {
  6. if (v % 5 === 0)
  7. fives.push(v);
  8. });
  9. // Lexical this
  10. var bob = {
  11. _name: "Bob",
  12. _friends: [],
  13. printFriends() {
  14. this._friends.forEach(f =>
  15. console.log(this._name + " knows " + f));
  16. }
  17. };
  18. // Lexical arguments
  19. function square() {
  20. let example = () => {
  21. let numbers = [];
  22. for (let number of arguments) {
  23. numbers.push(number * number);
  24. }
  25. return numbers;
  26. };
  27. return example();
  28. }
  29. square(2, 4, 7.5, 8, 11.5, 21); // returns: [4, 16, 56.25, 64, 132.25, 441]

Classes

ES2015 classes are syntactic sugar over the prototype-based OO pattern. Having a single convenient declarative form makes class patterns easier to use, and encourages interoperability. Classes support prototype-based inheritance, super calls, instance and static methods and constructors.

JavaScript

  1. class SkinnedMesh extends THREE.Mesh {
  2. constructor(geometry, materials) {
  3. super(geometry, materials);
  4. this.idMatrix = SkinnedMesh.defaultMatrix();
  5. this.bones = [];
  6. this.boneMatrices = [];
  7. //...
  8. }
  9. update(camera) {
  10. //...
  11. super.update();
  12. }
  13. static defaultMatrix() {
  14. return new THREE.Matrix4();
  15. }
  16. }

Enhanced Object Literals

Object literals are extended to support setting the prototype at construction, shorthand for foo: foo assignments, defining methods and making super calls. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences.

JavaScript

  1. var obj = {
  2. // Sets the prototype. "__proto__" or '__proto__' would also work.
  3. __proto__: theProtoObj,
  4. // Computed property name does not set prototype or trigger early error for
  5. // duplicate __proto__ properties.
  6. ['__proto__']: somethingElse,
  7. // Shorthand for ‘handler: handler’
  8. handler,
  9. // Methods
  10. toString() {
  11. // Super calls
  12. return "d " + super.toString();
  13. },
  14. // Computed (dynamic) property names
  15. [ "prop_" + (() => 42)() ]: 42
  16. };

Learn ES2015 - 图3caution

The **proto** property requires native support, and was deprecated in previous ECMAScript versions. Most engines now support the property, but some do not. Also, note that only web browsers are required to implement it, as it’s in Annex B. It is available in Node.

Template Strings

Template strings provide syntactic sugar for constructing strings. This is similar to string interpolation features in Perl, Python and more. Optionally, a tag can be added to allow the string construction to be customized, avoiding injection attacks or constructing higher level data structures from string contents.

JavaScript

  1. // Basic literal string creation
  2. `This is a pretty little template string.`
  3. // Multiline strings
  4. `In ES5 this is
  5. not legal.`
  6. // Interpolate variable bindings
  7. var name = "Bob", time = "today";
  8. `Hello ${name}, how are you ${time}?`
  9. // Unescaped template strings
  10. String.raw`In ES5 "\n" is a line-feed.`
  11. // Construct an HTTP request prefix is used to interpret the replacements and construction
  12. GET`http://foo.org/bar?a=${a}&b=${b}
  13. Content-Type: application/json
  14. X-Credentials: ${credentials}
  15. { "foo": ${foo},
  16. "bar": ${bar}}`(myOnReadyStateChangeHandler);

Destructuring

Destructuring allows binding using pattern matching, with support for matching arrays and objects. Destructuring is fail-soft, similar to standard object lookup foo["bar"], producing undefined values when not found.

JavaScript

  1. // list matching
  2. var [a, ,b] = [1,2,3];
  3. a === 1;
  4. b === 3;
  5. // object matching
  6. var { op: a, lhs: { op: b }, rhs: c }
  7. = getASTNode()
  8. // object matching shorthand
  9. // binds `op`, `lhs` and `rhs` in scope
  10. var {op, lhs, rhs} = getASTNode()
  11. // Can be used in parameter position
  12. function g({name: x}) {
  13. console.log(x);
  14. }
  15. g({name: 5})
  16. // Fail-soft destructuring
  17. var [a] = [];
  18. a === undefined;
  19. // Fail-soft destructuring with defaults
  20. var [a = 1] = [];
  21. a === 1;
  22. // Destructuring + defaults arguments
  23. function r({x, y, w = 10, h = 10}) {
  24. return x + y + w + h;
  25. }
  26. r({x:1, y:2}) === 23

Default + Rest + Spread

Callee-evaluated default parameter values. Turn an array into consecutive arguments in a function call. Bind trailing parameters to an array. Rest replaces the need for arguments and addresses common cases more directly.

JavaScript

  1. function f(x, y=12) {
  2. // y is 12 if not passed (or passed as undefined)
  3. return x + y;
  4. }
  5. f(3) == 15

JavaScript

  1. function f(x, ...y) {
  2. // y is an Array
  3. return x * y.length;
  4. }
  5. f(3, "hello", true) == 6

JavaScript

  1. function f(x, y, z) {
  2. return x + y + z;
  3. }
  4. // Pass each elem of array as argument
  5. f(...[1,2,3]) == 6

Let + Const

Block-scoped binding constructs. let is the new var. const is single-assignment. Static restrictions prevent use before assignment.

JavaScript

  1. function f() {
  2. {
  3. let x;
  4. {
  5. // this is ok since it's a block scoped name
  6. const x = "sneaky";
  7. // error, was just defined with `const` above
  8. x = "foo";
  9. }
  10. // this is ok since it was declared with `let`
  11. x = "bar";
  12. // error, already declared above in this block
  13. let x = "inner";
  14. }
  15. }

Iterators + For..Of

Iterator objects enable custom iteration like CLR IEnumerable or Java Iterable. Generalize for..in to custom iterator-based iteration with for..of. Don’t require realizing an array, enabling lazy design patterns like LINQ.

JavaScript

  1. let fibonacci = {
  2. [Symbol.iterator]() {
  3. let pre = 0, cur = 1;
  4. return {
  5. next() {
  6. [pre, cur] = [cur, pre + cur];
  7. return { done: false, value: cur }
  8. }
  9. }
  10. }
  11. }
  12. for (var n of fibonacci) {
  13. // truncate the sequence at 1000
  14. if (n > 1000)
  15. break;
  16. console.log(n);
  17. }

Iteration is based on these duck-typed interfaces (using TypeScript type syntax for exposition only):

  1. interface IteratorResult {
  2. done: boolean;
  3. value: any;
  4. }
  5. interface Iterator {
  6. next(): IteratorResult;
  7. }
  8. interface Iterable {
  9. [Symbol.iterator](): Iterator
  10. }

Learn ES2015 - 图4Support via polyfill

In order to use Iterators you must include the Babel polyfill.

Generators

Generators simplify iterator-authoring using function* and yield. A function declared as function* returns a Generator instance. Generators are subtypes of iterators which include additional next and throw. These enable values to flow back into the generator, so yield is an expression form which returns a value (or throws).

Note: Can also be used to enable ‘await’-like async programming, see also ES7 await proposal.

JavaScript

  1. var fibonacci = {
  2. [Symbol.iterator]: function*() {
  3. var pre = 0, cur = 1;
  4. for (;;) {
  5. var temp = pre;
  6. pre = cur;
  7. cur += temp;
  8. yield cur;
  9. }
  10. }
  11. }
  12. for (var n of fibonacci) {
  13. // truncate the sequence at 1000
  14. if (n > 1000)
  15. break;
  16. console.log(n);
  17. }

The generator interface is (using TypeScript type syntax for exposition only):

  1. interface Generator extends Iterator {
  2. next(value?: any): IteratorResult;
  3. throw(exception: any);
  4. }

Learn ES2015 - 图5Support via polyfill

In order to use Generators you must include the Babel polyfill.

Comprehensions

Removed in Babel 6.0

Unicode

Non-breaking additions to support full Unicode, including new unicode literal form in strings and new RegExp u mode to handle code points, as well as new APIs to process strings at the 21bit code points level. These additions support building global apps in JavaScript.

JavaScript

  1. // same as ES5.1
  2. "𠮷".length == 2
  3. // new RegExp behaviour, opt-in ‘u’
  4. "𠮷".match(/./u)[0].length == 2
  5. // new form
  6. "\u{20BB7}" == "𠮷"
  7. "𠮷" == "\uD842\uDFB7"
  8. // new String ops
  9. "𠮷".codePointAt(0) == 0x20BB7
  10. // for-of iterates code points
  11. for(var c of "𠮷") {
  12. console.log(c);
  13. }

Modules

Language-level support for modules for component definition. Codifies patterns from popular JavaScript module loaders (AMD, CommonJS). Runtime behaviour defined by a host-defined default loader. Implicitly async model – no code executes until requested modules are available and processed.

JavaScript

  1. // lib/math.js
  2. export function sum(x, y) {
  3. return x + y;
  4. }
  5. export var pi = 3.141593;

JavaScript

  1. // app.js
  2. import * as math from "lib/math";
  3. console.log("2π = " + math.sum(math.pi, math.pi));

JavaScript

  1. // otherApp.js
  2. import {sum, pi} from "lib/math";
  3. console.log("2π = " + sum(pi, pi));

Some additional features include export default and export *:

JavaScript

  1. // lib/mathplusplus.js
  2. export * from "lib/math";
  3. export var e = 2.71828182846;
  4. export default function(x) {
  5. return Math.exp(x);
  6. }

JavaScript

  1. // app.js
  2. import exp, {pi, e} from "lib/mathplusplus";
  3. console.log("e^π = " + exp(pi));

Learn ES2015 - 图6Module Formatters

Babel can transpile ES2015 Modules to several different formats including Common.js, AMD, System, and UMD. You can even create your own. For more details see the modules docs.

Module Loaders

Learn ES2015 - 图7Not part of ES2015

This is left as implementation-defined within the ECMAScript 2015 specification. The eventual standard will be in WHATWG’s Loader specification, but that is currently a work in progress. What is below is from a previous ES2015 draft.

Module loaders support:

  • Dynamic loading
  • State isolation
  • Global namespace isolation
  • Compilation hooks
  • Nested virtualization

The default module loader can be configured, and new loaders can be constructed to evaluate and load code in isolated or constrained contexts.

JavaScript

  1. // Dynamic loading – ‘System’ is default loader
  2. System.import("lib/math").then(function(m) {
  3. alert("2π = " + m.sum(m.pi, m.pi));
  4. });
  5. // Create execution sandboxes – new Loaders
  6. var loader = new Loader({
  7. global: fixup(window) // replace ‘console.log’
  8. });
  9. loader.eval("console.log(\"hello world!\");");
  10. // Directly manipulate module cache
  11. System.get("jquery");
  12. System.set("jquery", Module({$: $})); // WARNING: not yet finalized

Learn ES2015 - 图8Additional polyfill needed

Since Babel defaults to using common.js modules, it does not include the polyfill for the module loader API. Get it here.

Learn ES2015 - 图9Using Module Loader

In order to use this, you’ll need to tell Babel to use the system module formatter. Also be sure to check out System.js.

Map + Set + WeakMap + WeakSet

Efficient data structures for common algorithms. WeakMaps provides leak-free object-key’d side tables.

JavaScript

  1. // Sets
  2. var s = new Set();
  3. s.add("hello").add("goodbye").add("hello");
  4. s.size === 2;
  5. s.has("hello") === true;
  6. // Maps
  7. var m = new Map();
  8. m.set("hello", 42);
  9. m.set(s, 34);
  10. m.get(s) == 34;
  11. // Weak Maps
  12. var wm = new WeakMap();
  13. wm.set(s, { extra: 42 });
  14. wm.size === undefined
  15. // Weak Sets
  16. var ws = new WeakSet();
  17. ws.add({ data: 42 });
  18. // Because the added object has no other references, it will not be held in the set

Learn ES2015 - 图10Support via polyfill

In order to support Maps, Sets, WeakMaps, and WeakSets in all environments you must include the Babel polyfill.

Proxies

Proxies enable creation of objects with the full range of behaviors available to host objects. Can be used for interception, object virtualization, logging/profiling, etc.

JavaScript

  1. // Proxying a normal object
  2. var target = {};
  3. var handler = {
  4. get: function (receiver, name) {
  5. return `Hello, ${name}!`;
  6. }
  7. };
  8. var p = new Proxy(target, handler);
  9. p.world === "Hello, world!";

JavaScript

  1. // Proxying a function object
  2. var target = function () { return "I am the target"; };
  3. var handler = {
  4. apply: function (receiver, ...args) {
  5. return "I am the proxy";
  6. }
  7. };
  8. var p = new Proxy(target, handler);
  9. p() === "I am the proxy";

There are traps available for all of the runtime-level meta-operations:

JavaScript

  1. var handler =
  2. {
  3. // target.prop
  4. get: ...,
  5. // target.prop = value
  6. set: ...,
  7. // 'prop' in target
  8. has: ...,
  9. // delete target.prop
  10. deleteProperty: ...,
  11. // target(...args)
  12. apply: ...,
  13. // new target(...args)
  14. construct: ...,
  15. // Object.getOwnPropertyDescriptor(target, 'prop')
  16. getOwnPropertyDescriptor: ...,
  17. // Object.defineProperty(target, 'prop', descriptor)
  18. defineProperty: ...,
  19. // Object.getPrototypeOf(target), Reflect.getPrototypeOf(target),
  20. // target.__proto__, object.isPrototypeOf(target), object instanceof target
  21. getPrototypeOf: ...,
  22. // Object.setPrototypeOf(target), Reflect.setPrototypeOf(target)
  23. setPrototypeOf: ...,
  24. // Object.keys(target)
  25. ownKeys: ...,
  26. // Object.preventExtensions(target)
  27. preventExtensions: ...,
  28. // Object.isExtensible(target)
  29. isExtensible :...
  30. }

Learn ES2015 - 图11Unsupported feature

Due to the limitations of ES5, Proxies cannot be transpiled or polyfilled. See support in various JavaScript engines.

Symbols

Symbols enable access control for object state. Symbols allow properties to be keyed by either string (as in ES5) or symbol. Symbols are a new primitive type. Optional name parameter used in debugging - but is not part of identity. Symbols are unique (like gensym), but not private since they are exposed via reflection features like Object.getOwnPropertySymbols.

JavaScript

  1. (function() {
  2. // module scoped symbol
  3. var key = Symbol("key");
  4. function MyClass(privateData) {
  5. this[key] = privateData;
  6. }
  7. MyClass.prototype = {
  8. doStuff: function() {
  9. ... this[key] ...
  10. }
  11. };
  12. // Limited support from Babel, full support requires native implementation.
  13. typeof key === "symbol"
  14. })();
  15. var c = new MyClass("hello")
  16. c["key"] === undefined

Learn ES2015 - 图12Limited support via polyfill

Limited support requires the Babel polyfill. Due to language limitations, some features can’t be transpiled or polyfilled. See core.js’s caveats section for more details.

Subclassable Built-ins

In ES2015, built-ins like Array, Date and DOM Elements can be subclassed.

JavaScript

  1. // User code of Array subclass
  2. class MyArray extends Array {
  3. constructor(...args) { super(...args); }
  4. }
  5. var arr = new MyArray();
  6. arr[1] = 12;
  7. arr.length == 2

Learn ES2015 - 图13Partial support

Built-in subclassability should be evaluated on a case-by-case basis as classes such as HTMLElement can be subclassed while many such as Date, Array and Error cannot be due to ES5 engine limitations.

Math + Number + String + Object APIs

Many new library additions, including core Math libraries, Array conversion helpers, and Object.assign for copying.

JavaScript

  1. Number.EPSILON
  2. Number.isInteger(Infinity) // false
  3. Number.isNaN("NaN") // false
  4. Math.acosh(3) // 1.762747174039086
  5. Math.hypot(3, 4) // 5
  6. Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2
  7. "abcde".includes("cd") // true
  8. "abc".repeat(3) // "abcabcabc"
  9. Array.from(document.querySelectorAll("*")) // Returns a real Array
  10. Array.of(1, 2, 3) // Similar to new Array(...), but without special one-arg behavior
  11. [0, 0, 0].fill(7, 1) // [0,7,7]
  12. [1,2,3].findIndex(x => x == 2) // 1
  13. ["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"]
  14. ["a", "b", "c"].keys() // iterator 0, 1, 2
  15. ["a", "b", "c"].values() // iterator "a", "b", "c"
  16. Object.assign(Point, { origin: new Point(0,0) })

Learn ES2015 - 图14Limited support from polyfill

Most of these APIs are supported by the Babel polyfill. However, certain features are omitted for various reasons (e.g. String.prototype.normalize needs a lot of additional code to support). You can find more polyfills here.

Binary and Octal Literals

Two new numeric literal forms are added for binary (b) and octal (o).

JavaScript

  1. 0b111110111 === 503 // true
  2. 0o767 === 503 // true

Learn ES2015 - 图15Only supports literal form

Babel is only able to transform 0o767 and not Number("0o767").

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.

JavaScript

  1. function timeout(duration = 0) {
  2. return new Promise((resolve, reject) => {
  3. setTimeout(resolve, duration);
  4. })
  5. }
  6. var p = timeout(1000).then(() => {
  7. return timeout(2000);
  8. }).then(() => {
  9. throw new Error("hmm");
  10. }).catch(err => {
  11. return Promise.all([timeout(100), timeout(200)]);
  12. })

Learn ES2015 - 图16Support via polyfill

In order to support Promises you must include the Babel polyfill.

Reflect API

Full reflection API exposing the runtime-level meta-operations on objects. This is effectively the inverse of the Proxy API, and allows making calls corresponding to the same meta-operations as the proxy traps. Especially useful for implementing proxies.

JavaScript

  1. var O = {a: 1};
  2. Object.defineProperty(O, 'b', {value: 2});
  3. O[Symbol('c')] = 3;
  4. Reflect.ownKeys(O); // ['a', 'b', Symbol(c)]
  5. function C(a, b){
  6. this.c = a + b;
  7. }
  8. var instance = Reflect.construct(C, [20, 22]);
  9. instance.c; // 42

Learn ES2015 - 图17Support via polyfill

In order to use the Reflect API you must include the Babel polyfill.

Tail Calls

Calls in tail-position are guaranteed to not grow the stack unboundedly. Makes recursive algorithms safe in the face of unbounded inputs.

JavaScript

  1. function factorial(n, acc = 1) {
  2. "use strict";
  3. if (n <= 1) return acc;
  4. return factorial(n - 1, n * acc);
  5. }
  6. // Stack overflow in most implementations today,
  7. // but safe on arbitrary inputs in ES2015
  8. factorial(100000)

Learn ES2015 - 图18Temporarily Removed in Babel 6

Only explicit self referencing tail recursion was supported due to the complexity and performance impact of supporting tail calls globally. Removed due to other bugs and will be re-implemented.