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

4. Core ES6 features

This chapter describes the core ES6 features. These features are easy to adopt; the remaining features are mainly of interest to library authors. I explain each feature via the corresponding ES5 code.

4.1 From var to const/let

In ES5, you declare variables via var. Such variables are function-scoped, their scopes are the innermost enclosing functions. The behavior of var is occasionally confusing. This is an example:

  1. var x = 3;
  2. function func(randomize) {
  3. if (randomize) {
  4. var x = Math.random(); // (A) scope: whole function
  5. return x;
  6. }
  7. return x; // accesses the x from line A
  8. }
  9. func(false); // undefined

That func() returns undefined may be surprising. You can see why if you rewrite the code so that it more closely reflects what is actually going on:

  1. var x = 3;
  2. function func(randomize) {
  3. var x;
  4. if (randomize) {
  5. x = Math.random();
  6. return x;
  7. }
  8. return x;
  9. }
  10. func(false); // undefined

In ES6, you can additionally declare variables via let and const. Such variables are block-scoped, their scopes are the innermost enclosing blocks. let is roughly a block-scoped version of var. const works like let, but creates variables whose values can’t be changed.

let and const behave more strictly and throw more exceptions (e.g. when you access their variables inside their scope before they are declared). Block-scoping helps with keeping the effects of code fragments more local (see the next section for a demonstration). And it’s more mainstream than function-scoping, which eases moving between JavaScript and other programming languages.

If you replace var with let in the initial version, you get different behavior:

  1. let x = 3;
  2. function func(randomize) {
  3. if (randomize) {
  4. let x = Math.random();
  5. return x;
  6. }
  7. return x;
  8. }
  9. func(false); // 3

That means that you can’t blindly replace var with let or const in existing code; you have to be careful during refactoring.

My advice is:

  • Prefer const. You can use it for all variables whose values never change.
  • Otherwise, use let – for variables whose values do change.
  • Avoid var. More information: chapter “Variables and scoping”.

4.2 From IIFEs to blocks

In ES5, you had to use a pattern called IIFE (Immediately-Invoked Function Expression) if you wanted to restrict the scope of a variable tmp to a block:

  1. (function () { // open IIFE
  2. var tmp = ···;
  3. ···
  4. }()); // close IIFE
  5.  
  6. console.log(tmp); // ReferenceError

In ECMAScript 6, you can simply use a block and a let declaration (or a const declaration):

  1. { // open block
  2. let tmp = ···;
  3. ···
  4. } // close block
  5.  
  6. console.log(tmp); // ReferenceError

More information: section “Avoid IIFEs in ES6”.

4.3 From concatenating strings to template literals

With ES6, JavaScript finally gets literals for string interpolation and multi-line strings.

4.3.1 String interpolation

In ES5, you put values into strings by concatenating those values and string fragments:

  1. function printCoord(x, y) {
  2. console.log('('+x+', '+y+')');
  3. }

In ES6 you can use string interpolation via template literals:

  1. function printCoord(x, y) {
  2. console.log(`(${x}, ${y})`);
  3. }

4.3.2 Multi-line strings

Template literals also help with representing multi-line strings.

For example, this is what you have to do to represent one in ES5:

  1. var HTML5_SKELETON =
  2. '<!doctype html>\n' +
  3. '<html>\n' +
  4. '<head>\n' +
  5. ' <meta charset="UTF-8">\n' +
  6. ' <title></title>\n' +
  7. '</head>\n' +
  8. '<body>\n' +
  9. '</body>\n' +
  10. '</html>\n';

If you escape the newlines via backslashes, things look a bit nicer (but you still have to explicitly add newlines):

  1. var HTML5_SKELETON = '\
  2. <!doctype html>\n\
  3. <html>\n\
  4. <head>\n\
  5. <meta charset="UTF-8">\n\
  6. <title></title>\n\
  7. </head>\n\
  8. <body>\n\
  9. </body>\n\
  10. </html>';

ES6 template literals can span multiple lines:

  1. const HTML5_SKELETON = `
  2. <!doctype html>
  3. <html>
  4. <head>
  5. <meta charset="UTF-8">
  6. <title></title>
  7. </head>
  8. <body>
  9. </body>
  10. </html>`;

(The examples differ in how much whitespace is included, but that doesn’t matter in this case.)

More information: chapter “Template literals and tagged templates”.

4.4 From function expressions to arrow functions

In current ES5 code, you have to be careful with this whenever you are using function expressions. In the following example, I create the helper variable _this (line A) so that the this of UiComponent can be accessed in line B.

  1. function UiComponent() {
  2. var _this = this; // (A)
  3. var button = document.getElementById('myButton');
  4. button.addEventListener('click', function () {
  5. console.log('CLICK');
  6. _this.handleClick(); // (B)
  7. });
  8. }
  9. UiComponent.prototype.handleClick = function () {
  10. ···
  11. };

In ES6, you can use arrow functions, which don’t shadow this (line A):

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

(In ES6, you also have the option of using a class instead of a constructor function. That is explored later.)

Arrow functions are especially handy for short callbacks that only return results of expressions.

In ES5, such callbacks are relatively verbose:

  1. var arr = [1, 2, 3];
  2. var squares = arr.map(function (x) { return x * x });

In ES6, arrow functions are much more concise:

  1. const arr = [1, 2, 3];
  2. const squares = arr.map(x => x * x);

When defining parameters, you can even omit parentheses if the parameters are just a single identifier. Thus: (x) => x x and x => x x are both allowed.

More information: chapter “Arrow functions”.

4.5 Handling multiple return values

Some functions or methods return multiple values via arrays or objects. In ES5, you always need to create intermediate variables if you want to access those values. In ES6, you can avoid intermediate variables via destructuring.

4.5.1 Multiple return values via arrays

exec() returns captured groups via an Array-like object. In ES5, you need an intermediate variable (matchObj in the example below), even if you are only interested in the groups:

  1. var matchObj =
  2. /^(\d\d\d\d)-(\d\d)-(\d\d)$/
  3. .exec('2999-12-31');
  4. var year = matchObj[1];
  5. var month = matchObj[2];
  6. var day = matchObj[3];

In ES6, destructuring makes this code simpler:

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

The empty slot at the beginning of the Array pattern skips the Array element at index zero.

4.5.2 Multiple return values via objects

The method Object.getOwnPropertyDescriptor() returns a property descriptor, an object that holds multiple values in its properties.

In ES5, even if you are only interested in the properties of an object, you still need an intermediate variable (propDesc in the example below):

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

In ES6, you can use destructuring:

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

{writable, configurable} is an abbreviation for:

  1. { writable: writable, configurable: configurable }

More information: chapter “Destructuring”.

4.6 From for to forEach() to for-of

Prior to ES5, you iterated over Arrays as follows:

  1. var arr = ['a', 'b', 'c'];
  2. for (var i=0; i<arr.length; i++) {
  3. var elem = arr[i];
  4. console.log(elem);
  5. }

In ES5, you have the option of using the Array method forEach():

  1. arr.forEach(function (elem) {
  2. console.log(elem);
  3. });

A for loop has the advantage that you can break from it, forEach() has the advantage of conciseness.

In ES6, the for-of loop combines both advantages:

  1. const arr = ['a', 'b', 'c'];
  2. for (const elem of arr) {
  3. console.log(elem);
  4. }

If you want both index and value of each array element, for-of has got you covered, too, via the new Array method entries() and destructuring:

  1. for (const [index, elem] of arr.entries()) {
  2. console.log(index+'. '+elem);
  3. }

More information: Chap. “The for-of loop”.

4.7 Handling parameter default values

In ES5, you specify default values for parameters like this:

  1. function foo(x, y) {
  2. x = x || 0;
  3. y = y || 0;
  4. ···
  5. }

ES6 has nicer syntax:

  1. function foo(x=0, y=0) {
  2. ···
  3. }

An added benefit is that in ES6, a parameter default value is only triggered by undefined, while it is triggered by any falsy value in the previous ES5 code.

More information: section “Parameter default values”.

4.8 Handling named parameters

A common way of naming parameters in JavaScript is via object literals (the so-called options object pattern):

  1. selectEntries({ start: 0, end: -1 });

Two advantages of this approach are: Code becomes more self-descriptive and it is easier to omit arbitrary parameters.

In ES5, you can implement selectEntries() as follows:

  1. function selectEntries(options) {
  2. var start = options.start || 0;
  3. var end = options.end || -1;
  4. var step = options.step || 1;
  5. ···
  6. }

In ES6, you can use destructuring in parameter definitions and the code becomes simpler:

  1. function selectEntries({ start=0, end=-1, step=1 }) {
  2. ···
  3. }

4.8.1 Making the parameter optional

To make the parameter options optional in ES5, you’d add line A to the code:

  1. function selectEntries(options) {
  2. options = options || {}; // (A)
  3. var start = options.start || 0;
  4. var end = options.end || -1;
  5. var step = options.step || 1;
  6. ···
  7. }

In ES6 you can specify {} as a parameter default value:

  1. function selectEntries({ start=0, end=-1, step=1 } = {}) {
  2. ···
  3. }

More information: section “Simulating named parameters”.

4.9 From arguments to rest parameters

In ES5, if you want a function (or method) to accept an arbitrary number of arguments, you must use the special variable arguments:

  1. function logAllArguments() {
  2. for (var i=0; i < arguments.length; i++) {
  3. console.log(arguments[i]);
  4. }
  5. }

In ES6, you can declare a rest parameter (args in the example below) via the operator:

  1. function logAllArguments(...args) {
  2. for (const arg of args) {
  3. console.log(arg);
  4. }
  5. }

Rest parameters are even nicer if you are only interested in trailing parameters:

  1. function format(pattern, ...args) {
  2. ···
  3. }

Handling this case in ES5 is clumsy:

  1. function format(pattern) {
  2. var args = [].slice.call(arguments, 1);
  3. ···
  4. }

Rest parameters make code easier to read: You can tell that a function has a variable number of parameters just by looking at its parameter definitions.

More information: section “Rest parameters”.

4.10 From apply() to the spread operator (…)

In ES5, you turn arrays into parameters via apply(). ES6 has the spread operator for this purpose.

4.10.1 Math.max()

Math.max() returns the numerically greatest of its arguments. It works for an arbitrary number of arguments, but not for Arrays.

ES5 – apply():

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

ES6 – spread operator:

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

4.10.2 Array.prototype.push()

Array.prototype.push() appends all of its arguments as elements to its receiver. There is no method that destructively appends an Array to another one.

ES5 – apply():

  1. var arr1 = ['a', 'b'];
  2. var arr2 = ['c', 'd'];
  3.  
  4. arr1.push.apply(arr1, arr2);
  5. // arr1 is now ['a', 'b', 'c', 'd']

ES6 – spread operator:

  1. const arr1 = ['a', 'b'];
  2. const arr2 = ['c', 'd'];
  3.  
  4. arr1.push(...arr2);
  5. // arr1 is now ['a', 'b', 'c', 'd']

More information: section “The spread operator ()”.

4.11 From concat() to the spread operator (…)

The spread operator can also (non-destructively) turn the contents of its operand into Array elements. That means that it becomes an alternative to the Array method concat().

ES5 – concat():

  1. var arr1 = ['a', 'b'];
  2. var arr2 = ['c'];
  3. var arr3 = ['d', 'e'];
  4.  
  5. console.log(arr1.concat(arr2, arr3));
  6. // [ 'a', 'b', 'c', 'd', 'e' ]

ES6 – spread operator:

  1. const arr1 = ['a', 'b'];
  2. const arr2 = ['c'];
  3. const arr3 = ['d', 'e'];
  4.  
  5. console.log([...arr1, ...arr2, ...arr3]);
  6. // [ 'a', 'b', 'c', 'd', 'e' ]

More information: section “The spread operator ()”.

4.12 From function expressions in object literals to method definitions

In JavaScript, methods are properties whose values are functions.

In ES5 object literals, methods are created like other properties. The property values are provided via function expressions.

  1. var obj = {
  2. foo: function () {
  3. ···
  4. },
  5. bar: function () {
  6. this.foo();
  7. }, // trailing comma is legal in ES5
  8. }

ES6 has method definitions, special syntax for creating methods:

  1. const obj = {
  2. foo() {
  3. ···
  4. },
  5. bar() {
  6. this.foo();
  7. },
  8. }

More information: section “Method definitions”.

4.13 From constructors to classes

ES6 classes are mostly just more convenient syntax for constructor functions.

4.13.1 Base classes

In ES5, you implement constructor functions directly:

  1. function Person(name) {
  2. this.name = name;
  3. }
  4. Person.prototype.describe = function () {
  5. return 'Person called '+this.name;
  6. };

In ES6, classes provide slightly more convenient syntax for constructor functions:

  1. class Person {
  2. constructor(name) {
  3. this.name = name;
  4. }
  5. describe() {
  6. return 'Person called '+this.name;
  7. }
  8. }

Note the compact syntax for method definitions – no keyword function needed. Also note that there are no commas between the parts of a class.

4.13.2 Derived classes

Subclassing is complicated in ES5, especially referring to super-constructors and super-properties. This is the canonical way of creating a sub-constructor Employee of Person:

  1. function Employee(name, title) {
  2. Person.call(this, name); // super(name)
  3. this.title = title;
  4. }
  5. Employee.prototype = Object.create(Person.prototype);
  6. Employee.prototype.constructor = Employee;
  7. Employee.prototype.describe = function () {
  8. return Person.prototype.describe.call(this) // super.describe()
  9. + ' (' + this.title + ')';
  10. };

ES6 has built-in support for subclassing, via the extends clause:

  1. class Employee extends Person {
  2. constructor(name, title) {
  3. super(name);
  4. this.title = title;
  5. }
  6. describe() {
  7. return super.describe() + ' (' + this.title + ')';
  8. }
  9. }

More information: chapter “Classes”.

4.14 From custom error constructors to subclasses of Error

In ES5, it is impossible to subclass the built-in constructor for exceptions, Error. The following code shows a work-around that gives the constructor MyError important features such as a stack trace:

  1. function MyError() {
  2. // Use Error as a function
  3. var superInstance = Error.apply(null, arguments);
  4. copyOwnPropertiesFrom(this, superInstance);
  5. }
  6. MyError.prototype = Object.create(Error.prototype);
  7. MyError.prototype.constructor = MyError;
  8.  
  9. function copyOwnPropertiesFrom(target, source) {
  10. Object.getOwnPropertyNames(source)
  11. .forEach(function(propKey) {
  12. var desc = Object.getOwnPropertyDescriptor(source, propKey);
  13. Object.defineProperty(target, propKey, desc);
  14. });
  15. return target;
  16. };

In ES6, all built-in constructors can be subclassed, which is why the following code achieves what the ES5 code can only simulate:

  1. class MyError extends Error {
  2. }

More information: section “Subclassing built-in constructors”.

4.15 From objects to Maps

Using the language construct object as a map from strings to arbitrary values (a data structure) has always been a makeshift solution in JavaScript. The safest way to do so is by creating an object whose prototype is null. Then you still have to ensure that no key is ever the string 'proto', because that property key triggers special functionality in many JavaScript engines.

The following ES5 code contains the function countWords that uses the object dict as a map:

  1. var dict = Object.create(null);
  2. function countWords(word) {
  3. var escapedWord = escapeKey(word);
  4. if (escapedWord in dict) {
  5. dict[escapedWord]++;
  6. } else {
  7. dict[escapedWord] = 1;
  8. }
  9. }
  10. function escapeKey(key) {
  11. if (key.indexOf('__proto__') === 0) {
  12. return key+'%';
  13. } else {
  14. return key;
  15. }
  16. }

In ES6, you can use the built-in data structure Map and don’t have to escape keys. As a downside, incrementing values inside Maps is less convenient.

  1. const map = new Map();
  2. function countWords(word) {
  3. const count = map.get(word) || 0;
  4. map.set(word, count + 1);
  5. }

Another benefit of Maps is that you can use arbitrary values as keys, not just strings.

More information:

4.16 New string methods

The ECMAScript 6 standard library provides several new methods for strings.

From indexOf to startsWith:

  1. if (str.indexOf('x') === 0) {} // ES5
  2. if (str.startsWith('x')) {} // ES6

From indexOf to endsWith:

  1. function endsWith(str, suffix) { // ES5
  2. var index = str.indexOf(suffix);
  3. return index >= 0
  4. && index === str.length-suffix.length;
  5. }
  6. str.endsWith(suffix); // ES6

From indexOf to includes:

  1. if (str.indexOf('x') >= 0) {} // ES5
  2. if (str.includes('x')) {} // ES6

From join to repeat (the ES5 way of repeating a string is more of a hack):

  1. new Array(3+1).join('#') // ES5
  2. '#'.repeat(3) // ES6

More information: Chapter “New string features

4.17 New Array methods

There are also several new Array methods in ES6.

4.17.1 From Array.prototype.indexOf to Array.prototype.findIndex

The latter can be used to find NaN, which the former can’t detect:

  1. const arr = ['a', NaN];
  2.  
  3. arr.indexOf(NaN); // -1
  4. arr.findIndex(x => Number.isNaN(x)); // 1

As an aside, the new Number.isNaN() provides a safe way to detect NaN (because it doesn’t coerce non-numbers to numbers):

  1. > isNaN('abc')
  2. true
  3. > Number.isNaN('abc')
  4. false

4.17.2 From Array.prototype.slice() to Array.from() or the spread operator

In ES5, Array.prototype.slice() was used to convert Array-like objects to Arrays. In ES6, you have Array.from():

  1. var arr1 = Array.prototype.slice.call(arguments); // ES5
  2. const arr2 = Array.from(arguments); // ES6

If a value is iterable (as all Array-like DOM data structure are by now), you can also use the spread operator () to convert it to an Array:

  1. const arr1 = [...'abc'];
  2. // ['a', 'b', 'c']
  3. const arr2 = [...new Set().add('a').add('b')];
  4. // ['a', 'b']

4.17.3 From apply() to Array.prototype.fill()

In ES5, you can use apply(), as a hack, to create in Array of arbitrary length that is filled with undefined:

  1. // Same as Array(undefined, undefined)
  2. var arr1 = Array.apply(null, new Array(2));
  3. // [undefined, undefined]

In ES6, fill() is a simpler alternative:

  1. const arr2 = new Array(2).fill(undefined);
  2. // [undefined, undefined]

fill() is even more convenient if you want to create an Array that is filled with an arbitrary value:

  1. // ES5
  2. var arr3 = Array.apply(null, new Array(2))
  3. .map(function (x) { return 'x' });
  4. // ['x', 'x']
  5.  
  6. // ES6
  7. const arr4 = new Array(2).fill('x');
  8. // ['x', 'x']

fill() replaces all Array elements with the given value. Holes are treated as if they were elements.

More information: Sect. “Creating Arrays filled with values

4.18 From CommonJS modules to ES6 modules

Even in ES5, module systems based on either AMD syntax or CommonJS syntax have mostly replaced hand-written solutions such as the revealing module pattern.

ES6 has built-in support for modules. Alas, no JavaScript engine supports them natively, yet. But tools such as browserify, webpack or jspm let you use ES6 syntax to create modules, making the code you write future-proof.

4.18.1 Multiple exports

4.18.1.1 Multiple exports in CommonJS

In CommonJS, you export multiple entities as follows:

  1. //------ lib.js ------
  2. var sqrt = Math.sqrt;
  3. function square(x) {
  4. return x * x;
  5. }
  6. function diag(x, y) {
  7. return sqrt(square(x) + square(y));
  8. }
  9. module.exports = {
  10. sqrt: sqrt,
  11. square: square,
  12. diag: diag,
  13. };
  14.  
  15. //------ main1.js ------
  16. var square = require('lib').square;
  17. var diag = require('lib').diag;
  18.  
  19. console.log(square(11)); // 121
  20. console.log(diag(4, 3)); // 5

Alternatively, you can import the whole module as an object and access square and diag via it:

  1. //------ main2.js ------
  2. var lib = require('lib');
  3. console.log(lib.square(11)); // 121
  4. console.log(lib.diag(4, 3)); // 5
4.18.1.2 Multiple exports in ES6

In ES6, multiple exports are called named exports and handled like this:

  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. //------ main1.js ------
  11. import { square, diag } from 'lib';
  12. console.log(square(11)); // 121
  13. console.log(diag(4, 3)); // 5

The syntax for importing modules as objects looks as follows (line A):

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

4.18.2 Single exports

4.18.2.1 Single exports in CommonJS

Node.js extends CommonJS and lets you export single values from modules, via module.exports:

  1. //------ myFunc.js ------
  2. module.exports = function () { ··· };
  3.  
  4. //------ main1.js ------
  5. var myFunc = require('myFunc');
  6. myFunc();
4.18.2.2 Single exports in ES6

In ES6, the same thing is done via a so-called default export (declared via export default):

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

More information: chapter “Modules”.

4.19 What to do next

Now that you got a first taste of ES6, you can continue your exploration by browsing the chapters: Each chapter covers a feature or a set of related features and starts with an overview. The last chapter collects all of these overview sections in a single location.