Please support this book: buy it (PDF, EPUB, MOBI) or donate

30. An overview of what’s new in ES6

This chapter collects the overview sections of all the chapters in this book.

30.1 Categories of ES6 features

The introduction of the ES6 specification lists all new features:

Some of [ECMAScript 6’s] major enhancements include modules, class declarations, lexical block scoping, iterators and generators, promises for asynchronous programming, destructuring patterns, and proper tail calls. The ECMAScript library of built-ins has been expanded to support additional data abstractions including maps, sets, and arrays of binary numeric values as well as additional support for Unicode supplemental characters in strings and regular expressions. The built-ins are now extensible via subclassing.

There are three major categories of features:

30.2 New number and Math features

30.2.1 New integer literals

You can now specify integers in binary and octal notation:

  1. > 0xFF // ES5: hexadecimal
  2. 255
  3. > 0b11 // ES6: binary
  4. 3
  5. > 0o10 // ES6: octal
  6. 8

30.2.2 New Number properties

The global object Number gained a few new properties:

  • Number.EPSILON for comparing floating point numbers with a tolerance for rounding errors.
  • Number.isInteger(num) checks whether num is an integer (a number without a decimal fraction):
  1. > Number.isInteger(1.05)
  2. false
  3. > Number.isInteger(1)
  4. true
  5.  
  6. > Number.isInteger(-3.1)
  7. false
  8. > Number.isInteger(-3)
  9. true
  • A method and constants for determining whether a JavaScript integer is safe (within the signed 53 bit range in which there is no loss of precision):
    • Number.isSafeInteger(number)
    • Number.MIN_SAFE_INTEGER
    • Number.MAX_SAFE_INTEGER
  • Number.isNaN(num) checks whether num is the value NaN. In contrast to the global function isNaN(), it doesn’t coerce its argument to a number and is therefore safer for non-numbers:
  1. > isNaN('???')
  2. true
  3. > Number.isNaN('???')
  4. false
  • Three additional methods of Number are mostly equivalent to the global functions with the same names: Number.isFinite, Number.parseFloat, Number.parseInt.

30.2.3 New Math methods

The global object Math has new methods for numerical, trigonometric and bitwise operations. Let’s look at four examples.

Math.sign() returns the sign of a number:

  1. > Math.sign(-8)
  2. -1
  3. > Math.sign(0)
  4. 0
  5. > Math.sign(3)
  6. 1

Math.trunc() removes the decimal fraction of a number:

  1. > Math.trunc(3.1)
  2. 3
  3. > Math.trunc(3.9)
  4. 3
  5. > Math.trunc(-3.1)
  6. -3
  7. > Math.trunc(-3.9)
  8. -3

Math.log10() computes the logarithm to base 10:

  1. > Math.log10(100)
  2. 2

Math.hypot() Computes the square root of the sum of the squares of its arguments (Pythagoras’ theorem):

  1. > Math.hypot(3, 4)
  2. 5

30.3 New string features

New string methods:

  1. > 'hello'.startsWith('hell')
  2. true
  3. > 'hello'.endsWith('ello')
  4. true
  5. > 'hello'.includes('ell')
  6. true
  7. > 'doo '.repeat(3)
  8. 'doo doo doo '

ES6 has a new kind of string literal, the template literal:

  1. // String interpolation via template literals (in backticks)
  2. const first = 'Jane';
  3. const last = 'Doe';
  4. console.log(`Hello ${first} ${last}!`);
  5. // Hello Jane Doe!
  6.  
  7. // Template literals also let you create strings with multiple lines
  8. const multiLine = `
  9. This is
  10. a string
  11. with multiple
  12. lines`;

30.4 Symbols

Symbols are a new primitive type in ECMAScript 6. They are created via a factory function:

  1. const mySymbol = Symbol('mySymbol');

Every time you call the factory function, a new and unique symbol is created. The optional parameter is a descriptive string that is shown when printing the symbol (it has no other purpose):

  1. > mySymbol
  2. Symbol(mySymbol)

30.4.1 Use case 1: unique property keys

Symbols are mainly used as unique property keys – a symbol never clashes with any other property key (symbol or string). For example, you can make an object iterable (usable via the for-of loop and other language mechanisms), by using the symbol stored in Symbol.iterator as the key of a method (more information on iterables is given in the chapter on iteration):

  1. const iterableObject = {
  2. [Symbol.iterator]() { // (A)
  3. ···
  4. }
  5. }
  6. for (const x of iterableObject) {
  7. console.log(x);
  8. }
  9. // Output:
  10. // hello
  11. // world

In line A, a symbol is used as the key of the method. This unique marker makes the object iterable and enables us to use the for-of loop.

30.4.2 Use case 2: constants representing concepts

In ECMAScript 5, you may have used strings to represent concepts such as colors. In ES6, you can use symbols and be sure that they are always unique:

  1. const COLOR_RED = Symbol('Red');
  2. const COLOR_ORANGE = Symbol('Orange');
  3. const COLOR_YELLOW = Symbol('Yellow');
  4. const COLOR_GREEN = Symbol('Green');
  5. const COLOR_BLUE = Symbol('Blue');
  6. const COLOR_VIOLET = Symbol('Violet');
  7.  
  8. function getComplement(color) {
  9. switch (color) {
  10. case COLOR_RED:
  11. return COLOR_GREEN;
  12. case COLOR_ORANGE:
  13. return COLOR_BLUE;
  14. case COLOR_YELLOW:
  15. return COLOR_VIOLET;
  16. case COLOR_GREEN:
  17. return COLOR_RED;
  18. case COLOR_BLUE:
  19. return COLOR_ORANGE;
  20. case COLOR_VIOLET:
  21. return COLOR_YELLOW;
  22. default:
  23. throw new Exception('Unknown color: '+color);
  24. }
  25. }

Every time you call Symbol('Red'), a new symbol is created. Therefore, COLOR_RED can never be mistaken for another value. That would be different if it were the string 'Red'.

30.4.3 Pitfall: you can’t coerce symbols to strings

Coercing (implicitly converting) symbols to strings throws exceptions:

  1. const sym = Symbol('desc');
  2.  
  3. const str1 = '' + sym; // TypeError
  4. const str2 = `${sym}`; // TypeError

The only solution is to convert explicitly:

  1. const str2 = String(sym); // 'Symbol(desc)'
  2. const str3 = sym.toString(); // 'Symbol(desc)'

Forbidding coercion prevents some errors, but also makes working with symbols more complicated.

The following operations are aware of symbols as property keys:

  • Reflect.ownKeys()
  • Property access via []
  • Object.assign() The following operations ignore symbols as property keys:

  • Object.keys()

  • Object.getOwnPropertyNames()
  • for-in loop

30.5 Template literals

ES6 has two new kinds of literals: template literals and tagged template literals. These two literals have similar names and look similar, but they are quite different. It is therefore important to distinguish:

  • Template literals (code): multi-line string literals that support interpolation
  • Tagged template literals (code): function calls
  • Web templates (data): HTML with blanks to be filled in Template literals are string literals that can stretch across multiple lines and include interpolated expressions (inserted via ${···}):
  1. const firstName = 'Jane';
  2. console.log(`Hello ${firstName}!
  3. How are you
  4. today?`);
  5.  
  6. // Output:
  7. // Hello Jane!
  8. // How are you
  9. // today?

Tagged template literals (short: tagged templates) are created by mentioning a function before a template literal:

  1. > String.raw`A \tagged\ template`
  2. 'A \\tagged\\ template'

Tagged templates are function calls. In the previous example, the method String.raw is called to produce the result of the tagged template.

30.6 Variables and scoping

ES6 provides two new ways of declaring variables: let and const, which mostly replace the ES5 way of declaring variables, var.

30.6.1 let

let works similarly to var, but the variable it declares is block-scoped, it only exists within the current block. var is function-scoped.

In the following code, you can see that the let-declared variable tmp only exists inside the block that starts in line A:

  1. function order(x, y) {
  2. if (x > y) { // (A)
  3. let tmp = x;
  4. x = y;
  5. y = tmp;
  6. }
  7. console.log(tmp===x); // ReferenceError: tmp is not defined
  8. return [x, y];
  9. }

30.6.2 const

const works like let, but the variable you declare must be immediately initialized, with a value that can’t be changed afterwards.

  1. const foo;
  2. // SyntaxError: missing = in const declaration
  3.  
  4. const bar = 123;
  5. bar = 456;
  6. // TypeError: `bar` is read-only

Since for-of creates one binding (storage space for a variable) per loop iteration, it is OK to const-declare the loop variable:

  1. for (const x of ['a', 'b']) {
  2. console.log(x);
  3. }
  4. // Output:
  5. // a
  6. // b

30.6.3 Ways of declaring variables

The following table gives an overview of six ways in which variables can be declared in ES6 (inspired by a table by kangax):

HoistingScopeCreates global properties
varDeclarationFunctionYes
letTemporal dead zoneBlockNo
constTemporal dead zoneBlockNo
functionCompleteBlockYes
classNoBlockNo
importCompleteModule-globalNo

30.7 Destructuring

Destructuring is a convenient way of extracting multiple values from data stored in (possibly nested) objects and Arrays. It can be used in locations that receive data (such as the left-hand side of an assignment). How to extract the values is specified via patterns (read on for examples).

30.7.1 Object destructuring

Destructuring objects:

  1. const obj = { first: 'Jane', last: 'Doe' };
  2. const {first: f, last: l} = obj;
  3. // f = 'Jane'; l = 'Doe'
  4.  
  5. // {prop} is short for {prop: prop}
  6. const {first, last} = obj;
  7. // first = 'Jane'; last = 'Doe'

Destructuring helps with processing return values:

  1. const obj = { foo: 123 };
  2.  
  3. const {writable, configurable} =
  4. Object.getOwnPropertyDescriptor(obj, 'foo');
  5.  
  6. console.log(writable, configurable); // true true

30.7.2 Array destructuring

Array destructuring (works for all iterable values):

  1. const iterable = ['a', 'b'];
  2. const [x, y] = iterable;
  3. // x = 'a'; y = 'b'

Destructuring helps with processing return values:

  1. const [all, year, month, day] =
  2. /^(\d\d\d\d)-(\d\d)-(\d\d)$/
  3. .exec('2999-12-31');

30.7.3 Where can destructuring be used?

Destructuring can be used in the following locations (I’m showing Array patterns to demonstrate; object patterns work just as well):

  1. // Variable declarations:
  2. const [x] = ['a'];
  3. let [x] = ['a'];
  4. var [x] = ['a'];
  5.  
  6. // Assignments:
  7. [x] = ['a'];
  8.  
  9. // Parameter definitions:
  10. function f([x]) { ··· }
  11. f(['a']);

You can also destructure in a for-of loop:

  1. const arr = ['a', 'b'];
  2. for (const [index, element] of arr.entries()) {
  3. console.log(index, element);
  4. }
  5. // Output:
  6. // 0 a
  7. // 1 b

30.8 Parameter handling

Parameter handling has been significantly upgraded in ECMAScript 6. It now supports parameter default values, rest parameters (varargs) and destructuring.

Additionally, the spread operator helps with function/method/constructor calls and Array literals.

30.8.1 Default parameter values

A default parameter value is specified for a parameter via an equals sign (=). If a caller doesn’t provide a value for the parameter, the default value is used. In the following example, the default parameter value of y is 0:

  1. function func(x, y=0) {
  2. return [x, y];
  3. }
  4. func(1, 2); // [1, 2]
  5. func(1); // [1, 0]
  6. func(); // [undefined, 0]

30.8.2 Rest parameters

If you prefix a parameter name with the rest operator (), that parameter receives all remaining parameters via an Array:

  1. function format(pattern, ...params) {
  2. return {pattern, params};
  3. }
  4. format(1, 2, 3);
  5. // { pattern: 1, params: [ 2, 3 ] }
  6. format();
  7. // { pattern: undefined, params: [] }

30.8.3 Named parameters via destructuring

You can simulate named parameters if you destructure with an object pattern in the parameter list:

  1. function selectEntries({ start=0, end=-1, step=1 } = {}) { // (A)
  2. // The object pattern is an abbreviation of:
  3. // { start: start=0, end: end=-1, step: step=1 }
  4.  
  5. // Use the variables `start`, `end` and `step` here
  6. ···
  7. }
  8.  
  9. selectEntries({ start: 10, end: 30, step: 2 });
  10. selectEntries({ step: 3 });
  11. selectEntries({});
  12. selectEntries();

The = {} in line A enables you to call selectEntries() without paramters.

30.8.4 Spread operator (…)

In function and constructor calls, the spread operator turns iterable values into arguments:

  1. > Math.max(-1, 5, 11, 3)
  2. 11
  3. > Math.max(...[-1, 5, 11, 3])
  4. 11
  5. > Math.max(-1, ...[-5, 11], 3)
  6. 11

In Array literals, the spread operator turns iterable values into Array elements:

  1. > [1, ...[2,3], 4]
  2. [1, 2, 3, 4]

30.9 Callable entities in ECMAScript 6

In ES5, a single construct, the (traditional) function, played three roles:

  • Real (non-method) function
  • Method
  • Constructor In ES6, there is more specialization. The three duties are now handled as follows. As far as function definitions and class definitions are concerned, a definition is either a declaration or an expression.

  • Real (non-method) function:

    • Arrow functions (only have an expression form)
    • Traditional functions (created via function definitions)
    • Generator functions (created via generator function definitions)
  • Method:
    • Methods (created by method definitions in object literals and class definitions)
    • Generator methods (created by generator method definitions in object literals and class definitions)
  • Constructor:
    • Classes (created via class definitions) Especially for callbacks, arrow functions are handy, because they don’t shadow the this of the surrounding scope.

For longer callbacks and stand-alone functions, traditional functions can be OK. Some APIs use this as an implicit parameter. In that case, you have no choice but to use traditional functions.

Note that I distinguish:

  • The entities: e.g. traditional functions
  • The syntax that creates the entities: e.g. function definitions Even though their behaviors differ (as explained later), all of these entities are functions. For example:
  1. > typeof (() => {}) // arrow function
  2. 'function'
  3. > typeof function* () {} // generator function
  4. 'function'
  5. > typeof class {} // class
  6. 'function'

30.10 Arrow functions

There are two benefits to arrow functions.

First, they are less verbose than traditional function expressions:

  1. const arr = [1, 2, 3];
  2. const squares = arr.map(x => x * x);
  3.  
  4. // Traditional function expression:
  5. const squares = arr.map(function (x) { return x * x });

Second, their this is picked up from surroundings (lexical). Therefore, you don’t need bind() or that = this, anymore.

  1. function UiComponent() {
  2. const button = document.getElementById('myButton');
  3. button.addEventListener('click', () => {
  4. console.log('CLICK');
  5. this.handleClick(); // lexical `this`
  6. });
  7. }

The following variables are all lexical inside arrow functions:

  • arguments
  • super
  • this
  • new.target

30.11 New OOP features besides classes

30.11.1 New object literal features

Method definitions:

  1. const obj = {
  2. myMethod(x, y) {
  3. ···
  4. }
  5. };

Property value shorthands:

  1. const first = 'Jane';
  2. const last = 'Doe';
  3.  
  4. const obj = { first, last };
  5. // Same as:
  6. const obj = { first: first, last: last };

Computed property keys:

  1. const propKey = 'foo';
  2. const obj = {
  3. [propKey]: true,
  4. ['b'+'ar']: 123
  5. };

This new syntax can also be used for method definitions:

  1. const obj = {
  2. ['h'+'ello']() {
  3. return 'hi';
  4. }
  5. };
  6. console.log(obj.hello()); // hi

The main use case for computed property keys is to make it easy to use symbols as property keys.

30.11.2 New methods in Object

The most important new method of Object is assign(). Traditionally, this functionality was called extend() in the JavaScript world. In contrast to how this classic operation works, Object.assign() only considers own (non-inherited) properties.

  1. const obj = { foo: 123 };
  2. Object.assign(obj, { bar: true });
  3. console.log(JSON.stringify(obj));
  4. // {"foo":123,"bar":true}

30.12 Classes

A class and a subclass:

  1. class Point {
  2. constructor(x, y) {
  3. this.x = x;
  4. this.y = y;
  5. }
  6. toString() {
  7. return `(${this.x}, ${this.y})`;
  8. }
  9. }
  10.  
  11. class ColorPoint extends Point {
  12. constructor(x, y, color) {
  13. super(x, y);
  14. this.color = color;
  15. }
  16. toString() {
  17. return super.toString() + ' in ' + this.color;
  18. }
  19. }

Using the classes:

  1. > const cp = new ColorPoint(25, 8, 'green');
  2.  
  3. > cp.toString();
  4. '(25, 8) in green'
  5.  
  6. > cp instanceof ColorPoint
  7. true
  8. > cp instanceof Point
  9. true

Under the hood, ES6 classes are not something that is radically new: They mainly provide more convenient syntax to create old-school constructor functions. You can see that if you use typeof:

  1. > typeof Point
  2. 'function'

30.13 Modules

JavaScript has had modules for a long time. However, they were implemented via libraries, not built into the language. ES6 is the first time that JavaScript has built-in modules.

ES6 modules are stored in files. There is exactly one module per file and one file per module. You have two ways of exporting things from a module. These two ways can be mixed, but it is usually better to use them separately.

30.13.1 Multiple named exports

There can be multiple named exports:

  1. //------ lib.js ------
  2. export const sqrt = Math.sqrt;
  3. export function square(x) {
  4. return x * x;
  5. }
  6. export function diag(x, y) {
  7. return sqrt(square(x) + square(y));
  8. }
  9.  
  10. //------ main.js ------
  11. import { square, diag } from 'lib';
  12. console.log(square(11)); // 121
  13. console.log(diag(4, 3)); // 5

You can also import the complete module:

  1. //------ main.js ------
  2. import * as lib from 'lib';
  3. console.log(lib.square(11)); // 121
  4. console.log(lib.diag(4, 3)); // 5

30.13.2 Single default export

There can be a single default export. For example, a function:

  1. //------ myFunc.js ------
  2. export default function () { ··· } // no semicolon!
  3.  
  4. //------ main1.js ------
  5. import myFunc from 'myFunc';
  6. myFunc();

Or a class:

  1. //------ MyClass.js ------
  2. export default class { ··· } // no semicolon!
  3.  
  4. //------ main2.js ------
  5. import MyClass from 'MyClass';
  6. const inst = new MyClass();

Note that there is no semicolon at the end if you default-export a function or a class (which are anonymous declarations).

30.13.3 Browsers: scripts versus modules

ScriptsModules
HTML element<script><script type="module">
Default modenon-strictstrict
Top-level variables aregloballocal to module
Value of this at top levelwindowundefined
Executedsynchronouslyasynchronously
Declarative imports (import statement)noyes
Programmatic imports (Promise-based API)yesyes
File extension.js.js

30.14 The for-of loop

for-of is a new loop in ES6 that replaces both for-in and forEach() and supports the new iteration protocol.

Use it to loop over iterable objects (Arrays, strings, Maps, Sets, etc.; see Chap. “Iterables and iterators”):

  1. const iterable = ['a', 'b'];
  2. for (const x of iterable) {
  3. console.log(x);
  4. }
  5.  
  6. // Output:
  7. // a
  8. // b

break and continue work inside for-of loops:

  1. for (const x of ['a', '', 'b']) {
  2. if (x.length === 0) break;
  3. console.log(x);
  4. }
  5.  
  6. // Output:
  7. // a

Access both elements and their indices while looping over an Array (the square brackets before of mean that we are using destructuring):

  1. const arr = ['a', 'b'];
  2. for (const [index, element] of arr.entries()) {
  3. console.log(`${index}. ${element}`);
  4. }
  5.  
  6. // Output:
  7. // 0. a
  8. // 1. b

Looping over the [key, value] entries in a Map (the square brackets before of mean that we are using destructuring):

  1. const map = new Map([
  2. [false, 'no'],
  3. [true, 'yes'],
  4. ]);
  5. for (const [key, value] of map) {
  6. console.log(`${key} => ${value}`);
  7. }
  8.  
  9. // Output:
  10. // false => no
  11. // true => yes

30.15 New Array features

New static Array methods:

  • Array.from(arrayLike, mapFunc?, thisArg?)
  • Array.of(…items) New Array.prototype methods:

  • Iterating:

    • Array.prototype.entries()
    • Array.prototype.keys()
    • Array.prototype.values()
  • Searching for elements:
    • Array.prototype.find(predicate, thisArg?)
    • Array.prototype.findIndex(predicate, thisArg?)
  • Array.prototype.copyWithin(target, start, end=this.length)
  • Array.prototype.fill(value, start=0, end=this.length)

30.16 Maps and Sets

Among others, the following four data structures are new in ECMAScript 6: Map, WeakMap, Set and WeakSet.

30.16.1 Maps

The keys of a Map can be arbitrary values:

  1. > const map = new Map(); // create an empty Map
  2. > const KEY = {};
  3.  
  4. > map.set(KEY, 123);
  5. > map.get(KEY)
  6. 123
  7. > map.has(KEY)
  8. true
  9. > map.delete(KEY);
  10. true
  11. > map.has(KEY)
  12. false

You can use an Array (or any iterable) with [key, value] pairs to set up the initial data in the Map:

  1. const map = new Map([
  2. [ 1, 'one' ],
  3. [ 2, 'two' ],
  4. [ 3, 'three' ], // trailing comma is ignored
  5. ]);

30.16.2 Sets

A Set is a collection of unique elements:

  1. const arr = [5, 1, 5, 7, 7, 5];
  2. const unique = [...new Set(arr)]; // [ 5, 1, 7 ]

As you can see, you can initialize a Set with elements if you hand the constructor an iterable (arr in the example) over those elements.

30.16.3 WeakMaps

A WeakMap is a Map that doesn’t prevent its keys from being garbage-collected. That means that you can associate data with objects without having to worry about memory leaks. For example:

  1. //----- Manage listeners
  2.  
  3. const _objToListeners = new WeakMap();
  4.  
  5. function addListener(obj, listener) {
  6. if (! _objToListeners.has(obj)) {
  7. _objToListeners.set(obj, new Set());
  8. }
  9. _objToListeners.get(obj).add(listener);
  10. }
  11.  
  12. function triggerListeners(obj) {
  13. const listeners = _objToListeners.get(obj);
  14. if (listeners) {
  15. for (const listener of listeners) {
  16. listener();
  17. }
  18. }
  19. }
  20.  
  21. //----- Example: attach listeners to an object
  22.  
  23. const obj = {};
  24. addListener(obj, () => console.log('hello'));
  25. addListener(obj, () => console.log('world'));
  26.  
  27. //----- Example: trigger listeners
  28.  
  29. triggerListeners(obj);
  30.  
  31. // Output:
  32. // hello
  33. // world

30.17 Typed Arrays

Typed Arrays are an ECMAScript 6 API for handling binary data.

Code example:

  1. const typedArray = new Uint8Array([0,1,2]);
  2. console.log(typedArray.length); // 3
  3. typedArray[0] = 5;
  4. const normalArray = [...typedArray]; // [5,1,2]
  5.  
  6. // The elements are stored in typedArray.buffer.
  7. // Get a different view on the same data:
  8. const dataView = new DataView(typedArray.buffer);
  9. console.log(dataView.getUint8(0)); // 5

Instances of ArrayBuffer store the binary data to be processed. Two kinds of views are used to access the data:

  • Typed Arrays (Uint8Array, Int16Array, Float32Array, etc.) interpret the ArrayBuffer as an indexed sequence of elements of a single type.
  • Instances of DataView let you access data as elements of several types (Uint8, Int16, Float32, etc.), at any byte offset inside an ArrayBuffer. The following browser APIs support Typed Arrays (details are mentioned in a dedicated section):

  • File API

  • XMLHttpRequest
  • Fetch API
  • Canvas
  • WebSockets
  • And more

30.18 Iterables and iterators

ES6 introduces a new mechanism for traversing data: iteration. Two concepts are central to iteration:

  • An iterable is a data structure that wants to make its elements accessible to the public. It does so by implementing a method whose key is Symbol.iterator. That method is a factory for iterators.
  • An iterator is a pointer for traversing the elements of a data structure (think cursors in databases). Expressed as interfaces in TypeScript notation, these roles look like this:
  1. interface Iterable {
  2. [Symbol.iterator]() : Iterator;
  3. }
  4. interface Iterator {
  5. next() : IteratorResult;
  6. }
  7. interface IteratorResult {
  8. value: any;
  9. done: boolean;
  10. }

30.18.1 Iterable values

The following values are iterable:

  • Arrays
  • Strings
  • Maps
  • Sets
  • DOM data structures (work in progress) Plain objects are not iterable (why is explained in a dedicated section).

30.18.2 Constructs supporting iteration

Language constructs that access data via iteration:

  • Destructuring via an Array pattern:
  1. const [a,b] = new Set(['a', 'b', 'c']);
  • for-of loop:
  1. for (const x of ['a', 'b', 'c']) {
  2. console.log(x);
  3. }
  • Array.from():
  1. const arr = Array.from(new Set(['a', 'b', 'c']));
  • Spread operator ():
  1. const arr = [...new Set(['a', 'b', 'c'])];
  • Constructors of Maps and Sets:
  1. const map = new Map([[false, 'no'], [true, 'yes']]);
  2. const set = new Set(['a', 'b', 'c']);
  • Promise.all(), Promise.race():
  1. Promise.all(iterableOverPromises).then(···);
  2. Promise.race(iterableOverPromises).then(···);
  • yield*:
  1. yield* anIterable;

30.19 Generators

30.19.1 What are generators?

You can think of generators as processes (pieces of code) that you can pause and resume:

  1. function* genFunc() {
  2. // (A)
  3. console.log('First');
  4. yield;
  5. console.log('Second');
  6. }

Note the new syntax: function* is a new “keyword” for generator functions (there are also generator methods). yield is an operator with which a generator can pause itself. Additionally, generators can also receive input and send output via yield.

When you call a generator function genFunc(), you get a generator object genObj that you can use to control the process:

  1. const genObj = genFunc();

The process is initially paused in line A. genObj.next() resumes execution, a yield inside genFunc() pauses execution:

  1. genObj.next();
  2. // Output: First
  3. genObj.next();
  4. // output: Second

30.19.2 Kinds of generators

There are four kinds of generators:

  • Generator function declarations:
  1. function* genFunc() { ··· }
  2. const genObj = genFunc();
  • Generator function expressions:
  1. const genFunc = function* () { ··· };
  2. const genObj = genFunc();
  • Generator method definitions in object literals:
  1. const obj = {
  2. * generatorMethod() {
  3. ···
  4. }
  5. };
  6. const genObj = obj.generatorMethod();
  • Generator method definitions in class definitions (class declarations or class expressions):
  1. class MyClass {
  2. * generatorMethod() {
  3. ···
  4. }
  5. }
  6. const myInst = new MyClass();
  7. const genObj = myInst.generatorMethod();

30.19.3 Use case: implementing iterables

The objects returned by generators are iterable; each yield contributes to the sequence of iterated values. Therefore, you can use generators to implement iterables, which can be consumed by various ES6 language mechanisms: for-of loop, spread operator (), etc.

The following function returns an iterable over the properties of an object, one [key, value] pair per property:

  1. function* objectEntries(obj) {
  2. const propKeys = Reflect.ownKeys(obj);
  3.  
  4. for (const propKey of propKeys) {
  5. // `yield` returns a value and then pauses
  6. // the generator. Later, execution continues
  7. // where it was previously paused.
  8. yield [propKey, obj[propKey]];
  9. }
  10. }

objectEntries() is used like this:

  1. const jane = { first: 'Jane', last: 'Doe' };
  2. for (const [key,value] of objectEntries(jane)) {
  3. console.log(`${key}: ${value}`);
  4. }
  5. // Output:
  6. // first: Jane
  7. // last: Doe

How exactly objectEntries() works is explained in a dedicated section. Implementing the same functionality without generators is much more work.

30.19.4 Use case: simpler asynchronous code

You can use generators to tremendously simplify working with Promises. Let’s look at a Promise-based function fetchJson() and how it can be improved via generators.

  1. function fetchJson(url) {
  2. return fetch(url)
  3. .then(request => request.text())
  4. .then(text => {
  5. return JSON.parse(text);
  6. })
  7. .catch(error => {
  8. console.log(`ERROR: ${error.stack}`);
  9. });
  10. }

With the library co and a generator, this asynchronous code looks synchronous:

  1. const fetchJson = co.wrap(function* (url) {
  2. try {
  3. let request = yield fetch(url);
  4. let text = yield request.text();
  5. return JSON.parse(text);
  6. }
  7. catch (error) {
  8. console.log(`ERROR: ${error.stack}`);
  9. }
  10. });

ECMAScript 2017 will have async functions which are internally based on generators. With them, the code looks like this:

  1. async function fetchJson(url) {
  2. try {
  3. let request = await fetch(url);
  4. let text = await request.text();
  5. return JSON.parse(text);
  6. }
  7. catch (error) {
  8. console.log(`ERROR: ${error.stack}`);
  9. }
  10. }

All versions can be invoked like this:

  1. fetchJson('http://example.com/some_file.json')
  2. .then(obj => console.log(obj));

30.19.5 Use case: receiving asynchronous data

Generators can receive input from next() via yield. That means that you can wake up a generator whenever new data arrives asynchronously and to the generator it feels like it receives the data synchronously.

30.20 New regular expression features

The following regular expression features are new in ECMAScript 6:

  • The new flag /y (sticky) anchors each match of a regular expression to the end of the previous match.
  • The new flag /u (unicode) handles surrogate pairs (such as \uD83D\uDE80) as code points and lets you use Unicode code point escapes (such as \u{1F680}) in regular expressions.
  • The new data property flags gives you access to the flags of a regular expression, just like source already gives you access to the pattern in ES5:
  1. > /abc/ig.source // ES5
  2. 'abc'
  3. > /abc/ig.flags // ES6
  4. 'gi'
  • You can use the constructor RegExp() to make a copy of a regular expression:
  1. > new RegExp(/abc/ig).flags
  2. 'gi'
  3. > new RegExp(/abc/ig, 'i').flags // change flags
  4. 'i'

30.21 Promises for asynchronous programming

Promises are an alternative to callbacks for delivering the results of an asynchronous computation. They require more effort from implementors of asynchronous functions, but provide several benefits for users of those functions.

The following function returns a result asynchronously, via a Promise:

  1. function asyncFunc() {
  2. return new Promise(
  3. function (resolve, reject) {
  4. ···
  5. resolve(result);
  6. ···
  7. reject(error);
  8. });
  9. }

You call asyncFunc() as follows:

  1. asyncFunc()
  2. .then(result => { ··· })
  3. .catch(error => { ··· });

30.21.1 Chaining then() calls

then() always returns a Promise, which enables you to chain method calls:

  1. asyncFunc1()
  2. .then(result1 => {
  3. // Use result1
  4. return asyncFunction2(); // (A)
  5. })
  6. .then(result2 => { // (B)
  7. // Use result2
  8. })
  9. .catch(error => {
  10. // Handle errors of asyncFunc1() and asyncFunc2()
  11. });

How the Promise P returned by then() is settled depends on what its callback does:

  • If it returns a Promise (as in line A), the settlement of that Promise is forwarded to P. That’s why the callback from line B can pick up the settlement of asyncFunction2’s Promise.
  • If it returns a different value, that value is used to settle P.
  • If throws an exception then P is rejected with that exception. Furthermore, note how catch() handles the errors of two asynchronous function calls (asyncFunction1() and asyncFunction2()). That is, uncaught errors are passed on until there is an error handler.

30.21.2 Executing asynchronous functions in parallel

If you chain asynchronous function calls via then(), they are executed sequentially, one at a time:

  1. asyncFunc1()
  2. .then(() => asyncFunc2());

If you don’t do that and call all of them immediately, they are basically executed in parallel (a fork in Unix process terminology):

  1. asyncFunc1();
  2. asyncFunc2();

Promise.all() enables you to be notified once all results are in (a join in Unix process terminology). Its input is an Array of Promises, its output a single Promise that is fulfilled with an Array of the results.

  1. Promise.all([
  2. asyncFunc1(),
  3. asyncFunc2(),
  4. ])
  5. .then(([result1, result2]) => {
  6. ···
  7. })
  8. .catch(err => {
  9. // Receives first rejection among the Promises
  10. ···
  11. });

30.21.3 Glossary: Promises

The Promise API is about delivering results asynchronously. A Promise object (short: Promise) is a stand-in for the result, which is delivered via that object.

States:

  • A Promise is always in one of three mutually exclusive states:
    • Before the result is ready, the Promise is pending.
    • If a result is available, the Promise is fulfilled.
    • If an error happened, the Promise is rejected.
  • A Promise is settled if “things are done” (if it is either fulfilled or rejected).
  • A Promise is settled exactly once and then remains unchanged. Reacting to state changes:

  • Promise reactions are callbacks that you register with the Promise method then(), to be notified of a fulfillment or a rejection.

  • A thenable is an object that has a Promise-style then() method. Whenever the API is only interested in being notified of settlements, it only demands thenables (e.g. the values returned from then() and catch(); or the values handed to Promise.all() and Promise.race()). Changing states: There are two operations for changing the state of a Promise. After you have invoked either one of them once, further invocations have no effect.

  • Rejecting a Promise means that the Promise becomes rejected.

  • Resolving a Promise has different effects, depending on what value you are resolving with:
    • Resolving with a normal (non-thenable) value fulfills the Promise.
    • Resolving a Promise P with a thenable T means that P can’t be resolved anymore and will now follow T’s state, including its fulfillment or rejection value. The appropriate P reactions will get called once T settles (or are called immediately if T is already settled).

30.22 Metaprogramming with proxies

Proxies enable you to intercept and customize operations performed on objects (such as getting properties). They are a metaprogramming feature.

In the following example, proxy is the object whose operations we are intercepting and handler is the object that handles the interceptions. In this case, we are only intercepting a single operation, get (getting properties).

  1. const target = {};
  2. const handler = {
  3. get(target, propKey, receiver) {
  4. console.log('get ' + propKey);
  5. return 123;
  6. }
  7. };
  8. const proxy = new Proxy(target, handler);

When we get the property proxy.foo, the handler intercepts that operation:

  1. > proxy.foo
  2. get foo
  3. 123

Consult the reference for the complete API for a list of operations that can be intercepted.