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.
var
to const
/let
for
to forEach()
to for-of
arguments
to rest parameters
apply()
to the spread operator (...
)
Math.max()
Array.prototype.push()
concat()
to the spread operator (...
)
Error
Array.prototype.indexOf
to Array.prototype.findIndex
Array.prototype.slice()
to Array.from()
or the spread operatorapply()
to Array.prototype.fill()
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:
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:
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:
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:
const
. You can use it for all variables whose values never change.let
– for variables whose values do change.var
.More information: chapter “Variables and scoping”.
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:
In ECMAScript 6, you can simply use a block and a let
declaration (or a const
declaration):
More information: section “Avoid IIFEs in ES6”.
With ES6, JavaScript finally gets literals for string interpolation and multi-line strings.
In ES5, you put values into strings by concatenating those values and string fragments:
In ES6 you can use string interpolation via template literals:
Template literals also help with representing multi-line strings.
For example, this is what you have to do to represent one in ES5:
If you escape the newlines via backslashes, things look a bit nicer (but you still have to explicitly add newlines):
ES6 template literals can span multiple lines:
(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”.
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.
In ES6, you can use arrow functions, which don’t shadow this
(line A):
(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:
In ES6, arrow functions are much more concise:
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”.
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.
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:
In ES6, destructuring makes this code simpler:
The empty slot at the beginning of the Array pattern skips the Array element at index zero.
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):
In ES6, you can use destructuring:
{writable, configurable}
is an abbreviation for:
More information: chapter “Destructuring”.
for
to forEach()
to for-of
Prior to ES5, you iterated over Arrays as follows:
In ES5, you have the option of using the Array method forEach()
:
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:
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:
More information: Chap. “The for-of
loop”.
In ES5, you specify default values for parameters like this:
ES6 has nicer syntax:
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”.
A common way of naming parameters in JavaScript is via object literals (the so-called options object pattern):
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:
In ES6, you can use destructuring in parameter definitions and the code becomes simpler:
To make the parameter options
optional in ES5, you’d add line A to the code:
In ES6 you can specify {}
as a parameter default value:
More information: section “Simulating named parameters”.
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
:
In ES6, you can declare a rest parameter (args
in the example below) via the ...
operator:
Rest parameters are even nicer if you are only interested in trailing parameters:
Handling this case in ES5 is clumsy:
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”.
apply()
to the spread operator (...
) In ES5, you turn arrays into parameters via apply()
. ES6 has the spread operator for this purpose.
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()
:
ES6 – spread operator:
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()
:
ES6 – spread operator:
More information: section “The spread operator (...
)”.
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()
:
ES6 – spread operator:
More information: section “The spread operator (...
)”.
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.
ES6 has method definitions, special syntax for creating methods:
More information: section “Method definitions”.
ES6 classes are mostly just more convenient syntax for constructor functions.
In ES5, you implement constructor functions directly:
In ES6, classes provide slightly more convenient syntax for constructor functions:
Note the compact syntax for method definitions – no keyword function
needed. Also note that there are no commas between the parts of a class.
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
:
ES6 has built-in support for subclassing, via the extends
clause:
More information: chapter “Classes”.
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:
In ES6, all built-in constructors can be subclassed, which is why the following code achieves what the ES5 code can only simulate:
More information: section “Subclassing built-in constructors”.
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:
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.
Another benefit of Maps is that you can use arbitrary values as keys, not just strings.
More information:
The ECMAScript 6 standard library provides several new methods for strings.
From indexOf
to startsWith
:
From indexOf
to endsWith
:
From indexOf
to includes
:
From join
to repeat
(the ES5 way of repeating a string is more of a hack):
More information: Chapter “New string features”
There are also several new Array methods in ES6.
Array.prototype.indexOf
to Array.prototype.findIndex
The latter can be used to find NaN
, which the former can’t detect:
As an aside, the new Number.isNaN()
provides a safe way to detect NaN
(because it doesn’t coerce non-numbers to numbers):
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()
:
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:
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
:
In ES6, fill()
is a simpler alternative:
fill()
is even more convenient if you want to create an Array that is filled with an arbitrary value:
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”
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.
In CommonJS, you export multiple entities as follows:
Alternatively, you can import the whole module as an object and access square
and diag
via it:
In ES6, multiple exports are called named exports and handled like this:
The syntax for importing modules as objects looks as follows (line A):
Node.js extends CommonJS and lets you export single values from modules, via module.exports
:
In ES6, the same thing is done via a so-called default export (declared via export default
):
More information: chapter “Modules”.
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.