Js Book
Js Book
2024-07-06
“An exhaustive resource, yet cuts out the fluff that clutters many
programming books – with explanations that are understandable and to
the point, as promised by the title! The quizzes and exercises are a very
useful feature to check and lock in your knowledge. And you can
definitely tear through the book fairly quickly, to get up and running in
JavaScript.”
— Pam Selle, thewebivore.com
All rights reserved. This book or any portion thereof may not be reproduced or used in
any manner whatsoever without the express written permission of the publisher except
for the use of brief quotations in a book review or scholarly journal.
ISBN 978-1-09-121009-7
exploringjs.com
Table of contents
I Background 11
3 Why JavaScript? 21
3.1 The cons of JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.2 The pros of JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.3 Pro and con of JavaScript: innovation . . . . . . . . . . . . . . . . . . . . 23
3
4
7 FAQ: JavaScript 47
7.1 What are good references for JavaScript? . . . . . . . . . . . . . . . . . . . 47
7.2 How do I find out what JavaScript features are supported where? . . . . . 47
7.3 Where can I look up what features are planned for JavaScript? . . . . . . . 48
7.4 Why does JavaScript fail silently so often? . . . . . . . . . . . . . . . . . . 48
7.5 Why can’t we clean up JavaScript, by removing quirks and outdated features? 48
7.6 How can I quickly try out a piece of JavaScript code? . . . . . . . . . . . . 48
II First steps 49
9 Syntax 53
9.1 An overview of JavaScript’s syntax . . . . . . . . . . . . . . . . . . . . . . 54
9.2 (Advanced) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
9.3 Hashbang lines (Unix shell scripts) . . . . . . . . . . . . . . . . . . . . . . 61
9.4 Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
9.5 Statement vs. expression . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
9.6 Ambiguous syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
9.7 Semicolons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
9.8 Automatic semicolon insertion (ASI) . . . . . . . . . . . . . . . . . . . . . 66
9.9 Semicolons: best practices . . . . . . . . . . . . . . . . . . . . . . . . . . 68
9.10 Strict mode vs. sloppy mode . . . . . . . . . . . . . . . . . . . . . . . . . 68
11 Assertion API 77
11.1 Assertions in software development . . . . . . . . . . . . . . . . . . . . . 77
11.2 How assertions are used in this book . . . . . . . . . . . . . . . . . . . . . 77
11.3 Normal comparison vs. deep comparison . . . . . . . . . . . . . . . . . . 78
11.4 Quick reference: module assert . . . . . . . . . . . . . . . . . . . . . . . 79
5
14 Values 103
14.1 What’s a type? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
14.2 JavaScript’s type hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . 104
14.3 The types of the language specification . . . . . . . . . . . . . . . . . . . 104
14.4 Primitive values vs. objects . . . . . . . . . . . . . . . . . . . . . . . . . . 105
14.5 The operators typeof and instanceof: what’s the type of a value? . . . . . 108
14.6 Classes and constructor functions . . . . . . . . . . . . . . . . . . . . . . 109
14.7 Converting between types . . . . . . . . . . . . . . . . . . . . . . . . . . 110
15 Operators 113
15.1 Making sense of operators . . . . . . . . . . . . . . . . . . . . . . . . . . 113
15.2 The plus operator (+) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
15.3 Assignment operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
15.4 Equality: == vs. === . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
15.5 Ordering operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
15.6 Various other operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
17 Booleans 131
17.1 Converting to boolean . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
17.2 Falsy and truthy values . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
6
18 Numbers 139
18.1 Numbers are used for both floating point numbers and integers . . . . . . 140
18.2 Number literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
18.3 Arithmetic operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
18.4 Converting to number . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
18.5 Error values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
18.6 The precision of numbers: careful with decimal fractions . . . . . . . . . . 148
18.7 (Advanced) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
18.8 Background: floating point precision . . . . . . . . . . . . . . . . . . . . . 148
18.9 Integer numbers in JavaScript . . . . . . . . . . . . . . . . . . . . . . . . 150
18.10Bitwise operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
18.11 Quick reference: numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
19 Math 161
19.1 Data properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
19.2 Exponents, roots, logarithms . . . . . . . . . . . . . . . . . . . . . . . . . 162
19.3 Rounding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
19.4 Trigonometric Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
19.5 Various other functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
19.6 Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
22 Strings 187
22.1 Cheat sheet: strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
22.2 Plain string literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
22.3 Accessing JavaScript characters . . . . . . . . . . . . . . . . . . . . . . . . 191
22.4 String concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
22.5 Converting to string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
22.6 Comparing strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
7
22.7 Atoms of text: code points, JavaScript characters, grapheme clusters . . . . 195
22.8 Quick reference: Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
VI Modularity 271
29 Modules [ES6] 273
29.1 Cheat sheet: modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
29.2 JavaScript source code formats . . . . . . . . . . . . . . . . . . . . . . . . 276
29.3 Before we had modules, we had scripts . . . . . . . . . . . . . . . . . . . 277
29.4 Module systems created prior to ES6 . . . . . . . . . . . . . . . . . . . . . 278
29.5 ECMAScript modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
29.6 Named exports and imports . . . . . . . . . . . . . . . . . . . . . . . . . 281
29.7 Default exports and imports . . . . . . . . . . . . . . . . . . . . . . . . . 283
29.8 Re-exporting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
29.9 More details on exporting and importing . . . . . . . . . . . . . . . . . . 286
29.10npm packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
29.11 Naming modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
29.12Module specifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
29.13 import.meta – metadata for the current module [ES2020] . . . . . . . . . . . 292
[ES2020]
29.14Loading modules dynamically via import() (advanced) . . . . . . . 294
[ES2022]
29.15Top-level await in modules (advanced) . . . . . . . . . . . . . . . . 297
29.16Polyfills: emulating native web platform features (advanced) . . . . . . . 299
30 Objects 301
30.1 Cheat sheet: objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
30.2 What is an object? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
30.3 Fixed-layout objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
30.4 Spreading into object literals (...) [ES2018] . . . . . . . . . . . . . . . . . . 309
30.5 Methods and the special variable this . . . . . . . . . . . . . . . . . . . . 312
30.6 Optional chaining for property getting and method calls [ES2020] (advanced) 318
30.7 Dictionary objects (advanced) . . . . . . . . . . . . . . . . . . . . . . . . 322
30.8 Property attributes and property descriptors [ES5] (advanced) . . . . . . . . 331
[ES5]
30.9 Protecting objects from being changed (advanced) . . . . . . . . . . . 333
30.10Prototype chains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
30.11 FAQ: objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
30.12Quick reference: Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
30.13Quick reference: Reflect . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
Background
11
Chapter 1
Highlights:
No prior knowledge of JavaScript is required, but you should know how to program.
13
14 1 Before you buy the book
Since 2011, he has been blogging about web development at 2ality.com and has written
several books on JavaScript. He has held trainings and talks for companies such as eBay,
Bank of America, and O’Reilly Media.
1.4 Acknowledgements
• Cover image by Fran Caye
• Thanks for answering questions, discussing language topics, etc.:
– Allen Wirfs-Brock
– Benedikt Meurer
– Brian Terlson
– Daniel Ehrenberg
– Jordan Harband
– Maggie Johnson-Pint
– Mathias Bynens
– Myles Borins
1.4 Acknowledgements 15
– Rob Palmer
– Šime Vidas
– And many others
• Thanks for reviewing:
– Johannes Weber
16 1 Before you buy the book
Chapter 2
This chapter answers questions you may have and gives tips for reading this book.
17
18 2 FAQ: book and supplementary material
• It gives you a comprehensive look at current JavaScript. In this “mode”, you read
everything and don’t skip advanced content and quick references.
• It serves as a reference. If there is a topic that you are interested in, you can find in-
formation on it via the table of contents or via the index. Due to basic and advanced
content being mixed, everything you need is usually in a single location.
Exercises play an important part in helping you practice and retain what you have learned.
2.1.2 Why are some chapters and sections marked with “(advanced)”?
Several chapters and sections are marked with “(advanced)”. The idea is that you can
initially skip them. That is, you can get a quick working knowledge of JavaScript by only
reading the basic (non-advanced) content.
As your knowledge evolves, you can later come back to some or all of the advanced con-
tent.
• If you opted into emails while buying, you’ll get an email whenever there is new
content. To opt in later, you must contact Payhip (see bottom of payhip.com).
Alas, the reverse is not possible: you cannot get a discount for the print version if you
bought a digital version.
2.4 Notations and conventions 19
That is called the type signature of Number.isFinite(). This notation, especially the static
types number of num and boolean of the result, are not real JavaScript. The notation is bor-
rowed from the compile-to-JavaScript language TypeScript (which is mostly just JavaScript
plus static typing).
Why is this notation being used? It helps give you a quick idea of how a function works.
The notation is explained in detail in “Tackling TypeScript”, but is usually relatively intu-
itive.
Reading instructions
Explains how to best read the content.
External content
Points to additional, external, content.
Tip
Gives a tip related to the current content.
Question
Asks and answers a question pertinent to the current content (think FAQ).
20 2 FAQ: book and supplementary material
Warning
Warns about pitfalls, etc.
Details
Provides additional details, complementing the current content. It is similar to a
footnote.
Exercise
Mentions the path of a test-driven exercise that you can do at that point.
Chapter 3
Why JavaScript?
Additionally, many traditional quirks have been eliminated now. For example:
21
22 3 Why JavaScript?
• Prior to ES6, implementing object factories and inheritance via function and .pro-
totype was clumsy. ES6 introduced classes, which provide more convenient syntax
for these mechanisms.
• Traditionally, JavaScript did not have built-in modules. ES6 added them to the lan-
guage.
3.2.1 Community
JavaScript’s popularity means that it’s well supported and well documented. Whenever
you create something in JavaScript, you can rely on many people being (potentially) in-
terested. And there is a large pool of JavaScript programmers from which you can hire, if
you need to.
• Progressive Web Apps can be installed natively on Android and many desktop oper-
ating systems.
• Electron lets you build cross-platform desktop apps.
• React Native lets you write apps for iOS and Android that have native user interfaces.
• Node.js provides extensive support for writing shell scripts (in addition to being a
platform for web servers).
• Node.js (many of the following services are based on Node.js or support its APIs)
• ZEIT Now
• Microsoft Azure Functions
• AWS Lambda
• Google Cloud Functions
There are many data technologies available for JavaScript: many databases support it and
intermediate layers (such as GraphQL) exist. Additionally, the standard data format JSON
(JavaScript Object Notation) is based on JavaScript and supported by its standard library.
3.3 Pro and con of JavaScript: innovation 23
Lastly, many, if not most, tools for JavaScript are written in JavaScript. That includes IDEs,
build tools, and more. As a consequence, you install them the same way you install your
libraries and you can customize them in JavaScript.
3.2.3 Language
• Many libraries are available, via the de-facto standard in the JavaScript universe, the
npm software registry.
• If you are unhappy with “plain” JavaScript, it is relatively easy to add more features:
– You can compile future and modern language features to current and past ver-
sions of JavaScript, via Babel.
– You can add static typing, via TypeScript and Flow.
– You can work with ReasonML, which is, roughly, OCaml with JavaScript syn-
tax. It can be compiled to JavaScript or native code.
• The language is flexible: it is dynamic and supports both object-oriented program-
ming and functional programming.
• JavaScript has become suprisingly fast for such a dynamic language.
– Whenever it isn’t fast enough, you can switch to WebAssembly, a universal
virtual machine built into most JavaScript engines. It can run static code at
nearly native speeds.
25
26 4 The nature of JavaScript
• It is a dynamically typed language: variables don’t have fixed static types and you
can assign any value to a given (mutable) variable.
• It is deployed as source code. But that source code is often minified (rewritten to
require less storage). And there are plans for a binary source code format.
• JavaScript is part of the web platform – it is the language built into web browsers.
But it is also used elsewhere – for example, in Node.js, for server things, and shell
scripting.
• JavaScript engines often optimize less-efficient language mechanisms under the hood.
For example, in principle, JavaScript Arrays are dictionaries. But under the hood,
engines store Arrays contiguously if they have contiguous indices.
First example: If the operands of an operator don’t have the appropriate types, they are
converted as necessary.
Second example: If an arithmetic computation fails, you get an error value, not an excep-
tion.
> 1 / 0
Infinity
The reason for the silent failures is historical: JavaScript did not have exceptions until
ECMAScript 3. Since then, its designers have tried to avoid silent failures.
• Take your time to really get to know this language. The conventional C-style syntax
hides that this is a very unconventional language. Learn especially the quirks and
the rationales behind them. Then you will understand and appreciate the language
better.
– In addition to details, this book also teaches simple rules of thumb to be safe –
for example, “Always use === to determine if two values are equal, never ==.”
4.3 Tips for getting started with JavaScript 27
– Social media services such as Mastodon are popular among JavaScript pro-
grammers. As a mode of communication that sits between the spoken and the
written word, it is well suited for exchanging knowledge.
– Many cities have regular free meetups where people come together to learn
topics related to JavaScript.
– JavaScript conferences are another convenient way of meeting other JavaScript
programmers.
The idea was that major interactive parts of the client-side web were to be implemented
in Java. JavaScript was supposed to be a glue language for those parts and to also make
HTML slightly more interactive. Given its role of assisting Java, JavaScript had to look like
Java. That ruled out existing solutions such as Perl, Python, TCL, and others.
29
30 5 History and evolution of JavaScript
• In the Netscape Navigator 2.0 betas (September 1995), it was called LiveScript.
• In Netscape Navigator 2.0 beta 3 (December 1995), it got its final name, JavaScript.
The language described by these standards is called ECMAScript, not JavaScript. A differ-
ent name was chosen because Sun (now Oracle) had a trademark for the latter name. The
“ECMA” in “ECMAScript” comes from the organization that hosts the primary standard.
The original name of that organization was ECMA, an acronym for European Computer
Manufacturers Association. It was later changed to Ecma International (with “Ecma” being a
proper name, not an acronym) because the organization’s activities had expanded beyond
Europe. The initial all-caps acronym explains the spelling of ECMAScript.
Often, JavaScript and ECMAScript mean the same thing. Sometimes the following dis-
tinction is made:
• ECMAScript 2016 (June 2016): First yearly release. The shorter release life cycle
resulted in fewer new features compared to the large ES6.
• ECMAScript 2017 (June 2017). Second yearly release.
• Subsequent ECMAScript versions (ES2018, etc.) are always ratified in June.
Every two months, TC39 has meetings that member-appointed delegates and invited ex-
perts attend. The minutes of those meetings are public in a GitHub repository.
Outside of meetings, TC39 also collaborates with various members and groups of the
JavaScript community.
• If too much time passes between releases then features that are ready early, have to
wait a long time until they can be released. And features that are ready late, risk
being rushed to make the deadline.
• Features were often designed long before they were implemented and used. Design
deficiencies related to implementation and use were therefore discovered too late.
• ECMAScript features are designed independently and go through six stages: a straw-
person stage 0 and five “maturity” stages (1, 2, 2.7, 3, 4).
• Especially the later stages require prototype implementations and real-world test-
ing, leading to feedback loops between designs and implementations.
• ECMAScript versions are released once per year and include all features that have
reached stage 4 prior to a release deadline.
The result: smaller, incremental releases, whose features have already been field-tested.
ES2016 was the first ECMAScript version that was designed according to the TC39 process.
5.5.1 Tip: Think in individual features and stages, not ECMAScript ver-
sions
Up to and including ES6, it was most common to think about JavaScript in terms of ECMA-
Script versions – for example, “Does this browser support ES6 yet?”
Starting with ES2016, it’s better to think in individual features: once a feature reaches stage
4, we can safely use it (if it’s supported by the JavaScript engines we are targeting). We
don’t have to wait until the next ECMAScript release.
32 5 History and evolution of JavaScript
• Stage 0 means a proposal has yet to enter the actual process. This is where most
proposals start.
• Then the proposal goes through the five maturity stages 1, 2, 2.7, 3 and 4. If it reaches
stage 4, it is complete and ready for inclusion in the ECMAScript standard.
– If a proposal makes it to stage 4, its tests are integrated into Test262, the official
ECMAScript conformance test suite.
Each stage has entrance criteria regarding the state of the artifacts:
• Reviewer: Reviewers give feedback for the specification during stage 2 and must
sign off on it before the proposal can reach stage 2.7. They are appointed by TC39
(excluding the authors and champions of the proposal).
• Editor: Someone in charge of managing the ECMAScript specification. The current
editors are listed at the beginning of the ECMAScript specification.
– Not part of the usual advancement process. Any author can create a draft
proposal and assign it stage 0.
– Entrance criteria:
* Pick champions
* Repository with proposal
– Status:
* Proposal is under consideration.
• Stage 2: refining the solution
– Entrance criteria:
* Proposal is complete.
* Draft of specification.
– Status:
* Proposal is likely (but not guaranteed) to be standardized.
• Stage 2.7: testing and validation
– Entrance criteria:
* Specification is complete and approved by reviewers and editors.
– Status:
* The specification is finished. It’s time to validate it through tests and spec-
compliant prototypes.
* No more changes, aside from issues discovered through validation.
• Stage 3: gaining implementation experience
– Entrance criteria:
* Tests are finished.
– Status:
* The proposal is ready to be implemented.
* No changes except if web incompatibilities are discovered.
• Stage 4: integration into draft specification and eventual inclusion in standard
– Entrance criteria:
* Two implementation that pass the tests
* Significant in-the-field experience with shipping implementations
* Pull request for TC39 repository, approved by editors
– Status:
* Proposed feature is complete:
34 5 History and evolution of JavaScript
finished specification
two implementations
Figure 5.1: Each ECMAScript feature proposal goes through stages that are numbered from
0 to 4.
Let’s assume we create a new version of JavaScript that is not backward compatible and
fixes all of its flaws. As a result, we’d encounter the following problems:
• JavaScript engines become bloated: they need to support both the old and the new
version. The same is true for tools such as IDEs and build tools.
5.7 FAQ: ECMAScript and TC39 35
• Programmers need to know, and be continually conscious of, the differences be-
tween the versions.
• We can either migrate all of an existing code base to the new version (which can be
a lot of work). Or we can mix versions and refactoring becomes harder because we
can’t move code between versions without changing it.
• We somehow have to specify per piece of code – be it a file or code embedded in a
web page – what version it is written in. Every conceivable solution has pros and
cons. For example, strict mode is a slightly cleaner version of ES5. One of the reasons
why it wasn’t as popular as it should have been: it was a hassle to opt in via a
directive at the beginning of a file or a function.
• New versions are always completely backward compatible (but there may occasion-
ally be minor, hardly noticeable clean-ups).
• Old features aren’t removed or fixed. Instead, better versions of them are intro-
duced. One example is declaring variables via let – which is an improved version
of var.
• If aspects of the language are changed, it is done inside new syntactic constructs.
That is, we opt in implicitly – for example:
• In this book, there is a chapter that lists what’s new in each ECMAScript version. It
also links to explanations.
• The TC39 repository has a table with finished proposals that states in which ECMA-
Script versions they were (or will be) introduced.
• Section “Introduction” of the ECMAScript language specification lists the new fea-
tures of each ECMAScript version.
This chapter lists what’s new in recent ECMAScript versions – in reverse chronological or-
der. It ends before ES6 (ES2015): ES2016 was the first truly incremental release of ECMA-
Script – which is why ES6 has too many features to list here. If you want to get a feeling
for earlier releases:
Map.groupBy() groups the items of an iterable into Map entries whose keys are pro-
vided by a callback:
assert.deepEqual(
Map.groupBy([0, -5, 3, -4, 8, 9], x => Math.sign(x)),
new Map()
37
38 6 New JavaScript features
.set(0, [0])
.set(-1, [-5,-4])
.set(1, [3,8,9])
);
assert.deepEqual(
Object.groupBy([0, -5, 3, -4, 8, 9], x => Math.sign(x)),
{
'0': [0],
'-1': [-5,-4],
'1': [3,8,9],
__proto__: null,
}
);
> /^[\q{💫😵}]$/v.test('💫😵')
true
> /^[\q{abc|def}]$/v.test('abc')
true
> /^[\w--[a-g]]$/v.test('a')
false
> /^[\p{Number}--[0-9]]$/v.test('٣')
true
> /^[\p{RGI_Emoji}--\q{💫😵}]$/v.test('💫😵')
false
• SharedArrayBuffers can be resized, but they can only grow and never shrink. They
are not transferrable and therefore don’t get the method .transfer() that Array-
Buffers got.
• Two new methods help us ensure that strings are well-formed (w.r.t. UTF-16 code
units):
• “Array find from last”: Arrays and Typed Arrays get two new methods:
• Symbols as WeakMap keys: Before this feature, only objects could be used as keys
in WeakMaps. This feature also lets us use symbols – except for registered symbols
(created via Symbol.for()).
• “Hashbang grammar”: JavaScript now ignores the first line of a file if it starts with
a hash (#) and a bang (!). Some JavaScript runtimes, such as Node.js, have done this
for a long time. Now it is also part of the language proper. This is an example of a
“hashbang” line:
#!/usr/bin/env node
• Private slot checks (“ergonomic brand checks for private fields”): The following
expression checks if obj has a private slot #privateSlot:
#privateSlot in obj
• Top-level await in modules: We can now use await at the top levels of modules and
don’t have to enter async functions or methods anymore.
• error.cause: Error and its subclasses now let us specify which error caused the
current one:
• Method .at() of indexable values lets us read an element at a given index (like the
bracket operator []) and supports negative indices (unlike the bracket operator).
– string
– Array
– All Typed Array classes: Uint8Array etc.
We use Promise.any() when we are only interested in the first fulfilled Promise
among several.
a ||= b
a &&= b
a ??= b
42 6 New JavaScript features
• WeakRefs: This feature is beyond the scope of this book. Quoting its proposal states:
• Array.prototype.sort has been stable since ES2019. In ES2021, “[it] was made more
precise, reducing the amount of cases that result in an implementation-defined sort
order” [source]. For more information, see the pull request for this improvement.
– import.meta contains metadata for the current module. Its first widely sup-
ported property is import.meta.url which contains a string with the URL of
the current module’s file.
• Optional chaining for property accesses and method calls. One example of optional
chaining is:
value?.prop
value ?? defaultValue
This expression is defaultValue if value is either undefined or null and value oth-
erwise. This operator lets us use a default value whenever something is missing.
Previously the Logical Or operator (||) was used in this case but it has downsides
here because it returns the default value whenever the left-hand side is falsy (which
isn’t always correct).
6.6 New in ECMAScript 2019 43
• globalThis provides a way to access the global object that works both on browsers
and server-side platforms such as Node.js and Deno.
• for-in mechanics: This feature is beyond the scope of this book. For more informa-
tion on it, see its proposal.
• Namespace re-exporting:
• Array method .flat() converts nested Arrays into flat Arrays. Optionally, we can
tell it at which depth of nesting it should stop flattening.
• String methods: .trimStart() and .trimEnd() work like .trim() but remove white-
space only at the start or only at the end of a string.
• Optional catch binding: We can now omit the parameter of a catch clause if we
don’t use it.
• .sort() for Arrays and Typed Arrays is now guaranteed to be stable: If elements
are considered equal by sorting, then sorting does not change the order of those
elements (relative to each other).
– With synchronous iterables, we can immediately access each item. With asyn-
chronous iterables, we have to await before we can access an item.
– With synchronous iterables, we use for-of loops. With asynchronous iter-
ables, we use for-await-of loops.
• Spreading into object literals: By using spreading (...) inside an object literal, we
can copy the properties of another object into the current one. One use case is to
create a shallow copy of an object obj:
– s (dotAll) flag for regular expressions. If this flag is active, the dot matches
line terminators (by default, it doesn’t).
– RegExp Unicode property escapes give us more power when matching sets of
Unicode code points – for example:
> /^\p{Lowercase_Letter}+$/u.test('aüπ')
true
6.8 New in ECMAScript 2017 45
• Template literal revision allows text with backslashes in tagged templates that is
illegal in string literals – for example:
windowsPath`C:\uuu\xxx\111`
latex`\unicode`
• Object.entries() returns an Array with the key-value pairs of all enumerable string-
keyed properties of a given object. Each pair is encoded as a two-element Array.
• String padding: The string methods .padStart() and .padEnd() insert padding text
until the receivers are long enough:
• Trailing commas in function parameter lists and calls: Trailing commas have been
allowed in Arrays literals since ES3 and in Object literals since ES5. They are now
also allowed in function calls and method calls.
• The feature “Shared memory and atomics” is beyond the scope of this book. For
more information on it, see:
> 4 ** 2
16
46 6 New JavaScript features
FAQ: JavaScript
• Mozilla’s MDN web docs have tables for each feature that describe relevant ECMA-
Script versions and browser support.
• “Can I use…” documents what features (including JavaScript language features) are
supported by web browsers.
• ECMAScript compatibility tables for various engines
• Node.js compatibility tables
47
48 7 FAQ: JavaScript
7.3 Where can I look up what features are planned for JavaScript?
Please see the following sources:
First example: If the operands of an operator don’t have the appropriate types, they are
converted as necessary.
Second example: If an arithmetic computation fails, you get an error value, not an excep-
tion.
> 1 / 0
Infinity
The reason for the silent failures is historical: JavaScript did not have exceptions until
ECMAScript 3. Since then, its designers have tried to avoid silent failures.
First steps
49
Chapter 8
In this chapter, I’d like to paint the big picture: what are you learning in this book, and
how does it fit into the overall landscape of web development?
• Web browser
• Node.js
51
52 8 Using JavaScript: the big picture
JS standard
Platform API
library
Figure 8.1: The structure of the two JavaScript platforms web browser and Node.js. The APIs
“standard library” and “platform API” are hosted on top of a foundational layer with a
JavaScript engine and a platform-specific “core”.
• The foundational layer consists of the JavaScript engine and platform-specific “core”
functionality.
• Two APIs are hosted on top of this foundation:
– The JavaScript standard library is part of JavaScript proper and runs on top of
the engine.
– The platform API are also available from JavaScript – it provides access to plat-
form-specific functionality. For example:
* In browsers, you need to use the platform-specific API if you want to do
anything related to the user interface: react to mouse clicks, play sounds,
etc.
* In Node.js, the platform-specific API lets you read and write files, down-
load data via HTTP, etc.
• MDN Web Docs: cover various web technologies such as CSS, HTML, JavaScript,
and more. An excellent reference.
• Node.js Docs: document the Node.js API.
• ExploringJS.com: My other books cover various aspects of web development:
– “Deep JavaScript: Theory and techniques” describes JavaScript at a level of
detail that is beyond the scope of “Exploring JavaScript”.
– “Tackling TypeScript: Upgrading from JavaScript”
– “Shell scripting with Node.js”
Syntax
53
54 9 Syntax
// single-line comment
/*
Comment with
multiple lines
*/
Booleans:
true
false
Numbers:
1.141
-123
The basic number type is used for both floating point numbers (doubles) and integers.
Bigints:
17n
-49n
The basic number type can only properly represent integers within a range of 53 bits plus
sign. Bigints can grow arbitrarily large in size.
Strings:
'abc'
"abc"
`String with interpolated values: ${256} and ${true}`
JavaScript has no extra type for characters. It uses strings to represent them.
9.1 An overview of JavaScript’s syntax 55
Assertions
An assertion describes what the result of a computation is expected to look like and throws
an exception if those expectations aren’t correct. For example, the following assertion
states that the result of the computation 7 plus 1 must be 8:
assert.equal(7 + 1, 8);
assert.equal() is a method call (the object is assert, the method is .equal()) with two
arguments: the actual result and the expected result. It is part of a Node.js assertion API
that is explained later in this book.
Operators
// Comparison operators
assert.equal(3 < 4, true);
assert.equal(3 <= 4, true);
assert.equal('abc' === 'abc', true);
assert.equal('abc' !== 'def', true);
56 9 Syntax
Declaring variables
const creates immutable variable bindings: Each variable must be initialized immediately
and we can’t assign a different value later. However, the value itself may be mutable and
we may be able to change its contents. In other words: const does not make values im-
mutable.
Arrow function expressions are used especially as arguments of function calls and method
calls:
// Equivalent to add2:
const add3 = (a, b) => a + b;
The previous code contains the following two arrow functions (the terms expression and
statement are explained later in this chapter):
9.1 An overview of JavaScript’s syntax 57
Plain objects
Arrays
assert.deepEqual(
arr, ['a', 'β', 'c', 'd']);
Conditional statement:
if (x < 0) {
x = -x;
}
58 9 Syntax
for-of loop:
Output:
a
b
9.1.2 Modules
Each module is a single file. Consider, for example, the following two files with modules
in them:
file-tools.mjs
main.mjs
The module in main.mjs imports the whole module path and the function isTextFilePath():
9.1.3 Classes
class Person {
constructor(name) {
this.name = name;
}
describe() {
return `Person named ${this.name}`;
}
static logNames(persons) {
for (const person of persons) {
console.log(person.name);
}
}
}
this.title = title;
}
describe() {
return super.describe() +
` (${this.title})`;
}
}
function catchesException() {
try {
throwsException();
} catch (err) {
assert.ok(err instanceof Error);
assert.equal(err.message, 'Problem!');
}
}
Note:
Some words have special meaning in JavaScript and are called reserved. Examples include:
if, true, const.
const if = 123;
// SyntaxError: Unexpected token if
60 9 Syntax
Lowercase:
• Methods: obj.myMethod
• CSS:
Uppercase:
• Classes: MyClass
All-caps:
If the name of a parameter starts with an underscore (or is an underscore) it means that
this parameter is not used – for example:
arr.map((_x, i) => i)
If the name of a property of an object starts with an underscore then that property is con-
sidered private:
class ValueWrapper {
constructor(value) {
this._value = value;
9.2 (Advanced) 61
}
}
const x = 123;
func();
while (false) {
// ···
} // no semicolon
function func() {
// ···
} // no semicolon
However, adding a semicolon after such a statement is not a syntax error – it is interpreted
as an empty statement:
9.2 (Advanced)
All remaining sections of this chapter are advanced.
#!/usr/bin/env node
If we want to pass arguments to node, we have to use the env option -S (to be safe, some
Unixes don’t need it):
9.4 Identifiers
9.4.1 Valid identifiers (variable names, etc.)
First character:
• Unicode letter (including accented characters such as é and ü and characters from
non-latin alphabets, such as α)
• $
• _
Subsequent characters:
Examples:
const ε = 0.0001;
const строка = '';
let _tmp = 0;
const $foo2 = true;
await break case catch class const continue debugger default delete do
else export extends finally for function if import in instanceof let new
return static super switch this throw try typeof var void while with yield
The following tokens are also keywords, but currently not used in the language:
Technically, these words are not reserved, but you should avoid them, too, because they
effectively are keywords:
You shouldn’t use the names of global variables (String, Math, etc.) for your own variables
and parameters, either.
9.5.1 Statements
A statement is a piece of code that can be executed and performs some kind of action. For
example, if is a statement:
let myStr;
if (myBool) {
myStr = 'Yes';
} else {
myStr = 'No';
}
function twice(x) {
return x + x;
}
9.5.2 Expressions
An expression is a piece of code that can be evaluated to produce a value. For example, the
code between the parentheses is an expression:
The operator _?_:_ used between the parentheses is called the ternary operator. It is the
expression version of the if statement.
Let’s look at more examples of expressions. We enter expressions and the REPL evaluates
them for us:
function max(x, y) {
if (x > y) {
return x;
} else {
return y;
}
}
However, expressions can be used as statements. Then they are called expression state-
ments. The opposite is not true: when the context requires an expression, you can’t use a
statement.
The following code demonstrates that any expression bar() can be either expression or
statement – it depends on the context:
function f() {
console.log(bar()); // bar() is expression
bar(); // bar(); is (expression) statement
}
function id(x) {
return x;
}
{
}
9.6.3 Disambiguation
The ambiguities are only a problem in statement context: If the JavaScript parser encoun-
ters ambiguous syntax, it doesn’t know if it’s a plain statement or an expression statement.
For example:
To resolve the ambiguity, statements starting with function or { are never interpreted as
expressions. If you want an expression statement to start with either one of these tokens,
you must wrap it in parentheses:
Output:
abc
In this code:
The code fragment shown in (1) is only interpreted as an expression because we wrap it
in parentheses. If we didn’t, we would get a syntax error because then JavaScript expects
a function declaration and complains about the missing function name. Additionally, you
can’t put a function call immediately after a function declaration.
Later in this book, we’ll see more examples of pitfalls caused by syntactic ambiguity:
9.7 Semicolons
9.7.1 Rule of thumb for semicolons
Each statement is terminated by a semicolon:
const x = 3;
someFunction('abc');
i++;
function foo() {
// ···
66 9 Syntax
}
if (y > 0) {
// ···
}
The whole const declaration (a statement) ends with a semicolon, but inside it, there is
an arrow function expression. That is, it’s not the statement per se that ends with a curly
brace; it’s the embedded arrow function expression. That’s why there is a semicolon at the
end.
while (condition)
statement
But blocks are also statements and therefore legal bodies of control statements:
while (a > 0) {
a--;
}
If you want a loop to have an empty body, your first option is an empty statement (which
is just a semicolon):
• A semicolon
• A line terminator followed by an illegal token
In other words, ASI can be seen as inserting semicolons at line breaks. The next subsections
cover the pitfalls of ASI.
9.8 Automatic semicolon insertion (ASI) 67
The token where this is most practically relevant is return. Consider, for example, the
following code:
return
{
first: 'jane'
};
return;
{
first: 'jane';
}
;
That is:
Why does JavaScript do this? It protects against accidentally returning a value in a line
after a return.
a = b + c
(d + e).print()
Parsed as:
a = b + c(d + e).print();
a = b
/hi/g.exec(c).map(d)
Parsed as:
a = b / hi / g.exec(c).map(d);
68 9 Syntax
someFunction()
['ul', 'ol'].map(x => x + x)
Executed as:
• I like the visual structure it gives code – you clearly see where a statement ends.
• There are less rules to keep in mind.
• The majority of JavaScript programmers use semicolons.
However, there are also many people who don’t like the added visual clutter of semicolons.
If you are one of them: Code without them is legal. I recommend that you use tools to help
you avoid mistakes. The following are two examples:
• The automatic code formatter Prettier can be configured to not use semicolons. It
then automatically fixes problems. For example, if it encounters a line that starts
with a square bracket, it prefixes that line with a semicolon.
• The static checker ESLint has a rule that you tell your preferred style (always semi-
colons or as few semicolons as possible) and that warns you about critical issues.
• Normal “sloppy” mode is the default in scripts (code fragments that are a precursor
to modules and supported by browsers).
• Strict mode is the default in modules and classes, and can be switched on in scripts
(how is explained later). In this mode, several pitfalls of normal mode are removed
and more exceptions are thrown.
You’ll rarely encounter sloppy mode in modern JavaScript code, which is almost always
located in modules. In this book, I assume that strict mode is always switched on.
'use strict';
The neat thing about this “directive” is that ECMAScript versions before 5 simply ignore
it: it’s an expression statement that does nothing.
9.10 Strict mode vs. sloppy mode 69
You can also switch on strict mode for just a single function:
function functionInStrictMode() {
'use strict';
}
function sloppyFunc() {
undeclaredVar1 = 123;
}
sloppyFunc();
// Created global variable `undeclaredVar1`:
assert.equal(undeclaredVar1, 123);
Strict mode does it better and throws a ReferenceError. That makes it easier to detect
typos.
function strictFunc() {
'use strict';
undeclaredVar2 = 123;
}
assert.throws(
() => strictFunc(),
{
name: 'ReferenceError',
message: 'undeclaredVar2 is not defined',
});
The assert.throws() states that its first argument, a function, throws a ReferenceError
when it is called.
In strict mode, a variable created via a function declaration only exists within the innermost
enclosing block:
function strictFunc() {
'use strict';
{
function foo() { return 123 }
}
return foo(); // ReferenceError
}
assert.throws(
70 9 Syntax
() => strictFunc(),
{
name: 'ReferenceError',
message: 'foo is not defined',
});
function sloppyFunc() {
{
function foo() { return 123 }
}
return foo(); // works
}
assert.equal(sloppyFunc(), 123);
In strict mode, you get an exception if you try to change immutable data:
function strictFunc() {
'use strict';
true.prop = 1; // TypeError
}
assert.throws(
() => strictFunc(),
{
name: 'TypeError',
message: "Cannot create property 'prop' on boolean 'true'",
});
function sloppyFunc() {
true.prop = 1; // fails silently
return true.prop;
}
assert.equal(sloppyFunc(), undefined);
To find out how to open the console in your web browser, you can do a web search for “con-
sole «name-of-your-browser»”. These are pages for a few commonly used web browsers:
• Apple Safari
• Google Chrome
• Microsoft Edge
• Mozilla Firefox
71
72 10 Consoles: interactive JavaScript command lines
Figure 10.1: The console of the web browser “Google Chrome” is open (in the bottom half
of window) while visiting a web page.
REPL stands for read-eval-print loop and basically means command line. To use it, you must
first start Node.js from an operating system command line, via the command node. Then
an interaction with it looks as depicted in figure 10.2: The text after > is input from the
user; everything else is output from Node.js.
Figure 10.2: Starting and using the Node.js REPL (interactive command line).
10.2 The console.* API: printing data and more 73
• There are many web apps that let you experiment with JavaScript in web browsers
– for example, Babel’s REPL.
• There are also native apps and IDE plugins for running JavaScript.
The full console.* API is documented on MDN web docs and on the Node.js website. It is
not part of the JavaScript language standard, but much functionality is supported by both
browsers and Node.js.
In this chapter, we only look at the following two methods for printing data (“printing”
means displaying in the console):
• console.log()
• console.error()
The first variant prints (text representations of) values on the console:
74 10 Consoles: interactive JavaScript command lines
Output:
At the end, console.log() always prints a newline. Therefore, if you call it with zero
arguments, it just prints a newline.
Output:
These are some of the directives you can use for substitutions:
Output:
abc 123
Output:
Output:
{"foo":123,"bar":"abc"}
• %% inserts a single %.
console.log('%s%%', 99);
Output:
99%
Output:
{
"first": "Jane",
"last": "Doe"
}
76 10 Consoles: interactive JavaScript command lines
Chapter 11
Assertion API
This assertion states that the expected result of 3 plus 5 is 8. The import statement uses the
recommended strict version of assert.
77
78 11 Assertion API
function id(x) {
return x;
}
assert.equal(id('abc'), 'abc');
assert.equal(3+3, 6);
assert.notEqual(3+3, 22);
The optional last parameter message can be used to explain what is asserted. If the assertion
fails, the message is used to set up the AssertionError that is thrown.
let e;
try {
const x = 3;
assert.equal(x, 8, 'x must be equal to 8')
} catch (err) {
assert.equal(
String(err),
'AssertionError [ERR_ASSERTION]: x must be equal to 8');
}
assert.deepEqual([1,2,3], [1,2,3]);
assert.deepEqual([], []);
assert.notDeepEqual([1,2,3], [1,2]);
assert.throws(
() => {
null.prop;
}
);
assert.throws(
() => {
null.prop;
},
TypeError
);
assert.throws(
() => {
null.prop;
},
/^TypeError: Cannot read properties of null \(reading 'prop'\)$/
);
assert.throws(
() => {
null.prop;
},
{
name: 'TypeError',
message: "Cannot read properties of null (reading 'prop')",
}
);
try {
functionThatShouldThrow();
assert.fail();
} catch (_) {
11.4 Quick reference: module assert 81
// Success
}
82 11 Assertion API
Chapter 12
12.1 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
12.1.1 Installing the exercises . . . . . . . . . . . . . . . . . . . . . . . . 83
12.1.2 Running exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
12.2 Unit tests in JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
12.2.1 A typical test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
12.2.2 Asynchronous tests in Mocha . . . . . . . . . . . . . . . . . . . . . 85
Throughout most chapters, there are boxes that point to exercises. These are a paid feature,
but a comprehensive preview is available. This chapter explains how to get started with
them.
12.1 Exercises
12.1.1 Installing the exercises
To install the exercises:
83
84 12 Getting started with exercises
The key thing here is: everything we want to test must be exported. Otherwise, the test
code can’t access it.
// npm t demos/exercises/id_test.mjs
suite('id_test.mjs');
The core of this test file is line D – an assertion: assert.equal() specifies that the expected
result of id('abc') is 'abc'.
• The comment at the very beginning shows the shell command for running the test.
• Line A: We import the Node.js assertion library (in strict assertion mode).
• Line B: We import the function to test.
• Line C: We define a test. This is done by calling the function test():
– First parameter: the name of the test.
– Second parameter: the test code, which is provided via an arrow function. The
parameter t gives us access to AVA’s testing API (assertions, etc.).
npm t demos/exercises/id_test.mjs
The t is an abbreviation for test. That is, the long version of this command is:
Reading
You may want to postpone reading this section until you get to the chapters on
asynchronous programming.
Writing tests for asynchronous code requires extra work: The test receives its results later
and has to signal to Mocha that it isn’t finished yet when it returns. The following subsec-
tions examine three ways of doing so.
If the callback we pass to test() has a parameter (e.g., done), Mocha switches to callback-
based asynchronicity. When we are done with our asynchronous work, we have to call
done:
function dividePromise(x, y) {
return new Promise((resolve, reject) => {
if (y === 0) {
reject(new Error('Division by zero'));
} else {
resolve(x / y);
}
});
}
Async functions always return Promises. Therefore, an async function is a convenient way
of implementing an asynchronous test. The following code is equivalent to the previous
example.
We don’t need to explicitly return anything: The implicitly returned undefined is used to
fulfill the Promise returned by this async function. And if the test code throws an excep-
tion, then the async function takes care of rejecting the returned Promise.
Part III
87
Chapter 13
13.1 let . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
13.2 const . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
13.2.1 const and immutability . . . . . . . . . . . . . . . . . . . . . . . . 90
13.2.2 const and loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
13.3 Deciding between const and let . . . . . . . . . . . . . . . . . . . . . . . 91
13.4 The scope of a variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
13.4.1 Shadowing variables . . . . . . . . . . . . . . . . . . . . . . . . . 92
13.5 (Advanced) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
13.6 Terminology: static vs. dynamic . . . . . . . . . . . . . . . . . . . . . . . 93
13.6.1 Static phenomenon: scopes of variables . . . . . . . . . . . . . . . 93
13.6.2 Dynamic phenomenon: function calls . . . . . . . . . . . . . . . . 93
13.7 Global variables and the global object . . . . . . . . . . . . . . . . . . . . 93
13.7.1 globalThis [ES2020] . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
13.8 Declarations: scope and activation . . . . . . . . . . . . . . . . . . . . . . 96
13.8.1 const and let: temporal dead zone . . . . . . . . . . . . . . . . . 96
13.8.2 Function declarations and early activation . . . . . . . . . . . . . . 98
13.8.3 Class declarations are not activated early . . . . . . . . . . . . . . 99
13.8.4 var: hoisting (partial early activation) . . . . . . . . . . . . . . . . 99
13.9 Closures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
13.9.1 Bound variables vs. free variables . . . . . . . . . . . . . . . . . . 100
13.9.2 What is a closure? . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
13.9.3 Example: A factory for incrementors . . . . . . . . . . . . . . . . . 101
13.9.4 Use cases for closures . . . . . . . . . . . . . . . . . . . . . . . . . 102
89
90 13 Variables and assignment
Before ES6, there was also var. But it has several quirks, so it’s best to avoid it in modern
JavaScript. You can read more about it in Speaking JavaScript.
13.1 let
Variables declared via let are mutable:
let i;
i = 0;
i = i + 1;
assert.equal(i, 1);
let i = 0;
13.2 const
Variables declared via const are immutable. You must always initialize immediately:
assert.throws(
() => { i = i + 1 },
{
name: 'TypeError',
message: 'Assignment to constant variable.',
}
);
Output:
hello
world
• const indicates an immutable binding and that a variable never changes its value.
Prefer it.
• let indicates that the value of a variable changes. Use it only when you can’t use
const.
Exercise: const
exercises/variables-assignment/const_exrc.mjs
{ // // Scope A. Accessible: x
const x = 0;
assert.equal(x, 0);
{ // Scope B. Accessible: x, y
const y = 1;
assert.equal(x, 0);
assert.equal(y, 1);
{ // Scope C. Accessible: x, y, z
const z = 2;
assert.equal(x, 0);
92 13 Variables and assignment
assert.equal(y, 1);
assert.equal(z, 2);
}
}
}
// Outside. Not accessible: x, y, z
assert.throws(
() => console.log(x),
{
name: 'ReferenceError',
message: 'x is not defined',
}
);
Each variable is accessible in its direct scope and all scopes nested within that scope.
The variables declared via const and let are called block-scoped because their scopes are
always the innermost surrounding blocks.
assert.throws(
() => {
eval('let x = 1; let x = 2;');
},
{
name: 'SyntaxError',
message: "Identifier 'x' has already been declared",
});
Why eval()?
eval() delays parsing (and therefore the SyntaxError), until the callback of as-
sert.throws() is executed. If we didn’t use it, we’d already get an error when this
code is parsed and assert.throws() wouldn’t even be executed.
You can, however, nest a block and use the same variable name x that you used outside
the block:
const x = 1;
assert.equal(x, 1);
{
const x = 2;
assert.equal(x, 2);
13.5 (Advanced) 93
}
assert.equal(x, 1);
Inside the block, the inner x is the only accessible variable with that name. The inner x is
said to shadow the outer x. Once you leave the block, you can access the old value again.
13.5 (Advanced)
All remaining sections are advanced.
• Static means that something is related to source code and can be determined without
executing code.
• Dynamic means at runtime.
function f() {
const x = 3;
// ···
}
x is statically (or lexically) scoped. That is, its scope is fixed and doesn’t change at runtime.
function g(x) {}
function h(y) {
if (Math.random()) g(y); // (A)
}
Whether or not the function call in line A happens, can only be decided at runtime.
• And so on.
The root is also called the global scope. In web browsers, the only location where one is
directly in that scope is at the top level of a script. The variables of the global scope are
called global variables and accessible everywhere. There are two kinds of global variables:
– They can only be created while at the top level of a script, via const, let, and
class declarations.
• Global object variables are stored in properties of the so-called global object.
– They are created in the top level of a script, via var and function declarations.
– The global object can be accessed via the global variable globalThis. It can be
used to create, read, and delete global object variables.
– Other than that, global object variables work like normal variables.
The following HTML fragment demonstrates globalThis and the two kinds of global vari-
ables.
<script>
const declarativeVariable = 'd';
var objectVariable = 'o';
</script>
<script>
// All scripts share the same top-level scope:
console.log(declarativeVariable); // 'd'
console.log(objectVariable); // 'o'
Each ECMAScript module has its own scope. Therefore, variables that exist at the top level
of a module are not global. Figure 13.1 illustrates how the various scopes are related.
Global scope
Figure 13.1: The global scope is JavaScript’s outermost scope. It has two kinds of vari-
ables: object variables (managed via the global object) and normal declarative variables. Each
ECMAScript module has its own scope which is contained in the global scope.
Alternatives to globalThis
The following global variables let us access the global object on some platforms:
• window: The classic way of referring to the global object. But it doesn’t work in
Node.js and in Web Workers.
• self: Available in Web Workers and browsers in general. But it isn’t supported by
Node.js.
• global: Only available in Node.js.
The global object is now considered a mistake that JavaScript can’t get rid of, due to back-
ward compatibility. It affects performance negatively and is generally confusing.
ECMAScript 6 introduced several features that make it easier to avoid the global object –
for example:
• const, let, and class declarations don’t create global object properties when used in
global scope.
• Each ECMAScript module has its own local scope.
It is usually better to access global object variables via variables and not via properties of
globalThis. The former has always worked the same on all JavaScript platforms.
96 13 Variables and assignment
Tutorials on the web occasionally access global variables globVar via window.globVar. But
the prefix “window.” is not necessary and I recommend to omit it:
window.encodeURIComponent(str); // no
encodeURIComponent(str); // yes
Therefore, there are relatively few use cases for globalThis – for example:
Table 13.1 summarizes how various declarations handle these aspects. import is described
in “ECMAScript modules” (§29.5). The following sections describe the other constructs in
more detail.
{
console.log(x); // What happens here?
const x;
}
13.8 Declarations: scope and activation 97
Approach 1 was rejected because there is no precedent in the language for this approach.
It would therefore not be intuitive to JavaScript programmers.
Approach 2 was rejected because then x wouldn’t be a constant – it would have different
values before and after its declaration.
let uses the same approach 3 as const, so that both work similarly and it’s easy to switch
between them.
The time between entering the scope of a variable and executing its declaration is called
the temporal dead zone (TDZ) of that variable:
• During this time, the variable is considered to be uninitialized (as if that were a
special value it has).
• If you access an uninitialized variable, you get a ReferenceError.
• Once you reach a variable declaration, the variable is set to either the value of the
initializer (specified via the assignment symbol) or undefined – if there is no initial-
izer.
The next example shows that the temporal dead zone is truly temporal (related to time):
Even though func() is located before the declaration of myVar and uses that variable, we
can call func(). But we have to wait until the temporal dead zone of myVar is over.
98 13 Variables and assignment
A function declaration is always executed when entering its scope, regardless of where it
is located within that scope. That enables you to call a function foo() before it is declared:
assert.equal(foo(), 123); // OK
function foo() { return 123; }
The early activation of foo() means that the previous code is equivalent to:
If you declare a function via const or let, then it is not activated early. In the following
example, you can only use bar() after its declaration.
assert.throws(
() => bar(), // before declaration
ReferenceError);
Even if a function g() is not activated early, it can be called by a preceding function f()
(in the same scope) if we adhere to the following rule: f() must be invoked after the dec-
laration of g().
The functions of a module are usually invoked after its complete body is executed. There-
fore, in modules, you rarely need to worry about the order of functions.
Lastly, note how early activation automatically keeps the aforementioned rule: when en-
tering a scope, all function declarations are executed first, before any calls are made.
If you rely on early activation to call a function before its declaration, then you need to be
careful that it doesn’t access data that isn’t activated early.
13.8 Declarations: scope and activation 99
funcDecl();
The problem goes away if you make the call to funcDecl() after the declaration of MY_STR.
We have seen that early activation has a pitfall and that you can get most of its benefits
without using it. Therefore, it is better to avoid early activation. But I don’t feel strongly
about this and, as mentioned before, often use function declarations because I like their
syntax.
assert.throws(
() => new MyClass(),
ReferenceError);
class MyClass {}
The operand of extends is an expression. Therefore, you can do things like this:
Evaluating such an expression must be done at the location where it is mentioned. Any-
thing else would be confusing. That explains why class declarations are not activated
early.
var x = 123;
function f() {
// Partial early activation:
assert.equal(x, undefined);
if (true) {
var x = 123;
// The assignment is executed in place:
assert.equal(x, 123);
}
// Scope is function, not block:
assert.equal(x, 123);
}
13.9 Closures
Before we can explore closures, we need to learn about bound variables and free variables.
• Bound variables are declared within the scope. They are parameters and local vari-
ables.
• Free variables are declared externally. They are also called non-local variables.
function func(x) {
const y = 123;
console.log(z);
}
A closure is a function plus a connection to the variables that exist at its “birth
place”.
What is the point of keeping this connection? It provides the values for the free variables
of the function – for example:
13.9 Closures 101
function funcFactory(value) {
return () => {
return value;
};
}
funcFactory returns a closure that is assigned to func. Because func has the connection to
the variables at its birth place, it can still access the free variable value when it is called in
line A (even though it “escaped” its scope).
function createInc(startValue) {
return (step) => { // (A)
startValue += step;
return startValue;
};
}
const inc = createInc(5);
assert.equal(inc(2), 7);
We can see that the function created in line A keeps its internal number in the free variable
startValue. This time, we don’t just read from the birth scope, we use it to store data that
we change and that persists across function calls.
We can create more storage slots in the birth scope, via local variables:
function createInc(startValue) {
let index = -1;
return (step) => {
startValue += step;
index++;
return [index, startValue];
};
}
const inc = createInc(5);
assert.deepEqual(inc(2), [0, 7]);
102 13 Variables and assignment
• For starters, they are simply an implementation of static scoping. As such, they
provide context data for callbacks.
• They can also be used by functions to store state that persists across function calls.
createInc() is an example of that.
• And they can provide private data for objects (produced via literals or classes). The
details of how that works are explained in Exploring ES6.
Chapter 14
Values
103
104 14 Values
(any)
null number
Array Function
string
Map RegExp
symbol
Set Date
Figure 14.1: A partial hierarchy of JavaScript’s types. Missing are the classes for errors, the
classes associated with primitive types, and more. The diagram hints at the fact that not
all objects are instances of Object.
Figure 14.1 shows JavaScript’s type hierarchy. What do we learn from that diagram?
• JavaScript distinguishes two kinds of values: primitive values and objects. We’ll see
soon what the difference is.
• The diagram differentiates objects and instances of class Object. Each instance of
Object is also an object, but not vice versa. However, virtually all objects that you’ll
encounter in practice are instances of Object – for example, objects created via object
literals. More details on this topic are explained in “Not all objects are instances of
Object” (§31.7.3).
• Primitive values are the elements of the types undefined, null, boolean, number, big-
int, string, symbol.
• All other values are objects.
In contrast to Java (that inspired JavaScript here), primitive values are not second-class
citizens. The difference between them and objects is more subtle. In a nutshell:
Other than that, primitive values and objects are quite similar: they both have properties
(key-value entries) and can be used in the same locations.
Primitives are passed by value: variables (including parameters) store the contents of the
primitives. When assigning a primitive value to a variable or passing it as an argument to
a function, its content is copied.
const x = 123;
const y = x;
// `y` is the same as any other number 123
assert.equal(y, 123);
106 14 Values
Primitives are compared by value: when comparing two primitive values, we compare their
contents.
To see what’s so special about this way of comparing, read on and find out how objects are
compared.
14.4.2 Objects
Objects are covered in detail in “Objects” (§30) and the following chapter. Here, we mainly
focus on how they differ from primitive values.
• Object literal:
const obj = {
first: 'Jane',
last: 'Doe',
};
The object literal starts and ends with curly braces {}. It creates an object with two
properties. The first property has the key 'first' (a string) and the value 'Jane'.
The second property has the key 'last' and the value 'Doe'. For more information
on object literals, consult “Object literals: properties” (§30.3.1).
• Array literal:
The Array literal starts and ends with square brackets []. It creates an Array with
two elements: 'strawberry' and 'apple'. For more information on Array literals,
consult “Creating, reading, writing Arrays”.
By default, you can freely change, add, and remove the properties of objects:
assert.equal(obj.count, 2);
Objects are passed by identity (my term): variables (including parameters) store the identities
of objects.
The identity of an object is like a pointer (or a transparent reference) to the object’s actual
data on the heap (think shared main memory of a JavaScript engine).
Now the old value { prop: 'value' } of obj is garbage (not used anymore). JavaScript will
automatically garbage-collect it (remove it from memory), at some point in time (possibly
never if there is enough free memory).
Objects are compared by identity (my term): two variables are only equal if they contain the
same object identity. They are not equal if they refer to different objects with the same
content.
• typeof distinguishes the 7 types of the specification (minus one omission, plus one
addition).
• instanceof tests which class created a given value.
14.5.1 typeof
x typeof x
undefined 'undefined'
null 'object'
Boolean 'boolean'
Number 'number'
Bigint 'bigint'
String 'string'
Symbol 'symbol'
Function 'function'
All other objects 'object'
Table 14.1 lists all results of typeof. They roughly correspond to the 7 types of the language
specification. Alas, there are two differences, and they are language quirks:
• typeof null returns 'object' and not 'null'. That’s a bug. Unfortunately, it can’t
be fixed. TC39 tried to do that, but it broke too much code on the web.
• typeof of a function should be 'object' (functions are objects). Introducing a sepa-
rate category for functions is confusing.
'string'
> typeof {}
'object'
14.5.2 instanceof
This operator answers the question: has a value x been created by a class C?
x instanceof C
For example:
Exercise: instanceof
exercises/values/instanceof_exrc.mjs
ES6 introduced classes, which are mainly better syntax for constructor functions.
In this book, I’m using the terms constructor function and class interchangeably.
Classes can be seen as partitioning the single type object of the specification into subtypes
– they give us more types than the limited 7 ones of the specification. Each class is the type
of the objects that were created by it.
110 14 Values
assert.equal(Number('123'), 123);
• Number.prototype provides the properties for numbers – for example, method .toString():
assert.equal((123).toString, Number.prototype.toString);
• Number is a namespace/container object for tool functions for numbers – for example:
assert.equal(Number.isInteger(123), true);
• Lastly, you can also use Number as a class and create number objects. These objects
are different from real numbers and should be avoided.
The constructor functions related to primitive types are also called wrapper types because
they provide the canonical way of converting primitive values to objects. In the process,
primitive values are “wrapped” in objects.
Wrapping rarely matters in practice, but it is used internally in the language specification,
to give primitives properties.
> Boolean(0)
false
> Number('123')
123
> String(123)
'123'
The following table describes in more detail how this conversion works:
x Object(x)
undefined {}
null {}
boolean new Boolean(x)
number new Number(x)
bigint An instance of BigInt (new throws TypeError)
string new String(x)
symbol An instance of Symbol (new throws TypeError)
object x
Many built-in functions coerce, too. For example, Number.parseInt() coerces its parameter
to a string before parsing it. That explains the following result:
> Number.parseInt(123.45)
123
The number 123.45 is converted to the string '123.45' before it is parsed. Parsing stops
before the first non-digit character, which is why the result is 123.
112 14 Values
Operators
113
114 15 Operators
First, the multiplication operator can only work with numbers. Therefore, it converts
strings to numbers before computing its result.
Second, the square brackets operator ([ ]) for accessing the properties of an object can
only handle strings and symbols. All other values are coerced to string:
Why? The plus operator first coerces its operands to primitive values:
> String([1,2,3])
'1,2,3'
> String([4,5,6])
'4,5,6'
• First, it converts both operands to primitive values. Then it switches to one of two
modes:
– String mode: If one of the two primitive values is a string, then it converts the
other one to a string, concatenates both strings, and returns the result.
– Number mode: Otherwise, It converts both operands to numbers, adds them,
and returns the result.
Number mode means that if neither operand is a string (or an object that becomes a string)
then everything is coerced to numbers:
> 4 + true
5
Number(true) is 1.
const x = value;
let y = value;
Logical assignment operators work differently from other compound assignment opera-
tors:
a || (a = b)
a = a || b
116 15 Operators
The former expression has the benefit of short-circuiting: The assignment is only evaluated
if a evaluates to false. Therefore, the assignment is only performed if it’s necessary. In
contrast, the latter expression always performs an assignment.
For more on ??=, see “The nullish coalescing assignment operator (??=)” (§16.4.5).
For operators op other than || && ??, the following two ways of assigning are equivalent:
If, for example, op is +, then we get the operator += that works as follows.
assert.equal(str, '<b>Hello!</b>');
> '' == 0
true
Objects are coerced to primitives if (and only if!) the other operand is primitive:
15.4 Equality: == vs. === 117
If both operands are objects, they are only equal if they are the same object:
An object is only equal to another value if that value is the same object:
The === operator does not consider undefined and null to be equal:
Let’s look at two use cases for == and what I recommend to do instead.
== lets you check if a value x is a number or that number as a string – with a single com-
parison:
if (x == 123) {
// x is either 123 or '123'
}
You can also convert x to a number when you first encounter it.
if (x == null) {
// x is either null or undefined
}
The problem with this code is that you can’t be sure if someone meant to write it that way
or if they made a typo and meant === null.
A downside of the second alternative is that it accepts values other than undefined and
null, but it is a well-established pattern in JavaScript (to be explained in detail in “Truthi-
ness-based existence checks” (§17.3)).
if (x != null) ···
if (x !== undefined && x !== null) ···
if (x) ···
It is even stricter than ===. For example, it considers NaN, the error value for computations
involving numbers, to be equal to itself:
That is occasionally useful. For example, you can use it to implement an improved version
of the Array method .indexOf():
The result -1 means that .indexOf() couldn’t find its argument in the Array.
Operator name
< less than
<= Less than or equal
> Greater than
>= Greater than or equal
JavaScript’s ordering operators (table 15.1) work for both numbers and strings:
> 5 >= 2
true
> 'bar' < 'foo'
true
The next two subsections discuss two operators that are rarely used.
> void (3 + 2)
undefined
Primitive values
121
Chapter 16
Many programming languages have one “non-value” called null. It indicates that a vari-
able does not currently point to an object – for example, when it hasn’t been initialized
yet.
123
124 16 The non-values undefined and null
• undefined means “not initialized” (e.g., a variable) or “not existing” (e.g., a property
of an object).
• null means “the intentional absence of any object value” (a quote from the language
specification).
let myVar;
assert.equal(myVar, undefined);
function func(x) {
return x;
}
assert.equal(func(), undefined);
If we don’t explicitly specify the result of a function via a return statement, JavaScript
returns undefined for us:
function func() {}
assert.equal(func(), undefined);
> Object.getPrototypeOf(Object.prototype)
null
If we match a regular expression (such as /a/) against a string (such as 'x'), we either get
an object with matching data (if matching was successful) or null (if matching failed):
16.3 Checking for undefined or null 125
> /a/.exec('x')
null
The JSON data format does not support undefined, only null:
Truthy means “is true if coerced to boolean”. Falsy means “is false if coerced to boolean”.
Both concepts are explained properly in “Falsy and truthy values” (§17.2).
Sometimes we receive a value and only want to use it if it isn’t either null or undefined.
Otherwise, we’d like to use a default value, as a fallback. We can do that via the nullish
coalescing operator (??):
a ?? b
a !== undefined && a !== null ? a : b
126 16 The non-values undefined and null
assert.equal(
countMatches(/a/g, 'ababa'), 3);
assert.equal(
countMatches(/b/g, 'ababa'), 2);
assert.equal(
countMatches(/x/g, 'ababa'), 0);
If there are one or more matches for regex inside str, then .match() returns an Array. If
there are no matches, it unfortunately returns null (and not the empty Array). We fix that
via the ?? operator.
return matchResult?.length ?? 0;
const files = [
{path: 'index.html', title: 'Home'},
{path: 'tmp.html'},
];
assert.deepEqual(
files.map(f => getTitle(f)),
['Home', '(Untitled)']);
function getTitle(fileDesc) {
const {title = '(Untitled)'} = fileDesc;
return title;
}
But it also returns the default for all other falsy values – for example:
a ??= b
a ?? (a = b)
That means that ??= is short-circuiting: The assignment is only made if a is undefined or
null.
const books = [
{
isbn: '123',
},
{
128 16 The non-values undefined and null
assert.deepEqual(
books,
[
{
isbn: '123',
title: '(Untitled)',
},
{
title: 'ECMAScript Language Specification',
isbn: '456',
},
]);
undefined and null are the only two JavaScript values where we get an exception if we try
to read a property. To explore this phenomenon, let’s use the following function, which
reads (“gets”) property .foo and returns the result.
function getFoo(x) {
return x.foo;
}
If we apply getFoo() to various values, we can see that it only fails for undefined and null:
> getFoo(undefined)
TypeError: Cannot read properties of undefined (reading 'foo')
> getFoo(null)
TypeError: Cannot read properties of null (reading 'foo')
> getFoo(true)
undefined
> getFoo({})
undefined
16.6 The history of undefined and null 129
In JavaScript, each variable can hold both object values and primitive values. Therefore, if
null means “not an object”, JavaScript also needs an initialization value that means “nei-
ther an object nor a primitive value”. That initialization value is undefined.
130 16 The non-values undefined and null
Chapter 17
Booleans
The primitive type boolean comprises two values – false and true:
131
132 17 Booleans
These are three ways in which you can convert an arbitrary value x to a boolean.
• Boolean(x)
Most descriptive; recommended.
• x ? true : false
Uses the conditional operator (explained later in this chapter).
• !!x
Uses the logical Not operator (!). This operator coerces its operand to boolean. It is
applied a second time to get a non-negated result.
x Boolean(x)
undefined false
null false
boolean x (no change)
number 0 →false, NaN →false
Other numbers →true
bigint 0 →false
Other numbers →true
string '' →false
Other strings →true
symbol true
object Always true
if (value) {}
That is, JavaScript checks if value is true when converted to boolean. This kind of check
is so common that the following names were introduced:
Each value is either truthy or falsy. Consulting table 17.1, we can make an exhaustive list
of falsy values:
• undefined
• null
• Boolean: false
• Numbers: 0, NaN
• Bigint: 0n
• String: ''
> Boolean('abc')
true
> Boolean([])
true
> Boolean({})
true
if (!x) {
// x is falsy
}
if (x) {
// x is truthy
} else {
// x is falsy
}
The conditional operator that is used in the last line, is explained later in this chapter.
Exercise: Truthiness
exercises/booleans/truthiness_exrc.mjs
134 17 Booleans
if (obj.prop) {
// obj has property .prop
}
if (obj.prop) {
// obj has property .prop
}
• obj.prop is undefined.
• obj.prop is any other falsy value (null, 0, '', etc.).
In practice, this rarely causes problems, but you have to be aware of this pitfall.
function func(x) {
if (!x) {
throw new Error('Missing parameter x');
}
// ···
}
On the plus side, this pattern is established and short. It correctly throws errors for unde-
fined and null.
On the minus side, there is the previously mentioned pitfall: the code also throws errors
for all other falsy values.
17.4 Conditional operator (? :) 135
if (x === undefined) {
throw new Error('Missing parameter x');
}
function readFile(fileDesc) {
if (!fileDesc.path) {
throw new Error('Missing property: .path');
}
// ···
}
readFile({ path: 'foo.txt' }); // no error
This pattern is also established and has the usual caveat: it not only throws if the property
is missing, but also if it exists and has any of the falsy values.
If you truly want to check if the property exists, you have to use the in operator:
if (! ('path' in fileDesc)) {
throw new Error('Missing property: .path');
}
It is evaluated as follows:
The conditional operator is also called ternary operator because it has three operands.
Examples:
The following code demonstrates that whichever of the two branches “then” and “else” is
chosen via the condition, only that branch is evaluated. The other branch isn’t.
Output:
136 17 Booleans
then
17.5.1 Value-preservation
Value-preservation means that operands are interpreted as booleans but returned unchanged:
> 12 || 'hello'
12
> 0 || 'hello'
'hello'
17.5.2 Short-circuiting
Short-circuiting means if the first operand already determines the result, then the second
operand is not evaluated. The only other operator that delays evaluating its operands is the
conditional operator. Usually, all operands are evaluated before performing an operation.
For example, logical And (&&) does not evaluate its second operand if the first one is falsy:
Output:
hello
1. Evaluate a.
2. Is the result falsy? Return it.
3. Otherwise, evaluate b and return the result.
a && b
!a ? a : b
Examples:
1. Evaluate a.
2. Is the result truthy? Return it.
3. Otherwise, evaluate b and return the result.
a || b
a ? a : b
Examples:
ECMAScript 2020 introduced the nullish coalescing operator (??) for default values. Be-
fore that, logical Or was used for this purpose:
See “The nullish coalescing operator (??) for default values” (§16.4) for more information
on ?? and the downsides of || in this case.
1. Evaluate x.
2. Is it truthy? Return false.
3. Otherwise, return true.
Examples:
> !false
true
> !true
false
> !0
true
> !123
false
> !''
true
> !'abc'
false
Chapter 18
Numbers
18.1 Numbers are used for both floating point numbers and integers . . . . . . 140
18.2 Number literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
18.2.1 Integer literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
18.2.2 Floating point literals . . . . . . . . . . . . . . . . . . . . . . . . . 141
18.2.3 Syntactic pitfall: properties of integer literals . . . . . . . . . . . . 141
18.2.4 Underscores (_) as separators in number literals [ES2021] . . . . . . . 141
18.3 Arithmetic operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
18.3.1 Binary arithmetic operators . . . . . . . . . . . . . . . . . . . . . . 142
18.3.2 Unary plus (+) and negation (-) . . . . . . . . . . . . . . . . . . . . 143
18.3.3 Incrementing (++) and decrementing (--) . . . . . . . . . . . . . . 143
18.4 Converting to number . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
18.5 Error values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
18.5.1 Error value: NaN . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
18.5.2 Error value: Infinity . . . . . . . . . . . . . . . . . . . . . . . . . 147
18.6 The precision of numbers: careful with decimal fractions . . . . . . . . . . 148
18.7 (Advanced) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
18.8 Background: floating point precision . . . . . . . . . . . . . . . . . . . . . 148
18.8.1 A simplified representation of floating point numbers . . . . . . . 149
18.9 Integer numbers in JavaScript . . . . . . . . . . . . . . . . . . . . . . . . 150
18.9.1 Converting to integer . . . . . . . . . . . . . . . . . . . . . . . . . 150
18.9.2 Ranges of integer numbers in JavaScript . . . . . . . . . . . . . . . 151
18.9.3 Safe integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
18.10Bitwise operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
18.10.1 Internally, bitwise operators work with 32-bit integers . . . . . . . 153
18.10.2 Bitwise Not . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
18.10.3 Binary bitwise operators . . . . . . . . . . . . . . . . . . . . . . . 154
18.10.4 Bitwise shift operators . . . . . . . . . . . . . . . . . . . . . . . . 154
18.10.5 b32(): displaying unsigned 32-bit integers in binary notation . . . 155
18.11 Quick reference: numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
18.11.1 Global functions for numbers . . . . . . . . . . . . . . . . . . . . . 155
139
140 18 Numbers
• Numbers are 64-bit floating point numbers and are also used for smaller integers
(within a range of plus/minus 53 bits).
• Bigints represent integers with an arbitrary precision.
This chapter covers numbers. Bigints are covered later in this book.
18.1 Numbers are used for both floating point numbers and
integers
The type number is used for both integers and floating point numbers in JavaScript:
98
123.45
However, all numbers are doubles, 64-bit floating point numbers implemented according
to the IEEE Standard for Floating-Point Arithmetic (IEEE 754).
Integer numbers are simply floating point numbers without a decimal fraction:
Note that, under the hood, most JavaScript engines are often able to use real integers, with
all associated performance and storage size benefits.
// Binary (base 2)
assert.equal(0b11, 3); // ES6
// Octal (base 8)
assert.equal(0o10, 8); // ES6
Fractions:
> 35.0
35
> 3e2
300
> 3e-2
0.03
> 0.3e2
30
7.0.toString()
(7).toString()
7..toString()
7 .toString() // space before dot
• We can only put underscores between two digits. Therefore, all of the following
number literals are illegal:
3_.141
3._141
1_e12
1e_12
0_b111111000
0b_111111000
The motivation behind these restrictions is to keep parsing simple and to avoid strange
edge cases.
• Number()
• Number.parseInt()
• Number.parseFloat()
For example:
> Number('123_456')
NaN
> Number.parseInt('123_456')
123
The rationale is that numeric separators are for code. Other kinds of input should be pro-
cessed differently.
% is a remainder operator
% is a remainder operator, not a modulo operator. Its result has the sign of the first operand:
> 5 % 3
2
> -5 % 3
-2
For more information on the difference between remainder and modulo, see the blog post
“Remainder operator vs. modulo operator (with JavaScript code)” on 2ality.
Table 18.2: The operators unary plus (+) and negation (-).
> +'5'
5
> +'-12'
-12
> -'9'
-9
The decrementation operator -- works the same, but subtracts one from its operand. The
next two examples explain the difference between the prefix and the suffix version.
Table 18.3 summarizes the incrementation and decrementation operators. Next, we’ll look
144 18 Numbers
assert.equal(--bar, 2);
assert.equal(bar, 2);
Suffix ++ and suffix -- return their operands and then change them.
let foo = 3;
assert.equal(foo++, 3);
assert.equal(foo, 4);
let bar = 3;
assert.equal(bar--, 3);
assert.equal(bar, 2);
const obj = { a: 1 };
++obj.a;
assert.equal(obj.a, 2);
const arr = [ 4 ];
arr[0]++;
assert.deepEqual(arr, [5]);
• Number(value)
• +value
• parseFloat(value) (avoid; different than the other two!)
18.5 Error values 145
Recommendation: use the descriptive Number(). Table 18.4 summarizes how it works.
Examples:
x Number(x)
undefined NaN
null 0
boolean false →0, true →1
number x (no change)
bigint -1n →-1, 1n →1, etc.
string '' →0
Other →parsed number, ignoring leading/trailing whitespace
symbol Throws TypeError
object Configurable (e.g. via .valueOf())
assert.equal(Number(123.45), 123.45);
assert.equal(Number(''), 0);
assert.equal(Number('\n 123.45 \t'), 123.45);
assert.equal(Number('xyz'), NaN);
assert.equal(Number(-123n), -123);
How objects are converted to numbers can be configured – for example, by overriding
.valueOf():
• NaN
• Infinity
> Number('$$$')
NaN
> Number(undefined)
NaN
> Math.log(-1)
NaN
> Math.sqrt(-1)
NaN
> NaN - 3
NaN
> 7 ** NaN
NaN
NaN is the only JavaScript value that is not strictly equal to itself:
const n = NaN;
assert.equal(n === n, false);
const x = NaN;
> [NaN].indexOf(NaN)
-1
Others can:
> [NaN].includes(NaN)
true
> [NaN].findIndex(x => Number.isNaN(x))
0
> [NaN].find(x => Number.isNaN(x))
NaN
18.5 Error values 147
Alas, there is no simple rule of thumb. We have to check for each method how it handles
NaN.
> 5 / 0
Infinity
> -5 / 0
-Infinity
Infinity is larger than all other numbers (except NaN), making it a good default value:
function findMinimum(numbers) {
let min = Infinity;
for (const n of numbers) {
if (n < min) min = n;
}
return min;
}
const x = Infinity;
We therefore need to take rounding errors into consideration when performing arithmetic
in JavaScript.
18.7 (Advanced)
All remaining sections of this chapter are advanced.
To understand why, we need to explore how JavaScript represents floating point numbers
internally. It uses three integers to do so, which take up a total of 64 bits of storage (double
precision):
This representation can’t encode a zero because its second component (involving the frac-
tion) always has a leading 1. Therefore, a zero is encoded via the special exponent −1023
and a fraction 0.
18.8 Background: floating point precision 149
• Instead of base 2 (binary), we use base 10 (decimal) because that’s what most people
are more familiar with.
• The fraction is a natural number that is interpreted as a fraction (digits after a point).
We switch to a mantissa, an integer that is interpreted as itself. As a consequence,
the exponent is used differently, but its fundamental role doesn’t change.
• As the mantissa is an integer (with its own sign), we don’t need a separate sign,
anymore.
mantissa × 10exponent
Let’s try out this representation for a few floating point numbers.
• To encode the integer 123, we use the mantissa 123 and multiply it with 1 (100 ):
• To encode the integer −45, we use the mantissa −45 and, again, the exponent zero:
• For the number 1.5, we imagine there being a point after the mantissa. We use the
negative exponent −1 to move that point one digit to the left:
• For the number 0.25, we move the point two digits to the left:
In other words: As soon as we have decimal digits, the exponent becomes negative. We
can also write such a number as a fraction:
For example:
These fractions help with understanding why there are numbers that our encoding cannot
represent:
• 1/10 can be represented. It already has the required format: a power of 10 in the
denominator.
150 18 Numbers
• 1/2 can be represented as 5/10. We turned the 2 in the denominator into a power of
10 by multiplying the numerator and denominator by 5.
• 1/4 can be represented as 25/100. We turned the 4 in the denominator into a power
of 10 by multiplying the numerator and denominator by 25.
• 1/3 cannot be represented. There is no way to turn the denominator into a power
of 10. (The prime factors of 10 are 2 and 5. Therefore, any denominator that only
has these prime factors can be converted to a power of 10, by multiplying both the
numerator and denominator by enough twos and fives. If a denominator has a dif-
ferent prime factor, then there’s nothing we can do.)
• 0.5 = 1/2 can be represented with base 2 because the denominator is already a
power of 2.
• 0.25 = 1/4 can be represented with base 2 because the denominator is already a
power of 2.
• 0.1 = 1/10 cannot be represented because the denominator cannot be converted to
a power of 2.
• 0.2 = 2/10 cannot be represented because the denominator cannot be converted to
a power of 2.
Now we can see why 0.1 + 0.2 doesn’t produce a correct result: internally, neither of the
two operands can be represented precisely.
The only way to compute precisely with decimal fractions is by internally switching to
base 10. For many programming languages, base 2 is the default and base 10 an option.
For example:
There are plans to add something similar to JavaScript: the ECMAScript proposal “Deci-
mal”. Until that happens, we can use libraries such as big.js.
In this section, we’ll look at a few tools for working with these pseudo-integers. JavaScript
also supports bigints, which are real integers.
> Math.floor(2.1)
2
> Math.floor(2.9)
2
> Math.ceil(2.1)
3
> Math.ceil(2.9)
3
• Math.round(n): returns the integer that is “closest” to n with __.5 being rounded up
– for example:
> Math.round(2.4)
2
> Math.round(2.5)
3
• Math.trunc(n): removes any decimal fraction (after the point) that n has, therefore
turning it into an integer.
> Math.trunc(2.1)
2
> Math.trunc(2.9)
2
• Safe integers: can be represented “safely” by JavaScript (more on what that means
in the next subsection)
– Precision: 53 bits plus sign
– Range: (−253 , 253 )
• Array indices
– Precision: 32 bits, unsigned
– Range: [0, 232 −1) (excluding the maximum length)
– Typed Arrays have a larger range of 53 bits (safe and unsigned)
• Bitwise operators (bitwise Or, etc.)
– Precision: 32 bits
– Range of unsigned right shift (>>>): unsigned, [0, 232 )
– Range of all other bitwise operators: signed, [−231 , 231 )
An integer is safe if it is represented by exactly one JavaScript number. Given that JavaScript
numbers are encoded as a fraction multiplied by 2 to the power of an exponent, higher in-
tegers can also be represented, but then there are gaps between them.
> 18014398509481984
18014398509481984
> 18014398509481985
18014398509481984
> 18014398509481986
18014398509481984
> 18014398509481987
18014398509481988
assert.equal(Number.isSafeInteger(5), true);
assert.equal(Number.isSafeInteger('5'), false);
assert.equal(Number.isSafeInteger(5.1), false);
assert.equal(Number.isSafeInteger(Number.MAX_SAFE_INTEGER), true);
assert.equal(Number.isSafeInteger(Number.MAX_SAFE_INTEGER+1), false);
Safe computations
The following result is incorrect and unsafe, even though both of its operands are safe:
> 9007199254740990 + 3
9007199254740992
The following result is safe, but incorrect. The first operand is unsafe; the second operand
is safe:
> 9007199254740995 - 10
9007199254740986
• Input (JavaScript numbers): The 1–2 operands are first converted to JavaScript num-
bers (64-bit floating point numbers) and then to 32-bit integers.
• Computation (32-bit integers): The actual operation processes 32-bit integers and
produces a 32-bit integer.
• Output (JavaScript number): Before returning the result, it is converted back to a
JavaScript number.
For each bitwise operator, this book mentions the types of its operands and its result. Each
type is always one of the following two:
Considering the previously mentioned steps, I recommend to pretend that bitwise oper-
ators internally work with unsigned 32-bit integers (step “computation”) and that Int32
and Uint32 only affect how JavaScript numbers are converted to and from integers (steps
“input” and “output”).
While exploring the bitwise operators, it occasionally helps to display JavaScript numbers
as unsigned 32-bit integers in binary notation. That’s what b32() does (whose implemen-
tation is shown later):
assert.equal(
b32(-1),
'11111111111111111111111111111111');
assert.equal(
b32(1),
'00000000000000000000000000000001');
assert.equal(
b32(2 ** 31),
'10000000000000000000000000000000');
> b32(~0b100)
'11111111111111111111111111111011'
154 18 Numbers
This so-called ones’ complement is similar to a negative for some arithmetic operations. For
example, adding an integer to its ones’ complement is always -1:
> 4 + ~4
-1
> -11 + ~-11
-1
The binary bitwise operators (table 18.6) combine the bits of their operands to produce
their results:
The shift operators (table 18.7) move binary digits to the left or to the right:
/**
* Return a string representing n as a 32-bit unsigned integer,
* in binary notation.
*/
function b32(n) {
// >>> ensures highest bit isn’t interpreted as a sign
return (n >>> 0).toString(2).padStart(32, '0');
}
assert.equal(
b32(6),
'00000000000000000000000000000110');
n >>> 0 means that we are shifting n zero bits to the right. Therefore, in principle, the >>>
operator does nothing, but it still coerces n to an unsigned 32-bit integer:
> 12 >>> 0
12
> -12 >>> 0
4294967284
> (2**32 + 1) >>> 0
1
• isFinite()
• isNaN()
• parseFloat()
• parseInt()
• Number.EPSILON [ES6]
The difference between 1 and the next representable floating point number. In gen-
eral, a machine epsilon provides an upper bound for rounding errors in floating
point arithmetic.
• Number.MAX_SAFE_INTEGER [ES6]
156 18 Numbers
The largest integer that JavaScript can represent unambiguously (253 −1).
• Number.MAX_VALUE [ES1]
• Number.MIN_SAFE_INTEGER [ES6]
The smallest integer that JavaScript can represent unambiguously (−253 +1).
• Number.MIN_VALUE [ES1]
• Number.NaN [ES1]
• Number.NEGATIVE_INFINITY [ES1]
• Number.POSITIVE_INFINITY [ES1]
Returns true if num is an actual number (neither Infinity nor -Infinity nor NaN).
> Number.isFinite(Infinity)
false
> Number.isFinite(-Infinity)
false
> Number.isFinite(NaN)
false
> Number.isFinite(123)
true
• Number.isInteger(num) [ES6]
Returns true if num is a number and does not have a decimal fraction.
> Number.isInteger(-17)
true
> Number.isInteger(33)
true
> Number.isInteger(33.1)
false
> Number.isInteger('33')
18.11 Quick reference: numbers 157
false
> Number.isInteger(NaN)
false
> Number.isInteger(Infinity)
false
• Number.isNaN(num) [ES6]
> Number.isNaN(NaN)
true
> Number.isNaN(123)
false
> Number.isNaN('abc')
false
• Number.isSafeInteger(num) [ES6]
• Number.parseFloat(str) [ES6]
Coerces its parameter to string and parses it as a floating point number. For convert-
ing strings to numbers, Number() (which ignores leading and trailing whitespace)
is usually a better choice than Number.parseFloat() (which ignores leading white-
space and illegal trailing characters and can hide problems).
Coerces its parameter to string and parses it as an integer, ignoring leading white-
space and illegal trailing characters:
> Number.parseInt('101', 2)
5
> Number.parseInt('FF', 16)
255
Do not use this method to convert numbers to integers: coercing to string is ineffi-
cient. And stopping before the first non-digit is not a good algorithm for removing
the fraction of a number. Here is an example where it goes wrong:
18.11.4 Number.prototype.*
(Number.prototype is where the methods of numbers are stored.)
[ES3]
• Number.prototype.toExponential(fractionDigits?)
> 1234..toString()
'1234'
Example: fraction not small enough to get a negative exponent via .toString().
> 0.003.toString()
'0.003'
> 0.003.toExponential()
'3e-3'
• Number.prototype.toFixed(fractionDigits=0) [ES3]
[ES3]
• Number.prototype.toPrecision(precision?)
– Works like .toString(), but precision specifies how many digits should be
shown overall.
– If precision is missing, .toString() is used.
> 1234..toPrecision(4)
'1234'
> 1234..toPrecision(5)
'1234.0'
> 1.234.toPrecision(3)
'1.23'
• Number.prototype.toString(radix=10) [ES1]
> 123.456.toString()
'123.456'
If we want the numeral to have a different base, we can specify it via radix:
> 1234567890..toString(36)
'kf12oi'
18.11.5 Sources
• Wikipedia
• TypeScript’s built-in typings
• MDN web docs for JavaScript
160 18 Numbers
Math
Math is an object with data properties and methods for processing numbers. You can see it
as a poor man’s module: It was created long before JavaScript had modules.
161
162 19 Math
> Math.cbrt(8)
2
> Math.exp(0)
1
> Math.exp(1) === Math.E
true
Returns the natural logarithm of x (to base e, Euler’s number). The inverse of Math.exp().
> Math.log(1)
0
> Math.log(Math.E)
1
> Math.log(Math.E ** 2)
2
Returns Math.log(1 + x). The inverse of Math.expm1(). Very small numbers (frac-
tions close to 0) are represented with a higher precision. Therefore, you can provide
this function with a more precise argument whenever the argument for .log() is
close to 1.
19.3 Rounding 163
> Math.log10(1)
0
> Math.log10(10)
1
> Math.log10(100)
2
> Math.log2(1)
0
> Math.log2(2)
1
> Math.log2(4)
2
> Math.pow(2, 3)
8
> Math.pow(25, 0.5)
5
> Math.sqrt(9)
3
19.3 Rounding
Rounding means converting an arbitrary number to an integer (a number without a deci-
mal fraction). The following functions implement different approaches to rounding.
> Math.ceil(2.1)
3
> Math.ceil(2.9)
3
> Math.floor(2.1)
2
> Math.floor(2.9)
2
Returns the integer that is closest to x. If the decimal fraction of x is .5 then .round()
rounds up (to the integer closer to positive infinity):
> Math.round(2.4)
2
> Math.round(2.5)
3
> Math.trunc(2.1)
2
> Math.trunc(2.9)
2
Table 19.1 shows the results of the rounding functions for a few representative inputs.
Table 19.1: Rounding functions of Math. Note how things change with negative numbers
because “larger” always means “closer to positive infinity”.
function degreesToRadians(degrees) {
return degrees / 180 * Math.PI;
}
assert.equal(degreesToRadians(90), Math.PI/2);
function radiansToDegrees(radians) {
return radians / Math.PI * 180;
19.4 Trigonometric Functions 165
}
assert.equal(radiansToDegrees(Math.PI), 180);
> Math.acos(0)
1.5707963267948966
> Math.acos(1)
0
> Math.asin(0)
0
> Math.asin(1)
1.5707963267948966
> Math.cos(0)
1
> Math.cos(Math.PI)
-1
Returns the square root of the sum of the squares of values (Pythagoras’ theorem):
166 19 Math
> Math.hypot(3, 4)
5
> Math.sin(0)
0
> Math.sin(Math.PI / 2)
1
> Math.tan(0)
0
> Math.tan(1)
1.5574077246549023
> Math.abs(3)
3
> Math.abs(-3)
3
> Math.abs(0)
0
Counts the leading zero bits in the 32-bit integer x. Used in DSP algorithms.
> Math.clz32(0b01000000000000000000000000000000)
1
> Math.clz32(0b00100000000000000000000000000000)
2
> Math.clz32(2)
30
> Math.clz32(1)
31
19.6 Sources 167
> Math.sign(-8)
-1
> Math.sign(0)
0
> Math.sign(3)
1
19.6 Sources
• Wikipedia
• TypeScript’s built-in typings
• MDN web docs for JavaScript
• ECMAScript language specification
168 19 Math
Chapter 20
Bigints – arbitrary-precision
integers [ES2020] (advanced)
169
170 20 Bigints – arbitrary-precision integers [ES2020] (advanced)
In this chapter, we take a look at bigints, JavaScript’s integers whose storage space grows
and shrinks as needed.
• There only was a single type for floating point numbers and integers: 64-bit floating
point numbers (IEEE 754 double precision).
• JavaScript numbers could also represent integers beyond the small integer range,
as floating point numbers. Here, the safe range is plus/minus 53 bits. For more
information on this topic, see “Safe integers” (§18.9.3).
• X (formerly Twitter) uses 64-bit integers as IDs for posts (source). In JavaScript, these
IDs had to be stored in strings.
• Financial technology uses so-called big integers (integers with arbitrary precision)
to represent amounts of money. Internally, the amounts are multiplied so that the
decimal numbers disappear. For example, USD amounts are multiplied by 100 so
that the cents disappear.
20.2 Bigints
Bigint is a new primitive data type for integers. Bigints don’t have a fixed storage size in
bits; their sizes adapt to the integers they represent:
• Small integers are represented with fewer bits than large integers.
• There is no negative lower limit or positive upper limit for the integers that can be
represented.
A bigint literal is a sequence of one or more digits, suffixed with an n – for example:
123n
Bigints are primitive values. typeof returns a new result for them:
> 2n**53n
9007199254740992n
> 2n**53n + 1n
9007199254740993n
> 2n**53n + 2n
9007199254740994n
/**
* Takes a bigint as an argument and returns a bigint
*/
function nthPrime(nth) {
if (typeof nth !== 'bigint') {
throw new TypeError();
}
function isPrime(p) {
for (let i = 2n; i < p; i++) {
if (p % i === 0n) return false;
}
return true;
172 20 Bigints – arbitrary-precision integers [ES2020] (advanced)
}
for (let i = 2n; ; i++) {
if (isPrime(i)) {
if (--nth === 0n) return i;
}
}
}
assert.deepEqual(
[1n, 2n, 3n, 4n, 5n].map(nth => nthPrime(nth)),
[2n, 3n, 5n, 7n, 11n]
);
• Decimal: 123n
• Hexadecimal: 0xFFn
• Binary: 0b1101n
• Octal: 0o777n
Negative bigints are produced by prefixing the unary minus operator: -0123n
Bigints are often used to represent money in the financial technical sector. Separators can
help here, too:
> 2n + 1
TypeError: Cannot mix BigInt and other types, use explicit conversions
The reason for this rule is that there is no general way of coercing a number and a bigint
to a common type: numbers can’t represent bigints beyond 53 bits, bigints can’t represent
fractions. Therefore, the exceptions warn us about typos that may lead to unexpected
results.
20.4 Reusing number operators for bigints (overloading) 173
For example, should the result of the following expression be 9007199254740993n or 9007199254740992?
2**53 + 1n
It is also not clear what the result of the following expression should be:
2n**53n * 3.3
> 7n * 3n
21n
> 1n / 2n
0n
> -(-64n)
64n
Unary + is not supported for bigints because much code relies on it coercing its operand
to number:
> +23n
TypeError: Cannot convert a BigInt value to a number
Comparing bigints and numbers does not pose any risks. Therefore, we can mix bigints
and numbers:
> 3n > -1
true
Bitwise operators interpret numbers as 32-bit integers. These integers are either unsigned
or signed. If they are signed, the negative of an integer is its two’s complement (adding an
174 20 Bigints – arbitrary-precision integers [ES2020] (advanced)
Due to these integers having a fixed size, their highest bits indicate their signs:
For bigints, bitwise operators interpret a negative sign as an infinite two’s complement –
for example:
That is, a negative sign is more of an external flag and not represented as an actual bit.
> ~0b10n
-3n
> ~0n
-1n
> ~-2n
1n
Applying binary bitwise operators to bigints works analogously to applying them to num-
bers:
The signed shift operators for bigints preserve the sign of a number:
20.4 Reusing number operators for bigints (overloading) 175
> 2n << 1n
4n
> -2n << 1n
-4n
> 2n >> 1n
1n
> -2n >> 1n
-1n
Recall that -1n is a sequence of ones that extends infinitely to the left. That’s why shifting
it left doesn’t change it:
> 2n >>> 1n
TypeError: BigInts have no unsigned right shift, use >> instead
Why? The idea behind unsigned right shifting is that a zero is shifted in “from the left”.
In other words, the assumption is that there is a finite amount of binary digits.
However, with bigints, there is no “left”, their binary digits extend infinitely. This is espe-
cially important with negative numbers.
Signed right shift works even with an infinite number of digits because the highest digit
is preserved. Therefore, it can be adapted to bigints.
> 0n == false
true
> 1n == true
true
x BigInt(x)
undefined Throws TypeError
null Throws TypeError
boolean false →0n, true →1n
number Example: 123 →123n
Non-integer →throws RangeError
bigint x (no change)
string Example: '123' →123n
Unparsable →throws SyntaxError
symbol Throws TypeError
object Configurable (e.g. via .valueOf())
> BigInt(undefined)
TypeError: Cannot convert undefined to a BigInt
> BigInt(null)
TypeError: Cannot convert null to a BigInt
Converting strings
If a string does not represent an integer, BigInt() throws a SyntaxError (whereas Number()
returns the error value NaN):
> BigInt('abc')
SyntaxError: Cannot convert abc to a BigInt
> BigInt('123n')
SyntaxError: Cannot convert 123n to a BigInt
> BigInt('123')
123n
> BigInt('0xFF')
255n
> BigInt('0b1101')
13n
> BigInt('0o777')
511n
> BigInt(123.45)
RangeError: The number 123.45 cannot be converted to a BigInt because
it is not an integer
> BigInt(123)
123n
Converting objects
How objects are converted to bigints can be configured – for example, by overriding .val-
ueOf():
• BigInt.prototype.toLocaleString(locales?, options?)
• BigInt.prototype.toString(radix?)
• BigInt.prototype.valueOf()
Casts theInt to width bits (signed). This influences how the value is represented internally.
• BigInt.asUintN(width, theInt)
Footnote:
• (1) Unary + is not supported for bigints, because much code relies on it coercing its
operand to number.
> JSON.stringify(123n)
TypeError: Do not know how to serialize a BigInt
> JSON.stringify([123n])
TypeError: Do not know how to serialize a BigInt
20.9 FAQ: Bigints 179
• Use numbers for up to 53 bits and for Array indices. Rationale: They already appear
everywhere and are handled efficiently by most engines (especially if they fit into
31 bits). Appearances include:
– Array.prototype.forEach()
– Array.prototype.entries()
• Use bigints for large numeric values: If your fraction-less values don’t fit into 53
bits, you have no choice but to move to bigints.
180 20 Bigints – arbitrary-precision integers [ES2020] (advanced)
All existing web APIs return and accept only numbers and will only upgrade to bigint on
a case-by-case basis.
20.9.2 Why not just increase the precision of numbers in the same man-
ner as is done for bigints?
One could conceivably split number into integer and double, but that would add many
new complexities to the language (several integer-only operators etc.). I’ve sketched the
consequences in a Gist.
Acknowledgements:
Unicode is a standard for representing and managing text in most of the world’s writ-
ing systems. Virtually all modern software that works with text, supports Unicode. The
standard is maintained by the Unicode Consortium. A new version of the standard is pub-
lished every year (with new emojis, etc.). Unicode version 1.0.0 was published in October
1991.
• Code points are numbers that represent the atomic parts of Unicode text. Most of
them represent visible symbols but they can also have other meanings such as spec-
ifying an aspect of a symbol (the accent of a letter, the skin tone of an emoji, etc.).
• Code units are numbers that encode code points, to store or transmit Unicode text.
One or more code units encode a single code point. Each code unit has the same
size, which depends on the encoding format that is used. The most popular format,
181
182 21 Unicode – a brief introduction (advanced)
> 'A'.codePointAt(0).toString(16)
'41'
> 'ü'.codePointAt(0).toString(16)
'fc'
> 'π'.codePointAt(0).toString(16)
'3c0'
> '🙂'.codePointAt(0).toString(16)
'1f642'
The hexadecimal numbers of the code points tell us that the first three characters reside in
plane 0 (within 16 bits), while the emoji resides in plane 1.
UTF-32 uses 32 bits to store code units, resulting in one code unit per code point. This
format is the only one with fixed-length encoding; all others use a varying number of code
21.1 Code points vs. code units 183
• Astral planes: The BMP comprises 0x10_000 code points. Given that Unicode has a
total of 0x110_000 code points, we still need to encode the remaining 0x100_000 code
points (20 bits). The BMP has two ranges of unassigned code points that provide the
necessary storage:
If a surrogate appears on its own, without its partner, it is called a lone surrogate.
This is how the bits of the code points are distributed among the surrogates:
As an example, consider code point 0x1F642 (🙂) that is represented by two UTF-16 code
units – 0xD83D and 0xDE42:
> '🙂'.codePointAt(0).toString(16)
'1f642'
> '🙂'.length
2
> '🙂'.split('')
[ '\uD83D', '\uDE42' ]
In contrast, code point 0x03C0 (π) is part of the BMP and therefore represented by a single
UTF-16 code unit – 0x03C0:
> 'π'.length
1
184 21 Unicode – a brief introduction (advanced)
UTF-8 has 8-bit code units. It uses 1–4 code units to encode a code point:
Notes:
Three examples:
For more information on Unicode and strings, consult “Atoms of text: code points, JavaScript
characters, grapheme clusters” (§22.7).
21.3 Grapheme clusters – the real characters 185
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
···
For HTML modules loaded in web browsers, the standard encoding is also UTF-8.
For example, the Devanagari kshi is encoded by 4 code points. We use Array.from() to split
a string into an Array with code points (for details, consult “Working with code points”
(§22.7.1)):
Flag emojis are also grapheme clusters and composed of two code points – for example,
the flag of Japan:
The distinction between a concept and its representation is subtle and can blur when talk-
ing about Unicode.
Strings
187
188 22 Strings
Inside a String.raw tagged template (line A), backslashes are treated as normal characters:
assert.equal(
String.raw`\ \n\t`, // (A)
'\\ \\n\\t',
);
> String(undefined)
'undefined'
> String(null)
'null'
> String(123.45)
'123.45'
> String(true)
'true'
);
Concatenating strings:
assert.equal(
'I bought ' + 3 + ' apples',
'I bought 3 apples',
);
Code points are the atomic parts of Unicode text. Most of them fit into one JavaScript
character, some of them occupy two (especially emojis):
assert.equal(
'A'.length, 1
);
assert.equal(
'🙂'.length, 2
);
Grapheme clusters (user-perceived characters) represent written symbols. Each one com-
prises one or more code points.
Due to these facts, we shouldn’t split text into JavaScript characters, we should split it into
grapheme clusters. For more information on how to handle text, see “Atoms of text: code
points, JavaScript characters, grapheme clusters” (§22.7).
Finding substrings:
190 22 Strings
> 'abca'.includes('a')
true
> 'abca'.startsWith('ab')
true
> 'abca'.endsWith('ca')
true
> 'abca'.indexOf('a')
0
> 'abca'.lastIndexOf('a')
3
assert.deepEqual(
'a, b,c'.split(/, ?/),
['a', 'b', 'c']
);
assert.equal(
['a', 'b', 'c'].join(', '),
'a, b, c'
);
> '*'.repeat(5)
'*****'
> '= b2b ='.toUpperCase()
'= B2B ='
> 'ΑΒΓ'.toLowerCase()
'αβγ'
Single quotes are used more often because it makes it easier to mention HTML, where
double quotes are preferred.
• String interpolation
• Multiple lines
• Raw string literals (backslash has no special meaning)
22.2.1 Escaping
The backslash lets us create special characters:
The backslash also lets us use the delimiter of a string literal inside that literal:
assert.equal(
'She said: "Let\'s go!"',
"She said: \"Let's go!\"");
The characters we see on screen are called grapheme clusters. Most of them are represented
by single JavaScript characters. However, there are also grapheme clusters (especially
emojis) that are represented by multiple JavaScript characters:
> '🙂'.length
2
How that works is explained in “Atoms of text: code points, JavaScript characters, grapheme
clusters” (§22.7).
192 22 Strings
getPackingList(true, 7),
'tooth brush, passport, water bottle'
);
• String(x)
• ''+x
• x.toString() (does not work for undefined and null)
Examples:
assert.equal(String(undefined), 'undefined');
assert.equal(String(null), 'null');
assert.equal(String(false), 'false');
assert.equal(String(true), 'true');
assert.equal(String(123.45), '123.45');
Pitfall for booleans: If we convert a boolean to a string via String(), we generally can’t
convert it back via Boolean():
> String(false)
'false'
> Boolean('false')
true
The only string for which Boolean() returns false, is the empty string.
Arrays have a better string representation, but it still hides much information:
> String([true])
'true'
> String(['true'])
'true'
> String(true)
'true'
const obj = {
toString() {
return 'hello';
}
};
assert.equal(String(obj), 'hello');
The caveat is that JSON only supports null, booleans, numbers, strings, Arrays, and ob-
jects (which it always treats as if they were created by object literals).
Tip: The third parameter lets us switch on multiline output and specify how much to
indent – for example:
{
"first": "Jane",
"last": "Doe"
}
22.6 Comparing strings 195
There is one important caveat to consider: These operators compare based on the numeric
values of JavaScript characters. That means that the order that JavaScript uses for strings
is different from the one used in dictionaries and phone books:
Properly comparing text is beyond the scope of this book. It is supported via the ECMA-
Script Internationalization API (Intl).
• Code points are the atomic parts of Unicode text. Each code point is 21 bits in size.
• JavaScript strings implement Unicode via the encoding format UTF-16. It uses one
or two 16-bit code units to encode a single code point.
– Each JavaScript character (as indexed in strings) is a code unit. In the JavaScript
standard library, code units are also called char codes.
The following code demonstrates that a single code point comprises one or two JavaScript
characters. We count the latter via .length:
A Unicode code point escape lets us specify a code point hexadecimally (1–5 digits). It pro-
duces one or two JavaScript characters.
> '\u{1F642}'
'🙂'
> String.fromCodePoint(0x1F642)
'🙂'
> '🙂'.codePointAt(0).toString(16)
'1f642'
We can iterate over a string, which visits code points (not JavaScript characters). Iteration
is described later in this book. One way of iterating is via a for-of loop:
Output:
🙂
a
> Array.from('🙂a')
[ '🙂', 'a' ]
> Array.from('🙂a').length
2
> '🙂a'.length
3
22.8 Quick reference: Strings 197
To specify a code unit hexadecimally, we can use a Unicode code unit escape with exactly
four hexadecimal digits:
> '\uD83D\uDE42'
'🙂'
And we can use String.fromCharCode(). Char code is the standard library’s name for code
unit:
> '🙂'.charCodeAt(0).toString(16)
'd83d'
> 'He\x6C\x6Co'
'Hello'
(The official name of ASCII escapes is Hexadecimal escape sequences – it was the first escape
that used hexadecimal numbers.)
Until that proposal becomes a standard, we can use one of several libraries that are avail-
able (do a web search for “JavaScript grapheme”).
x String(x)
undefined 'undefined'
null 'null'
boolean false →'false', true →'true'
number Example: 123 →'123'
bigint Example: 123n →'123'
string x (input, unchanged)
symbol Example: Symbol('abc') →'Symbol(abc)'
object Configurable via, e.g., toString()
Returns true if searchString occurs in the string at index startPos. Returns false
otherwise.
> '.gitignore'.startsWith('.')
true
> 'abcde'.startsWith('bc', 1)
true
Returns true if the string would end with searchString if its length were endPos.
Returns false otherwise.
> 'poem.txt'.endsWith('.txt')
true
> 'abcde'.endsWith('cd', 4)
true
Returns true if the string contains the searchString and false otherwise. The search
starts at startPos.
> 'abc'.includes('b')
true
> 'abc'.includes('b', 2)
false
Returns the lowest index at which searchString appears within the string or -1,
otherwise. Any returned index will be minIndex or higher.
> 'abab'.indexOf('a')
0
> 'abab'.indexOf('a', 1)
2
> 'abab'.indexOf('c')
-1
Returns the highest index at which searchString appears within the string or -1,
otherwise. Any returned index will be maxIndex or lower.
> 'abab'.lastIndexOf('ab', 2)
2
> 'abab'.lastIndexOf('ab', 1)
0
> 'abab'.lastIndexOf('ab')
2
• String.prototype.match(regExpOrString) [ES3]
match(
regExpOrString: string | RegExp
): null | RegExpMatchArray
};
}
Numbered capture groups become Array indices (which is why this type ex-
tends Array). Named capture groups](#named-capture-groups) (ES2018) be-
come properties of .groups. In this mode, .match() works like [RegExp.proto
type.exec().
Examples:
> 'ababb'.match(/a(b+)/)
{ 0: 'ab', 1: 'b', index: 0, input: 'ababb', groups: undefined }
> 'ababb'.match(/a(?<foo>b+)/)
{ 0: 'ab', 1: 'b', index: 0, input: 'ababb', groups: { foo: 'b' } }
> 'abab'.match(/x/)
null
match(
regExpOrString: RegExp
): null | Array<string>
> 'ababb'.match(/a(b+)/g)
[ 'ab', 'abb' ]
> 'ababb'.match(/a(?<foo>b+)/g)
[ 'ab', 'abb' ]
> 'abab'.match(/x/g)
null
• String.prototype.search(regExpOrString) [ES3]
Returns the index at which regExpOrString occurs within the string. If regExpOrString
is a string, it is used to create a regular expression (think parameter of new RegExp()).
> 'a2b'.search(/[0-9]/)
1
> 'a2b'.search('[0-9]')
1
Returns the substring of the string that starts at (including) index start and ends at
(excluding) index end. If an index is negative, it is added to .length before it is used
(-1 becomes this.length-1, etc.).
> 'abc'.slice(1, 3)
'bc'
> 'abc'.slice(1)
22.8 Quick reference: Strings 201
'bc'
> 'abc'.slice(-2)
'bc'
> 'abc'.at(0)
'a'
> 'abc'.at(-1)
'c'
[ES3]
• String.prototype.split(separator, limit?)
Splits the string into an Array of substrings – the strings that occur between the
separators.
The last invocation demonstrates that captures made by groups in the regular ex-
pression become elements of the returned Array.
If we want the separators to be part of the returned string fragments, we can use a
regular expression with a lookbehind assertion:
Thanks to the lookbehind assertion, the regular expression used for splitting matches
but doesn’t capture any characters (which would be taken away from the output
fragments).
Warning about .split(''): Using the method this way splits a string into JavaScript
characters. That doesn’t work well when dealing with astral code points (which are
encoded as two JavaScript characters). For example, emojis are astral:
> '🙂X🙂'.split('')
[ '\uD83D', '\uDE42', 'X', '\uD83D', '\uDE42' ]
> Array.from('🙂X🙂')
[ '🙂', 'X', '🙂' ]
• String.prototype.concat(...strings) [ES3]
Appends (fragments of) fillString to the string until it has the desired length len.
If it already has or exceeds len, then it is returned without any changes.
> '#'.padEnd(2)
'# '
> 'abc'.padEnd(2)
'abc'
> '#'.padEnd(5, 'abc')
'#abca'
Prepends (fragments of) fillString to the string until it has the desired length len.
If it already has or exceeds len, then it is returned without any changes.
> '#'.padStart(2)
' #'
> 'abc'.padStart(2)
'abc'
> '#'.padStart(5, 'abc')
'abca#'
• String.prototype.repeat(count=0) [ES6]
> '*'.repeat()
''
> '*'.repeat(3)
'***'
22.8 Quick reference: Strings 203
– (1 of 2) replaceValue is string.
replaceAll(
searchValue: string | RegExp,
replaceValue: string
): string
* $$: becomes $
* $n: becomes the capture of numbered group n (alas, $0 stands for the
string '$0', it does not refer to the complete match)
* $&: becomes the complete match
* $`: becomes everything before the match
* $': becomes everything after the match
Examples:
Example:
204 22 Strings
assert.equal(
'a 1995-12 b'.replaceAll(
/(?<year>[0-9]{4})-(?<month>[0-9]{2})/g, '|$<month>|'),
'a |12| b');
– (2 of 2) replaceValue is function.
replaceAll(
searchValue: string | RegExp,
replaceValue: (...args: Array<any>) => string
): string
If the second parameter is a function, occurrences are replaced with the strings
it returns. Its parameters args are:
Named capture groups (ES2018) are supported, too. If there are any, an argu-
ment is added at the end with an object whose properties contain the captures:
replace(
searchValue: string | RegExp,
replaceValue: string
): string
replace(
searchValue: string | RegExp,
replaceValue: (...args: Array<any>) => string
): string
• String.prototype.toUpperCase() [ES1]
Returns a copy of the string in which all lowercase alphabetic characters are con-
verted to uppercase. How well that works for various alphabets, depends on the
JavaScript engine.
> '-a2b-'.toUpperCase()
'-A2B-'
> 'αβγ'.toUpperCase()
'ΑΒΓ'
• String.prototype.toLowerCase() [ES1]
Returns a copy of the string in which all uppercase alphabetic characters are con-
verted to lowercase. How well that works for various alphabets, depends on the
JavaScript engine.
> '-A2B-'.toLowerCase()
'-a2b-'
> 'ΑΒΓ'.toLowerCase()
'αβγ'
• String.prototype.trim() [ES5]
Returns a copy of the string in which all leading and trailing whitespace (spaces,
tabs, line terminators, etc.) is gone.
• String.prototype.trimStart() [ES2019]
• String.prototype.trimEnd() [ES2019]
206 22 Strings
• String.prototype.isWellFormed() [ES2024]
Returns true if a string is ill-formed and contains lone surrogates (see .toWellFormed()
for more information). Otherwise, it returns false.
• String.prototype.toWellFormed() [ES2024]
Each JavaScript string character is a UTF-16 code unit. One code point is encoded
as either one UTF-16 code unit or two UTF-16 code unit. In the latter case, the two
code units are called leading surrogate and trailing surrogate. A surrogate without
its partner is called a lone surrogate. A string with one or more lone surrogates is
ill-formed.
assert.deepEqual(
'🙂'.split(''), // split into code units
['\uD83D', '\uDE42']
);
assert.deepEqual(
// 0xD83D is a lone surrogate
'\uD83D\uDE42\uD83D'.toWellFormed().split(''),
['\uD83D', '\uDE42', '\uFFFD']
);
Before we dig into the two features template literal and tagged template, let’s first examine
the multiple meanings of the term template.
• A text template is a function from data to text. It is frequently used in web devel-
209
210 23 Using template literals and tagged templates [ES6]
opment and often defined via text files. For example, the following text defines a
template for the library Handlebars:
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
This template has two blanks to be filled in: title and body. It is used like this:
// First step: retrieve the template text, e.g. from a text file.
const tmplFunc = Handlebars.compile(TMPL_TEXT); // compile string
const data = {title: 'My page', body: 'Welcome to my page!'};
const html = tmplFunc(data);
• A template literal is similar to a string literal, but has additional features – for example,
interpolation. It is delimited by backticks:
const num = 5;
assert.equal(`Count: ${num}!`, 'Count: 5!');
• Syntactically, a tagged template is a template literal that follows a function (or rather,
an expression that evaluates to a function). That leads to the function being called.
Its arguments are derived from the contents of the template literal.
Note that getArgs() receives both the text of the literal and the data interpolated via
${}.
First, it supports string interpolation: if we put a dynamically computed value inside a ${},
it is converted to a string and inserted into the string returned by the literal.
function tagFunc(...args) {
return args;
}
assert.deepEqual(
tagFunc`Setting ${setting} is ${value}!`, // (A)
[['Setting ', ' is ', '!'], 'dark mode', true] // (B)
);
The function tagFunc before the first backtick is called a tag function. Its arguments are:
• Template strings (first argument): an Array with the text fragments surrounding the
interpolations ${}.
The static (fixed) parts of the literal (the template strings) are kept separate from the dy-
namic parts (the substitutions).
• A raw interpretation where backslashes do not have special meaning. For example,
\t produces two characters – a backslash and a t. This interpretation of the template
strings is stored in property .raw of the first argument (an Array).
212 23 Using template literals and tagged templates [ES6]
The raw interpretation enables raw string literals via String.raw (described later) and sim-
ilar applications.
We can also use Unicode code point escapes (\u{1F642}), Unicode code unit escapes (\u03A9),
and ASCII escapes (\x52) in tagged templates:
assert.deepEqual(
cookedRaw`\u{54}\u0065\x78t`,
{
cooked: ['Text'],
raw: ['\\u{54}\\u0065\\x78t'],
substitutions: [],
});
If the syntax of one of these escapes isn’t correct, the corresponding cooked template string
is undefined, while the raw version is still verbatim:
assert.deepEqual(
cookedRaw`\uu\xx ${1} after`,
{
cooked: [undefined, ' after'],
raw: ['\\uu\\xx ', ' after'],
substitutions: [1],
});
Incorrect escapes produce syntax errors in template literals and string literals. Before
ES2018, they even produced errors in tagged templates. Why was that changed? We can
now use tagged templates for text that was previously illegal – for example:
windowsPath`C:\uuu\xxx\111`
latex`\unicode`
23.4 Examples of tagged templates (as provided via libraries) 213
@customElement('my-element')
class MyElement extends LitElement {
// ···
render() {
return html`
<ul>
${repeat(
this.items,
(item) => item.id,
(item, index) => html`<li>${index}: ${item.name}</li>`
)}
</ul>
`;
}
}
repeat() is a custom function for looping. Its second parameter produces unique keys for
the values returned by the third parameter. Note the nested tagged template used by that
parameter.
• Flag /v
• Flag /x (emulated) enables insignificant whitespace and line comments via #.
• Flag /n (emulated) enables named capture only mode, which prevents the grouping
metacharacters (···) from capturing.
Additionally, there are plugins for pre-compiling such queries in Babel, TypeScript, etc.
assert.equal(String.raw`\back`, '\\back');
This helps whenever data contains backslashes – for example, strings with regular expres-
sions:
All three regular expressions are equivalent. With a normal string literal, we have to write
the backslash twice, to escape it for that literal. With a raw string literal, we don’t have to
do that.
Raw string literals are also useful for specifying Windows filename paths:
23.6 (Advanced)
All remaining sections are advanced
For example:
function div(text) {
return `
<div>
${text}
</div>
`;
}
console.log('Output:');
console.log(
div('Hello!')
// Replace spaces with mid-dots:
.replace(/ /g, '·')
// Replace \n with #\n:
.replace(/\n/g, '#\n')
);
Due to the indentation, the template literal fits well into the source code. Alas, the output
is also indented. And we don’t want the return at the beginning and the return plus two
spaces at the end.
Output:
#
····<div>#
······Hello!#
····</div>#
··
There are two ways to fix this: via a tagged template or by trimming the result of the
template literal.
return dedent`
<div>
${text}
</div>
`.replace(/\n/g, '#\n');
}
console.log('Output:');
console.log(divDedented('Hello!'));
Output:
<div>#
Hello!#
</div>
function divDedented(text) {
return `
<div>
${text}
</div>
`.trim().replace(/\n/g, '#\n');
}
console.log('Output:');
console.log(divDedented('Hello!'));
The string method .trim() removes the superfluous whitespace at the beginning and at
the end, but the content itself must start in the leftmost column. The advantage of this
solution is that we don’t need a custom tag function. The downside is that it looks ugly.
Output:
<div>#
Hello!#
</div>
const addresses = [
{ first: '<Jane>', last: 'Bond' },
{ first: 'Lars', last: '<Croft>' },
];
The function tmpl() that produces the HTML table looks as follows:
• The first one (line 1) takes addrs, an Array with addresses, and returns a string with
a table.
• The second one (line 4) takes addr, an object containing an address, and returns a
string with a table row. Note the .trim() at the end, which removes unnecessary
whitespace.
The first templating function produces its result by wrapping a table element around an
Array that it joins into a string (line 10). That Array is produced by mapping the second
templating function to each element of addrs (line 3). It therefore contains strings with
table rows.
The helper function escapeHtml() is used to escape special HTML characters (line 6 and
line 7). Its implementation is shown in the next subsection.
Let us call tmpl() with the addresses and log the result:
console.log(tmpl(addresses));
<table>
<tr>
<td><Jane></td>
<td>Bond</td>
</tr><tr>
<td>Lars</td>
<td><Croft></td>
218 23 Using template literals and tagged templates [ES6]
</tr>
</table>
function escapeHtml(str) {
return str
.replace(/&/g, '&') // first!
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/`/g, '`')
;
}
assert.equal(
escapeHtml('Rock & Roll'), 'Rock & Roll');
assert.equal(
escapeHtml('<blank>'), '<blank>');
Symbols [ES6]
24.1 Symbols are primitives that are also like objects . . . . . . . . . . . . . . . 219
24.1.1 Symbols are primitive values . . . . . . . . . . . . . . . . . . . . . 219
24.1.2 Symbols are also like objects . . . . . . . . . . . . . . . . . . . . . 220
24.2 The descriptions of symbols . . . . . . . . . . . . . . . . . . . . . . . . . 220
24.3 Use cases for symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
24.3.1 Symbols as values for constants . . . . . . . . . . . . . . . . . . . 221
24.3.2 Symbols as unique property keys . . . . . . . . . . . . . . . . . . . 222
24.4 Publicly known symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
24.5 Converting symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
The parameter is optional and provides a description, which is mainly useful for debug-
ging.
219
220 24 Symbols [ES6]
const obj = {
[sym]: 123,
};
Prior to symbols, objects were the best choice if we needed values that were unique (only
equal to themselves):
assert.equal(mySymbol.toString(), 'Symbol(mySymbol)');
Second, since ES2019, we can retrieve the description via the property .description:
assert.equal(mySymbol.description, 'mySymbol');
On the plus side, logging that constant produces helpful output. On the minus side, there
is a risk of mistaking an unrelated value for a color because two strings with the same
content are considered equal:
assert.notEqual(COLOR_BLUE, MOOD_BLUE);
function getComplement(color) {
switch (color) {
case COLOR_RED:
return COLOR_GREEN;
case COLOR_ORANGE:
return COLOR_BLUE;
case COLOR_YELLOW:
return COLOR_VIOLET;
case COLOR_GREEN:
return COLOR_RED;
case COLOR_BLUE:
return COLOR_ORANGE;
case COLOR_VIOLET:
return COLOR_YELLOW;
default:
throw new Exception('Unknown color: '+color);
}
}
assert.equal(getComplement(COLOR_YELLOW), COLOR_VIOLET);
222 24 Symbols [ES6]
• The program operates at a base level. The keys at that level reflect the problem domain
– the area in which a program solves a problem – for example:
– If a program manages employees, the property keys may be about job titles,
salary categories, department IDs, etc.
– If the program is a chess app, the property keys may be about chess pieces,
chess boards, player colors, etc.
• ECMAScript and many libraries operate at a meta-level. They manage data and pro-
vide services that are not part of the problem domain – for example:
const point = {
x: 7,
y: 4,
toString() {
return `(${this.x}, ${this.y})`;
},
};
assert.equal(
String(point), '(7, 4)'); // (A)
.x and .y are base-level properties – they are used to solve the problem of
computing with points. .toString() is a meta-level property – it doesn’t have
anything to do with the problem domain.
const point = {
x: 7,
y: 4,
toJSON() {
return [this.x, this.y];
},
};
assert.equal(
JSON.stringify(point), '[7,4]');
The base level and the meta-level of a program must be independent: Base-level property
keys should not be in conflict with meta-level property keys.
• When a language is first created, it can use any meta-level names it wants. Base-
level code is forced to avoid those names. Later, however, when much base-level
code already exists, meta-level names can’t be chosen freely, anymore.
24.4 Publicly known symbols 223
• We could introduce naming rules to separate base level and meta-level. For example,
Python brackets meta-level names with two underscores: __init__, __iter__, _-
_hash__, etc. However, the meta-level names of the language and the meta-level
names of libraries would still exist in the same namespace and can clash.
These are two examples of where the latter was an issue for JavaScript:
• In May 2018, the Array method .flatten() had to be renamed to .flat() because
the former name was already used by libraries (source).
• In November 2020, the Array method .item() had to be renamed to .at() because
the former name was already used by library (source).
Symbols, used as property keys, help us here: Each symbol is unique and a symbol key
never clashes with any other string or symbol key.
As an example, let’s assume we are writing a library that treats objects differently if they
implement a special method. This is what defining a property key for such a method and
implementing it for an object would look like:
The square brackets in line A enable us to specify that the method must have the key
specialMethod. More details are explained in “Computed keys in object literals” (§30.7.2).
• Symbol.iterator: makes an object iterable. It’s the key of a method that returns an
iterator. For more information on this topic, see “Synchronous iteration”.
const PrimitiveNull = {
[Symbol.hasInstance](x) {
return x === null;
}
};
assert.equal(null instanceof PrimitiveNull, true);
224 24 Symbols [ES6]
> String({})
'[object Object]'
> String({ [Symbol.toStringTag]: 'is no money' })
'[object is no money]'
ing them to something else. What is the thinking behind that? First, conversion to number
never makes sense and should be warned about. Second, converting a symbol to a string
is indeed useful for diagnostic output. But it also makes sense to warn about accidentally
turning a symbol into a string (which is a different kind of property key):
The downside is that the exceptions make working with symbols more complicated. You
have to explicitly convert symbols when assembling strings via the plus operator:
225
Chapter 25
227
228 25 Control flow statements
• if statement [ES1]
• switch statement [ES3]
• while loop [ES1]
• do-while loop [ES3]
• for loop [ES1]
• for-of loop [ES6]
• for-await-of loop [ES2018]
• for-in loop [ES1]
25.1.1 break
There are two versions of break: one with an operand and one without an operand. The
latter version works inside the following statements: while, do-while, for, for-of, for-
await-of, for-in and switch. It immediately leaves the current statement:
Output:
a
---
b
my_label: { // label
if (condition) break my_label; // labeled break
// ···
}
• Fail: The loop finishes without finding a result. That is handled directly after the
loop (line B).
• Succeed: While looping, we find a result. Then we use break plus label (line A) to
skip the code that handles failure.
25.1 Controlling loops: break and continue 229
25.1.3 continue
continue only works inside while, do-while, for, for-of, for-await-of, and for-in. It im-
mediately leaves the current loop iteration and continues with the next one – for example:
const lines = [
'Normal line',
'# Comment',
'Another normal line',
];
for (const line of lines) {
if (line.startsWith('#')) continue;
console.log(line);
}
Output:
Normal line
Another normal line
230 25 Control flow statements
if (value) {}
if (Boolean(value) === true) {}
• undefined, null
• false
• 0, NaN
• 0n
• ''
All other values are truthy. For more information, see “Falsy and truthy values” (§17.2).
if (cond) {
// then branch
}
if (cond) {
// then branch
} else {
// else branch
}
if (cond1) {
// ···
} else if (cond2) {
// ···
}
if (cond1) {
// ···
} else if (cond2) {
// ···
} else {
// ···
}
if («cond») «then_statement»
else «else_statement»
So far, the then_statement has always been a block, but we can use any statement. That
statement must be terminated with a semicolon:
That means that else if is not its own construct; it’s simply an if statement whose else_-
statement is another if statement.
switch («switch_expression») {
«switch_body»
}
case «case_expression»:
«statements»
default:
«statements»
function dayOfTheWeek(num) {
switch (num) {
case 1:
return 'Monday';
case 2:
return 'Tuesday';
case 3:
return 'Wednesday';
232 25 Control flow statements
case 4:
return 'Thursday';
case 5:
return 'Friday';
case 6:
return 'Saturday';
case 7:
return 'Sunday';
}
}
assert.equal(dayOfTheWeek(5), 'Friday');
At the end of a case clause, execution continues with the next case clause, unless we return
or break – for example:
function englishToFrench(english) {
let french;
switch (english) {
case 'hello':
french = 'bonjour';
case 'goodbye':
french = 'au revoir';
}
return french;
}
// The result should be 'bonjour'!
assert.equal(englishToFrench('hello'), 'au revoir');
That is, our implementation of dayOfTheWeek() only worked because we used return. We
can fix englishToFrench() by using break:
function englishToFrench(english) {
let french;
switch (english) {
case 'hello':
french = 'bonjour';
break;
case 'goodbye':
french = 'au revoir';
break;
}
return french;
}
assert.equal(englishToFrench('hello'), 'bonjour'); // ok
25.4 switch statements [ES3] 233
The statements of a case clause can be omitted, which effectively gives us multiple case
expressions per case clause:
function isWeekDay(name) {
switch (name) {
case 'Monday':
case 'Tuesday':
case 'Wednesday':
case 'Thursday':
case 'Friday':
return true;
case 'Saturday':
case 'Sunday':
return false;
}
}
assert.equal(isWeekDay('Wednesday'), true);
assert.equal(isWeekDay('Sunday'), false);
A default clause is jumped to if the switch expression has no other match. That makes it
useful for error checking:
function isWeekDay(name) {
switch (name) {
case 'Monday':
case 'Tuesday':
case 'Wednesday':
case 'Thursday':
case 'Friday':
return true;
case 'Saturday':
case 'Sunday':
return false;
default:
throw new Error('Illegal value: '+name);
}
}
assert.throws(
() => isWeekDay('January'),
{message: 'Illegal value: January'});
234 25 Control flow statements
Exercises: switch
• exercises/control-flow/number_to_month_test.mjs
• Bonus: exercises/control-flow/is_object_via_switch_test.mjs
while («condition») {
«statements»
}
Output:
a
b
c
while (true) {
if (Math.random() === 0) break;
}
let input;
do {
input = prompt('Enter text:');
25.7 for loops [ES1] 235
console.log(input);
} while (input !== ':q');
do-while can also be viewed as a while loop that runs at least once.
prompt() is a global function that is available in web browsers. It prompts the user to input
text and returns it.
The first line is the head of the loop and controls how often the body (the remainder of the
loop) is executed. It has three parts and each of them is optional:
• initialization: sets up variables, etc. for the loop. Variables declared here via let
or const only exist inside the loop.
• condition: This condition is checked before each loop iteration. If it is falsy, the loop
stops.
• post_iteration: This code is executed after each loop iteration.
«initialization»
while («condition») {
«statements»
«post_iteration»
}
Output:
0
1
2
Output:
a
b
c
for (;;) {
if (Math.random() === 0) break;
}
Output:
hello
world
In contrast, in for loops we must declare variables via let or var if their values change.
Output:
0 -> a
1 -> b
2 -> c
Exercise: for-of
exercises/control-flow/array_to_string_test.mjs
Output:
0
1
2
propKey
Exception handling
239
240 26 Exception handling
function readProfiles(filePaths) {
const profiles = [];
for (const filePath of filePaths) {
try {
const profile = readOneProfile(filePath);
profiles.push(profile);
} catch (err) { // (A)
console.log('Error in: '+filePath, err);
}
}
}
function readOneProfile(filePath) {
const profile = new Profile();
const file = openFile(filePath);
// ··· (Read the data in `file` into `profile`)
return profile;
}
function openFile(filePath) {
if (!fs.existsSync(filePath)) {
throw new Error('Could not find file '+filePath); // (B)
}
// ··· (Open the file whose path is `filePath`)
}
Let’s examine what happens in line B: An error occurred, but the best place to handle the
problem is not the current location, it’s line A. There, we can skip the current file and move
on to the next one.
Therefore:
readProfiles(···)
for (const filePath of filePaths)
try
readOneProfile(···)
openFile(···)
if (!fs.existsSync(filePath))
throw
One by one, throw exits the nested constructs, until it encounters a try statement. Execu-
tion continues in the catch clause of that try statement.
26.2 throw 241
26.2 throw
This is the syntax of the throw statement:
throw «value»;
• Using class Error directly. That is less limiting in JavaScript than in a more static
language because we can add our own properties to instances:
try {
«try_statements»
} catch (error) {
«catch_statements»
} finally {
«finally_statements»
}
• try-catch
• try-finally
• try-catch-finally
242 26 Exception handling
The following code demonstrates that the value that is thrown in line A is indeed caught
in line B.
try {
func();
} catch (err) { // (B)
assert.equal(err, errorObject);
}
We can omit the catch parameter if we are not interested in the value that was thrown:
try {
// ···
} catch {
// ···
}
That may occasionally be useful. For example, Node.js has the API function assert.throws(func)
that checks whether an error is thrown inside func. It could be implemented as follows.
function throws(func) {
try {
func();
} catch {
return; // everything OK
}
throw new Error('Function didn’t throw an exception!');
}
However, a more complete implementation of this function would have a catch parameter
and would, for example, check that its type is as expected.
26.4 Error and its subclasses 243
Let’s look at a common use case for finally: We have created a resource and want to
always destroy it when we are done with it, no matter what happens while working with
it. We would implement that as follows:
The finally clause is always executed, even if an error is thrown (line A):
class Error {
// Instance properties
message: string;
cause?: any; // ES2022
stack: string; // non-standard but widely supported
constructor(
message: string = '',
options?: ErrorOptions // ES2022
);
}
interface ErrorOptions {
cause?: any; // ES2022
}
The subsections after the next one explain the instance properties .message, .cause and
.stack in more detail.
Error.prototype.name
> Error.prototype.name
'Error'
> RangeError.prototype.name
'RangeError'
Therefore, there are two ways to get the name of the class of a built-in error object:
If we omit the message then the empty string is used as a default value (inherited from
Error.prototype.message):
The instance property .stack is not an ECMAScript feature, but it is widely supported by
JavaScript engines. It is usually a string, but its exact structure is not standardized and
varies between engines.
The instance property .cause is created via the options object in the second parameter of
new Error(). It specifies which other error caused the current one.
For information on how to use this property see “Chaining errors” (§26.5).
function readFiles(filePaths) {
return filePaths.map(
(filePath) => {
try {
const text = readText(filePath);
const json = JSON.parse(text);
return processJson(json);
} catch (error) {
// (A)
}
});
}
The statements inside the try clause may throw all kinds of errors. In most cases, an error
won’t be aware of the path of the file that caused it. That’s why we would like to attach
that information in line A.
function readFiles(filePaths) {
return filePaths.map(
(filePath) => {
try {
// ···
} catch (error) {
throw new Error(
`While processing ${filePath}`,
{cause: error}
);
}
});
}
26.5 Chaining errors 247
/**
* An error class that supports error chaining.
* If there is built-in support for .cause, it uses it.
* Otherwise, it creates this property itself.
*/
class CausedError extends Error {
constructor(message, options) {
super(message, options);
if (
(isObject(options) && 'cause' in options)
&& !('cause' in this)
) {
// .cause was specified but the superconstructor
// did not create an instance property.
const cause = options.cause;
this.cause = cause;
if ('stack' in cause) {
this.stack = this.stack + '\nCAUSE: ' + cause.stack;
}
}
}
}
function isObject(value) {
return value !== null && typeof value === 'object';
}
Callable values
249
250 27 Callable values
In this chapter, we look at JavaScript values that can be invoked: functions, methods, and
classes.
– Real function
– Method
– Constructor function
• A specialized function can only play one of those roles – for example:
Inside a scope, function declarations are activated early (see “Declarations: scope and ac-
tivation” (§13.8)) and can be called before they are declared. That is occasionally useful.
Variable declarations, such as the one for ordinary2, are not activated early.
myName is only accessible inside the body of the function. The function can use it to refer to
itself (for self-recursion, etc.) – independently of which variable it is assigned to:
Even if they are not assigned to variables, named function expressions have names (line
A):
function getNameOfCallback(callback) {
return callback.name;
}
assert.equal(
getNameOfCallback(function () {}), ''); // anonymous
assert.equal(
getNameOfCallback(function named() {}), 'named'); // (A)
Note that functions created via function declarations or variable declarations always have
names:
function funcDecl() {}
assert.equal(
getNameOfCallback(funcDecl), 'funcDecl');
One benefit of functions having names is that those names show up in error stack traces.
While function declarations are still popular in JavaScript, function expressions are almost
always arrow functions in modern code.
function add(x, y) {
return x + y;
}
JavaScript has always allowed and ignored trailing commas in Array literals. Since ES5,
they are also allowed in object literals. Since ES2017, we can add trailing commas to pa-
rameter lists (declarations and invocations):
// Declaration
function retrieveData(
contentText,
keyword,
{unique, ignoreCase, pageSize}, // trailing comma
) {
// ···
}
// Invocation
retrieveData(
'',
null,
{ignoreCase: true, pageSize: 10}, // trailing comma
);
function add(x, y) {
return x + y;
}
27.3 Specialized functions [ES6] 253
This function declaration creates an ordinary function whose name is add. As an ordinary
function, add() can play three roles:
As an aside, the names of constructor functions (incl. classes) normally start with
capital letters.
• Syntax is the code that we use to create entities. Function declarations and anony-
mous function expressions are syntax. They both create entities that are called ordi-
nary functions.
• A role describes how we use entities. The entity ordinary function can play the role
real function, or the role method, or the role class. The entity arrow function can also
play the role real function.
– The roles of functions are: real function, method, and constructor function.
Many other programming languages only have a single entity that plays the role real func-
tion. Then they can use the name function for both role and entity.
const obj = {
myMethod() {
return 'abc';
}
};
assert.equal(obj.myMethod(), 'abc');
class MyClass {
/* ··· */
}
const inst = new MyClass();
Apart from nicer syntax, each kind of specialized function also supports new features,
making them better at their jobs than ordinary functions.
Table 27.1: Capabilities of four kinds of functions. If a cell value is in parentheses, that
implies some kind of limitation. The special variable this is explained in “The special
variable this in methods, ordinary functions and arrow functions” (§27.3.3).
We’ll first examine the syntax of arrow functions and then how this works in various
functions.
The (roughly) equivalent arrow function looks as follows. Arrow functions are expres-
sions.
Here, the body of the arrow function is a block. But it can also be an expression. The
following arrow function works exactly like the previous one.
If an arrow function has only a single parameter and that parameter is an identifier (not a
destructuring pattern) then you can omit the parentheses around the parameter:
const id = x => x;
That is convenient when passing arrow functions as parameters to other functions or meth-
ods:
If you want the expression body of an arrow function to be an object literal, you must put
the literal in parentheses:
If you don’t, JavaScript thinks, the arrow function has a block body (that doesn’t return
anything):
{a: 1} is interpreted as a block with the label a: and the expression statement 1. Without
an explicit return statement, the block body returns undefined.
This pitfall is caused by syntactic ambiguity: object literals and code blocks have the same
syntax. We use the parentheses to tell JavaScript that the body is an expression (an object
literal) and not a statement (a block).
27.3.3 The special variable this in methods, ordinary functions and ar-
row functions
Inside methods, the special variable this lets us access the receiver – the object which re-
ceived the method call:
const obj = {
myMethod() {
assert.equal(this, obj);
}
};
obj.myMethod();
Ordinary functions can be methods and therefore also have the implicit parameter this:
const obj = {
myMethod: function () {
assert.equal(this, obj);
}
};
obj.myMethod();
this is even an implicit parameter when we use an ordinary function as a real function.
Then its value is undefined (if strict mode is active, which it almost always is):
function ordinaryFunc() {
assert.equal(this, undefined);
}
ordinaryFunc();
27.3 Specialized functions [ES6] 257
That means that an ordinary function, used as a real function, can’t access the this of a
surrounding method (line A). In contrast, arrow functions don’t have this as an implicit
parameter. They treat it like any other variable and can therefore access the this of a
surrounding method (line B):
const jill = {
name: 'Jill',
someMethod() {
function ordinaryFunc() {
assert.throws(
() => this.name, // (A)
/^TypeError: Cannot read properties of undefined \(reading 'name'\)$/);
}
ordinaryFunc();
• Dynamic this: In line A, we try to access the this of .someMethod() from an ordinary
function. There, it is shadowed by the function’s own this, which is undefined (as
filled in by the function call). Given that ordinary functions receive their this via
(dynamic) function or method calls, their this is called dynamic.
• Lexical this: In line B, we again try to access the this of .someMethod(). This time,
we succeed because the arrow function does not have its own this. this is resolved
lexically, just like any other variable. That’s why the this of arrow functions is called
lexical.
When it comes to real functions, the choice between an arrow function and an ordinary
function is less clear-cut, though:
• For anonymous inline function expressions, arrow functions are clear winners, due
to their compact syntax and them not having this as an implicit parameter:
• For stand-alone named function declarations, arrow functions still benefit from lex-
ical this. But function declarations (which produce ordinary functions) have nice
258 27 Callable values
syntax and early activation is also occasionally useful (see “Declarations: scope and
activation” (§13.8)). If this doesn’t appear in the body of an ordinary function, there
is no downside to using it as a real function. The static checking tool ESLint can warn
us during development when we do this wrong via a built-in rule.
function timesOrdinary(x, y) {
return x * y;
}
const timesArrow = (x, y) => {
return x * y;
};
So far, all (real) functions and methods, that we have seen, were:
• Single-result
• Synchronous
• Iteration treats objects as containers of data (so-called iterables) and provides a stan-
dardized way for retrieving what is inside them. If a function or a method returns
an iterable, it returns multiple values.
• Asynchronous programming deals with handling a long-running computation. You
are notified when the computation is finished and can do something else in between.
The standard pattern for asynchronously delivering single results is called Promise.
These modes can be combined – for example, there are synchronous iterables and asyn-
chronous iterables.
Several new kinds of functions and methods help with some of the mode combinations:
• Async functions help implement functions that return Promises. There are also async
methods.
• Synchronous generator functions help implement functions that return synchronous
iterables. There are also synchronous generator methods.
• Asynchronous generator functions help implement functions that return asynchronous
iterables. There are also asynchronous generator methods.
Table 27.2 gives an overview of the syntax for creating these 4 kinds of functions and meth-
ods.
Result #
Sync function Sync method
function f() {} { m() {} } value 1
f = function () {}
f = () => {}
Sync generator function Sync gen. method
function* f() {} { * m() {} } iterable 0+
f = function* () {}
Async function Async method
async function f() {} { async m() {} } Promise 1
f = async function () {}
f = async () => {}
Async generator function Async gen. method
async function* f() {} { async * m() {} } async iterable 0+
f = async function* () {}
Table 27.2: Syntax for creating functions and methods. The last column specifies how
many values are produced by an entity.
function func() {
return 123;
}
assert.equal(func(), 123);
Another example:
function boolToYesNo(bool) {
if (bool) {
return 'Yes';
} else {
return 'No';
}
}
assert.equal(boolToYesNo(true), 'Yes');
assert.equal(boolToYesNo(false), 'No');
If, at the end of a function, you haven’t returned anything explicitly, JavaScript returns
undefined for you:
260 27 Callable values
function noReturn() {
// No explicit return
}
assert.equal(noReturn(), undefined);
• Parameters are part of a function definition. They are also called formal parameters
and formal arguments.
• Arguments are part of a function call. They are also called actual parameters and actual
arguments.
Output:
a
b
For example:
function foo(x, y) {
return [x, y];
}
assert.deepEqual(
f(undefined, undefined),
[undefined, 0]);
There are two restrictions related to how we can use rest parameters:
• We cannot use more than one rest parameter per function definition.
assert.throws(
() => eval('function f(...x, ...y) {}'),
/^SyntaxError: Rest parameter must be last formal parameter$/
);
• A rest parameter must always come last. As a consequence, we can’t access the last
parameter like this:
262 27 Callable values
assert.throws(
() => eval('function f(...restParams, lastParam) {}'),
/^SyntaxError: Rest parameter must be last formal parameter$/
);
You can use a rest parameter to enforce a certain number of arguments. Take, for example,
the following function:
function createPoint(x, y) {
return {x, y};
// same as {x: x, y: y}
}
function createPoint(...args) {
if (args.length !== 2) {
throw new Error('Please provide exactly 2 arguments!');
}
const [x, y] = args; // (A)
return {x, y};
}
selectEntries(3, 20, 2)
• They lead to more self-explanatory code because each argument has a descriptive
label. Just compare the two versions of selectEntries(): with the second one, it is
much easier to see what happens.
• The order of the arguments doesn’t matter (as long as the names are correct).
• Handling more than one optional parameter is more convenient: callers can easily
provide any subset of all optional parameters and don’t have to be aware of the
27.6 Parameter handling 263
ones they omit (with positional parameters, you have to fill in preceding optional
parameters, with undefined).
This function uses destructuring to access the properties of its single parameter. The pattern
it uses is an abbreviation for the following pattern:
> selectEntries({})
{ start: 0, end: -1, step: 1 }
But it does not work if you call the function without any parameters:
> selectEntries()
TypeError: Cannot read properties of undefined (reading 'start')
You can fix this by providing a default value for the whole pattern. This default value
works the same as default values for simpler parameter definitions: if the parameter is
missing, the default is used.
function func(x, y) {
console.log(x);
console.log(y);
}
const someIterable = ['a', 'b'];
func(...someIterable);
// same as func('a', 'b')
Output:
264 27 Callable values
a
b
Spreading and rest parameters use the same syntax (...), but they serve opposite pur-
poses:
• Rest parameters are used when defining functions or methods. They collect argu-
ments into Arrays.
• Spread arguments are used when calling functions or methods. They turn iterable
objects into arguments.
Math.max() returns the largest one of its zero or more arguments. Alas, it can’t be used for
Arrays, but spreading gives us a way out:
Similarly, the Array method .push() destructively adds its zero or more parameters to
the end of its Array. JavaScript has no method for destructively appending an Array to
another one. Once again, we are saved by spreading:
arr1.push(...arr2);
assert.deepEqual(arr1, ['a', 'b', 'c', 'd']);
However, with .call(), we can also specify a value for the implicit parameter this. In
other words: .call() makes the implicit parameter this explicit.
function func(x, y) {
return [this, x, y];
}
assert.deepEqual(
func.call('hello', 'a', 'b'),
['hello', 'a', 'b']);
assert.deepEqual(
func('a', 'b'),
[undefined, 'a', 'b']);
assert.deepEqual(
func.call(undefined, 'a', 'b'),
[undefined, 'a', 'b']);
In arrow functions, the value for this provided via .call() (or other means) is ignored.
This method invocation is loosely equivalent to the following function call (which uses
spreading):
However, with .apply(), we can also specify a value for the implicit parameter this.
function func(x, y) {
return [this, x, y];
}
.bind() returns a new function boundFunc(). Calling that function invokes someFunc()
with this set to thisValue and these parameters: arg1, arg2, followed by the parameters
of boundFunc().
boundFunc('a', 'b')
someFunc.call(thisValue, arg1, arg2, 'a', 'b')
An alternative to .bind()
An implementation of .bind()
Considering the previous section, .bind() can be implemented as a real function as fol-
lows:
Using .bind() for real functions is somewhat unintuitive because we have to provide a
value for this. Given that it is undefined during function calls, it is usually set to undefined
or null.
In the following example, we create add8(), a function that has one parameter, by binding
the first parameter of add() to 8.
function add(x, y) {
return x + y;
}
In this chapter, we’ll look at two ways of evaluating code dynamically: eval() and new
Function().
28.1 eval()
Given a string str with JavaScript code, eval(str) evaluates that code and returns the
result:
• Directly, via a function call. Then the code in its argument is evaluated inside the
current scope.
• Indirectly, not via a function call. Then it evaluates its code in global scope.
“Not via a function call” means “anything that looks different than eval(···)”:
267
268 28 Evaluating code dynamically: eval(), new Function() (advanced)
• Etc.
globalThis.myVariable = 'global';
function func() {
const myVariable = 'local';
// Direct eval
assert.equal(eval('myVariable'), 'local');
// Indirect eval
assert.equal(eval.call(undefined, 'myVariable'), 'global');
}
Evaluating code in global context is safer because the code has access to fewer internals.
The previous statement is equivalent to the next statement. Note that «param_1», etc., are
not inside string literals, anymore.
In the next example, we create the same function twice, first via new Function(), then via
a function expression:
28.3 Recommendations
Avoid dynamic evaluation of code as much as you can:
• It’s a security risk because it may enable an attacker to execute arbitrary code with
the privileges of your code.
• It may be switched off – for example, in browsers, via a Content Security Policy.
28.3 Recommendations 269
Very often, JavaScript is dynamic enough so that you don’t need eval() or similar. In the
following example, what we are doing with eval() (line A) can be achieved just as well
without it (line B).
• Prefer new Function() over eval(): it always executes its code in global context and
a function provides a clean interface to the evaluated code.
• Prefer indirect eval over direct eval: evaluating code in global context is safer.
270 28 Evaluating code dynamically: eval(), new Function() (advanced)
Part VI
Modularity
271
Chapter 29
Modules [ES6]
273
274 29 Modules [ES6]
// Namespace import
import * as lib1 from './lib1.mjs';
assert.equal(lib1.one, 1);
assert.equal(lib1.myFunc(), 3);
The string after from is called a module specifier. It identifies from which module we want
to import.
29.1 Cheat sheet: modules 275
A default export is the exception to the rule that function declarations always have names:
In the previous example, we can omit the name getHello.
There can be at most one default export. That’s why const or let can’t be default-exported
(line A).
'https://www.unpkg.com/browse/[email protected]/browser.mjs'
'file:///opt/nodejs/config.mjs'
276 29 Modules [ES6]
Absolute specifiers are mostly used to access libraries that are directly hosted on the
web.
• Relative specifiers are relative URLs (starting with '/', './' or '../') – for example:
'./sibling-module.js'
'../module-in-parent-dir.mjs'
'../../dir/other-module.js'
Relative specifiers are mostly used to access other modules within the same code
base.
• Bare specifiers are paths (without protocol and domain) that start with neither slashes
nor dots. They begin with the names of packages (as installed via a package manager
such npm). Those names can optionally be followed by subpaths:
'some-package'
'some-package/sync'
'some-package/util/files/path-tools.js'
'@some-scope/scoped-name'
'@some-scope/scoped-name/async'
'@some-scope/scoped-name/dir/some-module.mjs'
Each bare specifier refers to exactly one module inside a package; if it has no subpath,
it refers to the designated “main” module of its package.
• Scripts are code fragments that browsers run in global scope. They are precursors of
modules.
• CommonJS modules are a module format that is mainly used on servers (e.g., via
Node.js).
• AMD modules are a module format that is mainly used in browsers.
• ECMAScript modules are JavaScript’s built-in module format. It supersedes all pre-
vious formats.
Table 29.1 gives an overview of these code formats. Note that for CommonJS modules
and ECMAScript modules, two filename extensions are commonly used. Which one is
appropriate depends on how we want to use a file. Details are given later in this chapter.
<script src="other-module1.js"></script>
<script src="other-module2.js"></script>
<script src="my-module.js"></script>
// Body
function internalFunc() {
// ···
}
function exportedFunc() {
importedFunc1();
importedFunc2();
internalFunc();
}
myModule is a global variable that is assigned the result of immediately invoking a function
expression. The function expression starts in the first line. It is invoked in the last line.
This way of wrapping a code fragment is called immediately invoked function expression (IIFE,
coined by Ben Alman). What do we gain from an IIFE? var is not block-scoped (like const
278 29 Modules [ES6]
and let), it is function-scoped: the only way to create new scopes for var-declared vari-
ables is via functions or methods (with const and let, we can use either functions, meth-
ods, or blocks {}). Therefore, the IIFE in the example hides all of the following variables
from global scope and minimizes name clashes: importedFunc1, importedFunc2, inter-
nalFunc, exportedFunc.
Note that we are using an IIFE in a particular manner: at the end, we pick what we want to
export and return it via an object literal. That is called the revealing module pattern (coined
by Christian Heilmann).
• Libraries in script files export and import functionality via global variables, which
risks name clashes.
• Dependencies are not stated explicitly, and there is no built-in way for a script to
load the scripts it depends on. Therefore, the web page has to load not just the
scripts that are needed by the page but also the dependencies of those scripts, the
dependencies’ dependencies, etc. And it has to do so in the right order!
From now on, CommonJS module means the Node.js version of this standard (which has a
few additional features). This is an example of a CommonJS module:
// Imports
var importedFunc1 = require('./other-module1.js').importedFunc1;
var importedFunc2 = require('./other-module2.js').importedFunc2;
// Body
function internalFunc() {
// ···
}
function exportedFunc() {
importedFunc1();
importedFunc2();
internalFunc();
29.4 Module systems created prior to ES6 279
// Exports
module.exports = {
exportedFunc: exportedFunc,
};
define(['./other-module1.js', './other-module2.js'],
function (otherModule1, otherModule2) {
var importedFunc1 = otherModule1.importedFunc1;
var importedFunc2 = otherModule2.importedFunc2;
function internalFunc() {
// ···
}
function exportedFunc() {
importedFunc1();
importedFunc2();
internalFunc();
}
return {
exportedFunc: exportedFunc,
};
});
On the plus side, AMD modules can be executed directly. In contrast, CommonJS modules
must either be compiled before deployment or custom source code must be generated and
evaluated dynamically (think eval()). That isn’t always permitted on the web.
280 29 Modules [ES6]
• With CommonJS, ES modules share the compact syntax and support for cyclic de-
pendencies.
• With AMD, ES modules share being designed for asynchronous loading.
function internalFunc() {
···
}
1. Syntax (how code is written): What is a module? How are imports and exports
declared? Etc.
2. Semantics (how code is executed): How are variable bindings exported? How are
imports connected with exports? Etc.
3. A programmatic loader API for configuring module loading.
lib/my-math.mjs
main.mjs
To export something, we put the keyword export in front of a declaration. Entities that are
not exported are private to a module and can’t be accessed from outside.
assert.deepEqual(
Object.keys(myMath), ['LIGHTSPEED', 'square']);
But we can also use separate export clauses. For example, this is what lib/my-math.mjs
looks like with an export clause:
function times(a, b) {
return a * b;
}
function square(x) {
return times(x, x);
}
const LIGHTSPEED = 299792458;
With an export clause, we can rename before exporting and use different names internally:
function times(a, b) {
return a * b;
}
function sq(x) {
return times(x, x);
}
const LS = 299792458;
export {
sq as square,
LS as LIGHTSPEED, // trailing comma is optional
};
my-func.mjs
main.mjs
Note the syntactic difference: the curly braces around named imports indicate that we are
reaching into the module, while a default import is the module.
284 29 Modules [ES6]
Second, we can directly default-export values. This style of export default is much like
a declaration.
The reason is that export default can’t be used to label const: const may define multiple
values, but export default needs exactly one value. Consider the following hypothetical
code:
With this code, we don’t know which one of the three values is the default export.
export {
greet as default,
};
The default export is also available via property .default of namespace imports:
29.8 Re-exporting
A module library.mjs can export one or more exports of another module internal.mjs
as if it had made them itself. That is called re-exporting.
• The wildcard re-export turns all exports of module internal.mjs into exports of
library.mjs, except the default export.
• The namespace re-export turns all exports of module internal.mjs into an object
that becomes the named export ns of library.mjs. Because internal.mjs has a de-
fault export, ns has a property .default.
assert.deepEqual(
Object.keys(library),
['DEF', 'INTERNAL_DEF', 'func', 'internalFunc', 'ns']
);
assert.deepEqual(
Object.keys(library.ns),
['INTERNAL_DEF', 'default', 'internalFunc']
);
counter.mjs
main.mjs
main.mjs name-imports both exports. When we use incCounter(), we discover that the
connection to counter is live – we can always access the live state of that variable:
Note that while the connection is live and we can read counter, we cannot change this
variable (e.g., via counter++).
29.10 npm packages 287
• It is easier to split modules because previously shared variables can become exports.
• This behavior is crucial for supporting transparent cyclic imports. Read on for more
information.
N O
P Q R S
in two phases:
• Instantiation: Every module is visited and its imports are connected to its exports.
Before a parent can be instantiated, all of its children must be instantiated.
• Evaluation: The bodies of the modules are executed. Once again, children are eval-
uated before parents.
This approach handles cyclic imports correctly, due to two features of ES modules:
• Due to the static structure of ES modules, the exports are already known after pars-
ing. That makes it possible to instantiate P before its child M: P can already look up
M’s exports.
• When P is evaluated, M hasn’t been evaluated, yet. However, entities in P can al-
ready mention imports from M. They just can’t use them, yet, because the imported
values are filled in later. For example, a function in P can access an import from
M. The only limitation is that we must wait until after the evaluation of M, before
calling that function.
Imports being filled in later is enabled by them being “live immutable views” on
exports.
{
"name": "my-package",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
• name specifies the name of this package. Once it is uploaded to the npm registry, it
can be installed via npm install my-package.
• version is used for version management and follows semantic versioning, with
three numbers:
– Major version: is incremented when incompatible API changes are made.
– Minor version: is incremented when functionality is added in a backward
compatible manner.
– Patch version: is incremented when backward compatible changes are made.
• description, keywords, author make it easier to find packages.
• license clarifies how we can use this package.
• main: specifies the module that “is” the package (explained later in this chapter).
• scripts: are commands that we can execute via npm run. For example, the script
test can be executed via npm run test.
• /tmp/a/b/node_modules
• /tmp/a/node_modules
• /tmp/node_modules
When installing a package some-pkg, npm uses the closest node_modules. If, for example,
we are inside /tmp/a/b/ and there is a node_modules in that directory, then npm puts the
package inside the directory:
/tmp/a/b/node_modules/some-pkg/
29.11 Naming modules 289
When importing a module, we can use a special module specifier to tell Node.js that we
want to import it from an installed package. How exactly that works, is explained later.
For now, consider the following example:
// /home/jane/proj/main.mjs
import * as theModule from 'the-package/the-module.mjs';
To find the-module.mjs (Node.js prefers the filename extension .mjs for ES modules),
Node.js walks up the node_module chain and searches the following locations:
• /home/jane/proj/node_modules/the-package/the-module.mjs
• /home/jane/node_modules/the-package/the-module.mjs
• /home/node_modules/the-package/the-module.mjs
That is enabled via bundling tools, such as webpack, that compile and optimize code be-
fore it is deployed online. During this compilation process, the code in npm packages is
adapted so that it works in browsers.
• The names of module files are dash-cased and start with lowercase letters:
./my-module.mjs
./some-func.mjs
• npm doesn’t allow uppercase letters in package names (source). Thus, we avoid
camel case, so that “local” files have names that are consistent with those of npm
packages. Using only lowercase letters also minimizes conflicts between file systems
that are case-sensitive and file systems that aren’t: the former distinguish files whose
names have the same letters, but with different cases; the latter don’t.
• There are clear rules for translating dash-cased file names to camel-cased JavaScript
variable names. Due to how we name namespace imports, these rules work for both
namespace imports and default imports.
290 29 Modules [ES6]
I also like underscore-cased module file names because we can directly use these names
for namespace imports (without any translation):
But that style does not work for default imports: I like underscore-casing for namespace
objects, but it is not a good choice for functions, etc.
'./some/other/module.mjs'
'../../lib/counter.mjs'
'/home/jane/file-tools.mjs'
'https://example.com/some-module.mjs'
'file:///home/john/tmp/main.mjs'
• Bare path: does not start with a dot, a slash or a protocol, and consists of a single
filename without an extension. Examples:
'lodash'
'the-package'
• Deep import path: starts with a bare path and has at least one slash. Example:
'the-package/dist/the-module.mjs'
• Relative paths, absolute paths, and URLs work as expected. They all must point
to real files (in contrast to CommonJS, which lets us omit filename extensions and
more).
• The file name extensions of modules don’t matter, as long as they are served with
the content type text/javascript.
• How bare paths will end up being handled is not yet clear. We will probably even-
tually be able to map them to other specifiers via lookup tables.
29.12 Module specifiers 291
Note that bundling tools such as webpack, which combine modules into fewer files, are of-
ten less strict with specifiers than browsers. That’s because they operate at build/compile
time (not at runtime) and can search for files by traversing the file system.
• Relative paths are resolved as they are in web browsers – relative to the path of the
current module.
• Absolute paths are currently not supported. As a workaround, we can use URLs
that start with file:///. We can create such URLs via url.pathToFileURL().
• A bare path is interpreted as a package name and resolved relative to the closest
node_modules directory. What module should be loaded, is determined by looking
at property "main" of the package’s package.json (similarly to CommonJS).
• Deep import paths are also resolved relatively to the closest node_modules directory.
They contain file names, so it is always clear which module is meant.
All specifiers, except bare paths, must refer to actual files. That is, ESM does not support
the following CommonJS features:
All built-in Node.js modules are available via bare paths and have named ESM exports –
for example:
assert.equal(
path.join('a/b/c', '../d'), 'a/b/d');
The filename extension .js stands for either ESM or CommonJS. Which one it is is con-
figured via the “closest” package.json (in the current directory, the parent directory, etc.).
Using package.json in this manner is independent of packages.
• "commonjs" (the default): files with the extension .js or without an extension are
interpreted as CommonJS modules.
• "module": files with the extension .js or without an extension are interpreted as
ESM modules.
Not all source code executed by Node.js comes from files. We can also send it code via
stdin, --eval, and --print. The command line option --input-type lets us specify how
such code is interpreted:
29.13.1 import.meta.url
The most important property of import.meta is .url which contains a string with the URL
of the current module’s file – for example:
'https://example.com/code/main.mjs'
Parameter input contains the URL to be parsed. It can be relative if the second parameter,
base, is provided.
In other words, this constructor lets us resolve a relative path against a base URL:
This is how we get a URL instance that points to a file data.txt that sits next to the current
module:
'file:///Users/rauschma/my-module.mjs'
Many Node.js file system operations accept either strings with paths or instances of URL.
That enables us to read a sibling file data.txt of the current module:
For most functions of the module fs, we can refer to files via:
For more information on this topic, see the Node.js API documentation.
The Node.js module url has two functions for converting between file: URLs and paths:
If we need a path that can be used in the local file system, then property .pathname of URL
instances does not always work:
assert.equal(
new URL('file:///tmp/with%20space.txt').pathname,
'/tmp/with%20space.txt');
Similarly, pathToFileURL() does more than just prepend 'file://' to an absolute path.
294 29 Modules [ES6]
• We must use it at the top level of a module. That is, we can’t, for example, import
something when we are inside a function or inside an if statement.
• The module specifier is always fixed. That is, we can’t change what we import de-
pending on a condition. And we can’t assemble a specifier dynamically.
import(moduleSpecifierStr)
.then((namespaceObject) => {
console.log(namespaceObject.namedExport);
});
This operator is used like a function, receives a string with a module specifier and returns
a Promise that resolves to a namespace object. The properties of that object are the exports
of the imported module.
Note that await can be used at the top levels of modules (see next section).
lib/my-math.mjs
main1.mjs
main2.mjs
// main1.mjs
const moduleSpecifier = './lib/my-math.mjs';
function mathOnDemand() {
return import(moduleSpecifier)
.then(myMath => {
const result = myMath.LIGHTSPEED;
assert.equal(result, 299792458);
return result;
});
}
await mathOnDemand()
.then((result) => {
assert.equal(result, 299792458);
});
Next, we’ll implement the same functionality as in main1.mjs but via a feature called async
function or async/await which provides nicer syntax for Promises.
// main2.mjs
const moduleSpecifier = './lib/my-math.mjs';
Some functionality of web apps doesn’t have to be present when they start, it can be loaded
on demand. Then import() helps because we can put such functionality into modules –
for example:
We may want to load a module depending on whether a condition is true. For example, a
module with a polyfill that makes a new feature available on legacy platforms:
if (isLegacyPlatform()) {
import('./my-polyfill.mjs')
.then(···);
}
import(`messages_${getLocale()}.mjs`)
.then(···);
29.15 Top-level await in modules [ES2022] (advanced) 297
We can use the await operator at the top level of a module. If we do that, the module
becomes asynchronous and works differently. Thankfully, we don’t usually see that as
programmers because it is handled transparently by the language.
console.log(messages.welcome);
let mylib;
try {
mylib = await import('https://primary.example.com/mylib');
} catch {
mylib = await import('https://secondary.example.com/mylib');
}
first.mjs:
main.mjs:
main.mjs:
Each asynchronous module exports a Promise (line A and line B) that is fulfilled after its
body was executed. At that point, it is safe to access the exports of that module.
In case (2), the importing module waits until the Promises of all imported asynchronous
modules are fulfilled, before it enters its body (line C). Synchronous modules are handled
as usually.
• It ensures that modules don’t access asynchronous imports before they are fully ini-
tialized.
• It handles asynchronicity transparently: Importers do not need to know if an im-
ported module is asynchronous or not.
29.16 Polyfills: emulating native web platform features (advanced) 299
On the downside, top-level await delays the initialization of importing modules. There-
fore, it’s best used sparingly. Asynchronous tasks that take longer are better performed
later, on demand.
However, even modules without top-level await can block importers (e.g. via an infinite
loop at the top level), so blocking per se is not an argument against it.
Polyfills help with a conflict that we are facing when developing a web application in
JavaScript:
• On one hand, we want to use modern web platform features that make the app
better and/or development easier.
• On the other hand, the app should run on as many browsers as possible.
• A speculative polyfill is a polyfill for a proposed web platform feature (that is not
standardized, yet).
• A replica of X is a library that reproduces the API and functionality of X locally. Such
a library exists independently of a native (and global) implementation of X.
• There is also the term shim, but it doesn’t have a universally agreed upon definition.
It often means roughly the same as polyfill.
Every time our web applications starts, it must first execute all polyfills for features that
may not be available everywhere. Afterwards, we can be sure that those features are avail-
able natively.
300 29 Modules [ES6]
Objects
301
302 30 Objects
1. Single objects (this chapter): How do objects, JavaScript’s basic OOP building blocks,
work in isolation?
2. Prototype chains (this chapter): Each object has a chain of zero or more prototype
objects. Prototypes are JavaScript’s core inheritance mechanism.
3. Classes (next chapter): JavaScript’s classes are factories for objects. The relationship
between a class and its instances is based on prototypal inheritance (step 2).
4. Subclassing (next chapter): The relationship between a subclass and its superclass is
30.1 Cheat sheet: objects 303
SuperClass
superData
superMthd
mthd ƒ
MyClass SubClass
mthd ƒ __proto__ data subData
data 4 data 4 mthd subMthd
Figure 30.1: This book introduces object-oriented programming in JavaScript in four steps.
assert.equal(
myObject.myProperty, 1
);
assert.equal(
myObject.myMethod(), 2
);
assert.equal(
myObject.myAccessor, 1
);
myObject.myAccessor = 3;
assert.equal(
myObject.myProperty, 3
);
304 30 Objects
Being able to create objects directly (without classes) is one of the highlights of JavaScript.
const original = {
a: 1,
b: {
c: 3,
},
};
assert.deepEqual(
modifiedCopy,
{
a: 1,
b: {
c: 3,
},
d: 4,
}
);
Notes:
The most important use case for prototypes is that several objects can share methods by
inheriting them from a common prototype.
• Fixed-layout objects: Used this way, objects work like records in databases. They
have a fixed number of properties, whose keys are known at development time.
Their values generally have different types.
const fixedLayoutObject = {
product: 'carrot',
quantity: 4,
};
• Dictionary objects: Used this way, objects work like lookup tables or maps. They
have a variable number of properties, whose keys are not known at development
time. All of their values have the same type.
const dictionaryObject = {
['one']: 1,
['two']: 2,
};
Note that the two ways can also be mixed: Some objects are both fixed-layout objects and
dictionary objects.
The ways of using objects influence how they are explained in this chapter:
• First, we’ll explore fixed-layout objects. Even though property keys are strings or
symbols under the hood, they will appear as fixed identifiers to us.
• Later, we’ll explore dictionary objects. Note that Maps are usually better dictionaries
than objects. However, some of the operations that we’ll encounter are also useful
for fixed-layout objects.
const jane = {
first: 'Jane',
last: 'Doe', // optional trailing comma
};
In the example, we created an object via an object literal, which starts and ends with curly
braces {}. Inside it, we defined two properties (key-value entries):
• The first property has the key first and the value 'Jane'.
• The second property has the key last and the value 'Doe'.
30.3 Fixed-layout objects 307
We will later see other ways of specifying property keys, but with this way of specifying
them, they must follow the rules of JavaScript variable names. For example, we can use
first_name as a property key, but not first-name). However, reserved words are allowed:
const obj = {
if: true,
const: true,
};
In order to check the effects of various operations on objects, we’ll occasionally use Ob-
ject.keys() in this part of the chapter. It lists property keys:
function createPoint(x, y) {
return {x, y}; // Same as: {x: x, y: y}
}
assert.deepEqual(
createPoint(9, 2),
{ x: 9, y: 2 }
);
const jane = {
first: 'Jane',
last: 'Doe',
};
assert.equal(jane.unknownProperty, undefined);
const obj = {
prop: 1,
};
308 30 Objects
assert.equal(obj.prop, 1);
obj.prop = 2; // (A)
assert.equal(obj.prop, 2);
We just changed an existing property via setting. If we set an unknown property, we create
a new entry:
obj.unknownProperty = 'abc';
assert.deepEqual(
Object.keys(obj), ['unknownProperty']);
const jane = {
first: 'Jane', // value property
says(text) { // method
return `${this.first} says “${text}”`; // (A)
}, // comma as separator (optional at end)
};
assert.equal(jane.says('hello'), 'Jane says “hello”');
During the method call jane.says('hello'), jane is called the receiver of the method call
and assigned to the special variable this (more on this in “Methods and the special vari-
able this” (§30.5)). That enables method .says() to access the sibling property .first in
line A.
Getters
const jane = {
first: 'Jane',
last: 'Doe',
get full() {
return `${this.first} ${this.last}`;
},
[ES2018]
30.4 Spreading into object literals (...) 309
};
Setters
const jane = {
first: 'Jane',
last: 'Doe',
set full(fullName) {
const parts = fullName.split(' ');
this.first = parts[0];
this.last = parts[1];
},
};
[ES2018]
30.4 Spreading into object literals (...)
Inside an object literal, a spread property adds the properties of another object to the current
one:
> {...undefined}
{}
> {...null}
{}
> {...123}
{}
> {...'abc'}
{ '0': 'a', '1': 'b', '2': 'c' }
> {...['a', 'b']}
{ '0': 'a', '1': 'b' }
Property .length of strings and Arrays is hidden from this kind of operation (it is not enu-
merable; see “Property attributes and property descriptors” (§30.8) for more information).
Spreading includes properties whose keys are symbols (which are ignored by Object.keys(),
Object.values() and Object.entries()):
Caveat – copying is shallow: copy is a fresh object with duplicates of all properties (key-
value entries) of original. But if property values are objects, then those are not copied
themselves; they are shared between original and copy. Let’s look at an example:
The first level of copy is really a copy: If we change any properties at that level, it does not
affect the original:
[ES2018]
30.4 Spreading into object literals (...) 311
copy.a = 2;
assert.deepEqual(
original, { a: 1, b: {prop: true} }); // no change
However, deeper levels are not copied. For example, the value of .b is shared between
original and copy. Changing .b in the copy also changes it in the original.
copy.b.prop = false;
assert.deepEqual(
original, { a: 1, b: {prop: false} });
30.4.2 Use case for spreading: default values for missing properties
If one of the inputs of our code is an object with data, we can make properties optional
by specifying default values that are used if those properties are missing. One technique
for doing so is via an object whose properties contain the default values. In the following
example, that object is DEFAULTS:
The result, the object allData, is created by copying DEFAULTS and overriding its properties
with those of providedData.
But we don’t need an object to specify the default values; we can also specify them inside
the object literal, individually:
With spreading, we can change .alpha non-destructively – we make a copy of obj where
.alpha has a different value:
This expression assigns all properties of source_1 to target, then all properties of source_-
2, etc. At the end, it returns target – for example:
const target = { a: 1 };
assert.deepEqual(
result, { a: 1, b: true, c: 3 });
// target was modified and returned:
assert.equal(result, target);
The use cases for Object.assign() are similar to those for spread properties. In a way, it
spreads destructively.
const jane = {
first: 'Jane',
says(text) {
return `${this.first} says “${text}”`;
30.5 Methods and the special variable this 313
},
};
Why is that? We learned in the chapter on callable values that ordinary functions play
several roles. Method is one of those roles. Therefore, internally, jane roughly looks as
follows.
const jane = {
first: 'Jane',
says: function (text) {
return `${this.first} says “${text}”`;
},
};
const obj = {
someMethod(x, y) {
assert.equal(this, obj); // (A)
assert.equal(x, 'a');
assert.equal(y, 'b');
}
};
obj.someMethod('a', 'b'); // (B)
In line B, obj is the receiver of a method call. It is passed to the function stored in obj.someMethod
via an implicit (hidden) parameter whose name is this (line A).
obj.someMethod('a', 'b')
.call() makes the normally implicit parameter this explicit: When invoking a function
via .call(), the first parameter is this, followed by the regular (explicit) function param-
eters.
As an aside, this means that there are actually two different dot operators:
They are different in that (2) is not just (1) followed by the function call operator (). Instead,
(2) additionally provides a value for this.
const jane = {
first: 'Jane',
says(text) {
return `${this.first} says “${text}”`; // (A)
},
};
Setting this to jane via .bind() is crucial here. Otherwise, func() wouldn’t work properly
because this is used in line A. In the next section, we’ll explore why that is.
In the following example, we fail when we extract method jane.says(), store it in the
variable func, and function-call func.
const jane = {
first: 'Jane',
says(text) {
return `${this.first} says “${text}”`;
},
};
const func = jane.says; // extract the method
assert.throws(
() => func('hello'), // (A)
30.5 Methods and the special variable this 315
{
name: 'TypeError',
message: "Cannot read properties of undefined (reading 'first')",
});
In line A, we are making a normal function call. And in normal function calls, this is
undefined (if strict mode is active, which it almost always is). Line A is therefore equivalent
to:
assert.throws(
() => jane.says.call(undefined, 'hello'), // `this` is undefined!
{
name: 'TypeError',
message: "Cannot read properties of undefined (reading 'first')",
}
);
The .bind() ensures that this is always jane when we call func().
The following is a simplified version of code that we may see in actual web development:
class ClickHandler {
constructor(id, elem) {
this.id = id;
elem.addEventListener('click', this.handleClick); // (A)
}
handleClick(event) {
alert('Clicked ' + this.id);
}
}
In line A, we don’t extract the method .handleClick() properly. Instead, we should do:
// Later, possibly:
elem.removeEventListener('click', listener);
Each invocation of .bind() creates a new function. That’s why we need to store the result
somewhere if we want to remove it later on.
316 30 Objects
Alas, there is no simple way around the pitfall of extracting methods: Whenever we extract
a method, we have to be careful and do it properly – for example, by binding this or by
using an arrow function.
Consider the following problem: when we are inside an ordinary function, we can’t access
the this of the surrounding scope because the ordinary function has its own this. In
other words, a variable in an inner scope hides a variable in an outer scope. That is called
shadowing. The following code is an example:
const prefixer = {
prefix: '==> ',
prefixStringArray(stringArray) {
return stringArray.map(
function (x) {
return this.prefix + x; // (A)
});
},
};
assert.throws(
() => prefixer.prefixStringArray(['a', 'b']),
{
name: 'TypeError',
message: "Cannot read properties of undefined (reading 'prefix')",
}
);
In line A, we want to access the this of .prefixStringArray(). But we can’t since the
surrounding ordinary function has its own this that shadows (and blocks access to) the
this of the method. The value of the former this is undefined due to the callback being
function-called. That explains the error message.
The simplest way to fix this problem is via an arrow function, which doesn’t have its own
this and therefore doesn’t shadow anything:
const prefixer = {
prefix: '==> ',
30.5 Methods and the special variable this 317
prefixStringArray(stringArray) {
return stringArray.map(
(x) => {
return this.prefix + x;
});
},
};
assert.deepEqual(
prefixer.prefixStringArray(['a', 'b']),
['==> a', '==> b']);
We can also store this in a different variable (line A), so that it doesn’t get shadowed:
prefixStringArray(stringArray) {
const that = this; // (A)
return stringArray.map(
function (x) {
return that.prefix + x;
});
},
Another option is to specify a fixed this for the callback via .bind() (line A):
prefixStringArray(stringArray) {
return stringArray.map(
function (x) {
return this.prefix + x;
}.bind(this)); // (A)
},
Lastly, .map() lets us specify a value for this (line A) that it uses when invoking the call-
back:
prefixStringArray(stringArray) {
return stringArray.map(
function (x) {
return this.prefix + x;
},
this); // (A)
},
• Use arrow functions as anonymous inline functions. They don’t have this as an
implicit parameter and don’t shadow it.
• For named stand-alone function declarations we can either use arrow functions or
function declarations. If we do the latter, we have to make sure this isn’t mentioned
318 30 Objects
in their bodies.
Inside a callable entity, the value of this depends on how the callable entity is invoked
and what kind of callable entity it is:
• Function call:
– Ordinary functions: this === undefined (in strict mode)
– Arrow functions: this is same as in surrounding scope (lexical this)
• Method call: this is receiver of call
• new: this refers to the newly created instance
• If the value before the question mark is neither undefined nor null, then perform
the operation after the question mark.
• Otherwise, return undefined.
Each of the three syntaxes is covered in more detail later. These are a few first examples:
> null?.prop
undefined
> {prop: 1}?.prop
1
> null?.(123)
undefined
30.6 Optional chaining for property getting and method calls [ES2020] (advanced) 319
> String?.(123)
'123'
const persons = [
{
surname: 'Zoe',
address: {
street: {
name: 'Sesame Street',
number: '123',
},
},
},
{
surname: 'Mariner',
},
{
surname: 'Carmen',
address: {
},
},
];
The nullish coalescing operator allows us to use the default value '(no name)' instead of
undefined:
assert.deepEqual(
streetNames, ['Sesame Street', '(no name)', '(no name)']
);
o?.prop
(o !== undefined && o !== null) ? o.prop : undefined
Examples:
assert.equal(undefined?.prop, undefined);
assert.equal(null?.prop, undefined);
assert.equal({prop:1}?.prop, 1);
o?.[«expr»]
(o !== undefined && o !== null) ? o[«expr»] : undefined
Examples:
f?.(arg0, arg1)
(f !== undefined && f !== null) ? f(arg0, arg1) : undefined
Examples:
assert.equal(undefined?.(123), undefined);
assert.equal(null?.(123), undefined);
assert.equal(String?.(123), '123');
Note that this operator produces an error if its left-hand side is not callable:
assert.throws(
() => true?.(123),
TypeError);
Why? The idea is that the operator only tolerates deliberate omissions. An uncallable
value (other than undefined and null) is probably an error and should be reported, rather
than worked around.
30.6 Optional chaining for property getting and method calls [ES2020] (advanced) 321
function invokeM(value) {
return value?.a.b.m(); // (A)
}
const obj = {
a: {
b: {
m() { return 'result' }
}
}
};
assert.equal(
invokeM(obj), 'result'
);
assert.equal(
invokeM(undefined), undefined // (B)
);
This behavior differs from a normal operator where JavaScript always evaluates all operands
before evaluating the operator. It is called short-circuiting. Other short-circuiting operators
are:
• Deeply nested structures are more difficult to manage. For example, refactoring
is harder if there are many sequences of property names: Each one enforces the
structure of multiple objects.
• Being so forgiving when accessing data hides problems that will surface much later
and are then harder to debug. For example, a typo early in a sequence of optional
property names has more negative effects than a normal typo.
With either approach, it is possible to perform checks and to fail early if there are problems.
322 30 Objects
Further reading:
The syntaxes of the following two optional operator are not ideal:
Alas, the less elegant syntax is necessary because distinguishing the ideal syntax (first ex-
pression) from the conditional operator (second expression) is too complicated:
The operator ?. is mainly about its right-hand side: Does property .prop exist? If not, stop
early. Therefore, keeping information about its left-hand side is rarely useful. However,
only having a single “early termination” value does simplify things.
We first look at features of objects that are related to dictionaries but also useful for fixed-
layout objects. This section concludes with tips for actually using objects as dictionaries.
(Spoiler: If possible, it’s better to use Maps.)
const obj = {
mustBeAnIdentifier: 123,
};
// Get property
assert.equal(obj.mustBeAnIdentifier, 123);
// Set property
obj.mustBeAnIdentifier = 'abc';
assert.equal(obj.mustBeAnIdentifier, 'abc');
30.7 Dictionary objects (advanced) 323
As a next step, we’ll go beyond this limitation for property keys: In this subsection, we’ll
use arbitrary fixed strings as keys. In the next subsection, we’ll dynamically compute keys.
First, when creating property keys via object literals, we can quote property keys (with
single or double quotes):
const obj = {
'Can be any string!': 123,
};
Second, when getting or setting properties, we can use square brackets with strings inside
them:
// Get property
assert.equal(obj['Can be any string!'], 123);
// Set property
obj['Can be any string!'] = 'abc';
assert.equal(obj['Can be any string!'], 'abc');
const obj = {
'A nice method'() {
return 'Yes!';
},
};
The syntax of dynamically computed property keys in object literals is inspired by dynam-
ically accessing properties. That is, we can use square brackets to wrap expressions:
const obj = {
['Hello world!']: true,
['p'+'r'+'o'+'p']: 123,
[Symbol.toStringTag]: 'Goodbye', // (A)
};
The main use case for computed keys is having symbols as property keys (line A).
324 30 Objects
Note that the square brackets operator for getting and setting properties works with arbi-
trary expressions:
assert.equal(obj['p'+'r'+'o'+'p'], 123);
assert.equal(obj['==> prop'.slice(4)], 123);
assert.equal(obj[methodKey](), 'Yes!');
For the remainder of this chapter, we’ll mostly use fixed property keys again (because they
are syntactically more convenient). But all features are also available for arbitrary strings
and symbols.
const obj = {
alpha: 'abc',
beta: false,
};
assert.equal(
obj.alpha ? 'exists' : 'does not exist',
'exists');
assert.equal(
obj.unknownKey ? 'exists' : 'does not exist',
'does not exist');
30.7 Dictionary objects (advanced) 325
The previous checks work because obj.alpha is truthy and because reading a missing
property returns undefined (which is falsy).
There is, however, one important caveat: truthiness checks fail if the property exists, but
has a falsy value (undefined, null, false, 0, "", etc.):
assert.equal(
obj.beta ? 'exists' : 'does not exist',
'does not exist'); // should be: 'exists'
const obj = {
myProp: 123,
};
assert.deepEqual(Object.keys(obj), ['myProp']);
delete obj.myProp;
assert.deepEqual(Object.keys(obj), []);
30.7.5 Enumerability
Enumerability is an attribute of a property. Non-enumerable properties are ignored by some
operations – for example, by Object.keys() and when spreading properties. By default,
most properties are enumerable. The next example shows how to change that and how it
affects spreading.
Table 30.1: Standard library methods for listing own (non-inherited) property keys. All of
them return Arrays with strings and/or symbols.
Each of the methods in table 30.1 returns an Array with the own property keys of the
parameter. In the names of the methods, we can see that the following distinction is made:
• A property key can be either a string or a symbol. (Object.keys() is older and does
not yet follow this convention.)
• A property name is a property key whose value is a string.
• A property symbol is a property key whose value is a symbol.
To demonstrate the four operations, we revisit the example from the previous subsection:
const obj = {
enumerableStringKey: 1,
[enumerableSymbolKey]: 2,
}
Object.defineProperties(obj, {
nonEnumStringKey: {
value: 3,
enumerable: false,
},
[nonEnumSymbolKey]: {
value: 4,
enumerable: false,
},
30.7 Dictionary objects (advanced) 327
});
assert.deepEqual(
Object.keys(obj),
['enumerableStringKey']
);
assert.deepEqual(
Object.getOwnPropertyNames(obj),
['enumerableStringKey', 'nonEnumStringKey']
);
assert.deepEqual(
Object.getOwnPropertySymbols(obj),
[enumerableSymbolKey, nonEnumSymbolKey]
);
assert.deepEqual(
Reflect.ownKeys(obj),
[
'enumerableStringKey', 'nonEnumStringKey',
enumerableSymbolKey, nonEnumSymbolKey,
]
);
);
assert.deepEqual(
Object.entries(obj),
[
['lastName', 'Doe'],
]);
function entries(obj) {
return Object.keys(obj)
.map(key => [key, obj[key]]);
}
Exercise: Object.entries()
exercises/objects/find_key_test.mjs
1. Properties with string keys that contain integer indices (that includes Array indices):
In ascending numeric order
2. Remaining properties with string keys:
In the order in which they were added
3. Properties with symbol keys:
In the order in which they were added
The following example demonstrates that property keys are sorted according to these
rules:
[
['stringKey', 1],
[symbolKey, 2],
]
),
{
stringKey: 1,
[symbolKey]: 2,
}
);
To demonstrate both, we’ll use them to implement two tool functions from the library
Underscore in the next subsubsections.
Example: pick()
pick(object, ...keys)
It returns a copy of object that has only those properties whose keys are mentioned in the
trailing arguments:
const address = {
street: 'Evergreen Terrace',
number: '742',
city: 'Springfield',
state: 'NT',
zip: '49007',
};
assert.deepEqual(
pick(address, 'street', 'number'),
{
street: 'Evergreen Terrace',
number: '742',
}
);
Example: invert()
invert(object)
It returns a copy of object where the keys and values of all properties are swapped:
assert.deepEqual(
invert({a: 1, b: 2, c: 3}),
{1: 'a', 2: 'b', 3: 'c'}
);
function invert(object) {
const reversedEntries = Object.entries(object)
.map(([key, value]) => [value, key]);
return Object.fromEntries(reversedEntries);
}
function fromEntries(iterable) {
const result = {};
for (const [key, value] of iterable) {
let coercedKey;
if (typeof key === 'string' || typeof key === 'symbol') {
coercedKey = key;
} else {
coercedKey = String(key);
}
result[coercedKey] = value;
}
return result;
}
The first pitfall is that the in operator also finds inherited properties:
We want dict to be treated as empty, but the in operator detects the properties it inherits
from its prototype, Object.prototype.
30.8 Property attributes and property descriptors [ES5] (advanced) 331
The second pitfall is that we can’t use the property key __proto__ because it has special
powers (it sets the prototype of the object):
dict['__proto__'] = 123;
// No property was added to dict:
assert.deepEqual(Object.keys(dict), []);
• If we can, we use Maps. They are the best solution for dictionaries.
• If we can’t, we use a library for objects-as-dictionaries that protects us from making
mistakes.
• If that’s not possible or desired, we use an object without a prototype.
dict['__proto__'] = 123;
assert.deepEqual(Object.keys(dict), ['__proto__']);
• First, a property without a prototype does not inherit any properties (line A).
• Second, in modern JavaScript, __proto__ is implemented via Object.prototype.
That means that it is switched off if Object.prototype is not in the prototype chain.
[ES5]
30.8 Property attributes and property descriptors (ad-
vanced)
Just as objects are composed of properties, properties are composed of attributes. There are
two kinds of properties and they are characterized by their attributes:
• A data property stores data. Its attribute value holds any JavaScript value.
– Methods are data properties whose values are functions.
• An accessor property consists of a getter function and/or a setter function. The former
is stored in the attribute get, the latter in the attribute set.
Additionally, there are attributes that both kinds of properties have. The following table
lists all attributes and their default values.
332 30 Objects
We have already encountered the attributes value, get, and set. The other attributes work
as follows:
When we are using one of the operations for handling property attributes, attributes are
specified via property descriptors: objects where each property represents one attribute. For
example, this is how we read the attributes of a property obj.myProp:
assert.deepEqual(Object.keys(obj), ['myProp']);
assert.deepEqual(Object.keys(obj), []);
const obj = {
myMethod() {},
get myGetter() {},
};
const propDescs = Object.getOwnPropertyDescriptors(obj);
propDescs.myMethod.value = typeof propDescs.myMethod.value;
propDescs.myGetter.get = typeof propDescs.myGetter.get;
assert.deepEqual(
propDescs,
{
myMethod: {
value: 'function',
writable: true,
enumerable: true,
configurable: true
},
myGetter: {
get: 'function',
set: undefined,
enumerable: true,
configurable: true
}
}
);
Further reading
For more information on property attributes and property descriptors, see Deep
JavaScript.
• Freezing seals an object after making all of its properties non-writable. That is, the
object is not extensible, all properties are read-only and there is no way to change
that.
– Apply: Object.freeze(obj)
– Check: Object.isFrozen(obj)
Changing frozen properties only causes an exception in strict mode. In sloppy mode, it
fails silently.
Further reading
For more information on freezing and other ways of locking down objects, see Deep
JavaScript.
In an object literal, we can set the prototype via the special property __proto__:
const proto = {
protoProp: 'a',
};
const obj = {
__proto__: proto,
objProp: 'b',
};
assert.equal(obj.protoProp, 'a');
assert.equal('protoProp' in obj, true);
Given that a prototype object can have a prototype itself, we get a chain of objects – the so-
called prototype chain. Inheritance gives us the impression that we are dealing with single
objects, but we are actually dealing with chains of objects.
Figure 30.2 shows what the prototype chain of obj looks like. Non-inherited properties
...
proto
__proto__
protoProp 'a'
obj
__proto__
objProp 'b'
Figure 30.2: obj starts a chain of objects that continues with proto and other objects.
are called own properties. obj has one own property, .objProp.
> Object.keys(obj)
[ 'one' ]
Read on for another operation that also only considers own properties: setting properties.
const proto = {
protoProp: 'a',
};
const obj = {
__proto__: proto,
objProp: 'b',
};
In the next code snippet, we set the inherited property obj.protoProp (line A). That “changes”
it by creating an own property: When reading obj.protoProp, the own property is found
first and its value overrides the value of the inherited property.
...
proto
__proto__
protoProp 'a'
obj
__proto__
objProp 'b'
protoProp 'x'
Figure 30.3: The own property .protoProp of obj overrides the property inherited from
proto.
30.10 Prototype chains 337
– It can’t be used with all objects (e.g. objects that are not instances of Object).
– The language specification has deprecated it.
• Using __proto__ in object literals to set prototypes is different: It’s a feature of object
literals that has no pitfalls.
• The best time to set the prototype of an object is when we are creating it. We can do
so via __proto__ in an object literal or via:
const obj1 = {
__proto__: proto1,
};
assert.equal(Object.getPrototypeOf(obj1), proto1);
Object.setPrototypeOf(obj2, proto2b);
assert.equal(Object.getPrototypeOf(obj2), proto2b);
So far, “proto is a prototype of obj” always meant “proto is a direct prototype of obj”. But
it can also be used more loosely and mean that proto is in the prototype chain of obj. That
looser relationship can be checked via .isPrototypeOf():
For example:
338 30 Objects
const a = {};
const b = {__proto__: a};
const c = {__proto__: b};
assert.equal(a.isPrototypeOf(b), true);
assert.equal(a.isPrototypeOf(c), true);
assert.equal(c.isPrototypeOf(a), false);
assert.equal(a.isPrototypeOf(a), false);
[ES2022]
30.10.4 Object.hasOwn(): Is a given property own (non-inherited)?
The in operator (line A) checks if an object has a given property. In contrast, Object.hasOwn()
(lines B and C) checks if a property is own.
const proto = {
protoProp: 'protoProp',
};
const obj = {
__proto__: proto,
objProp: 'objProp',
}
assert.equal('protoProp' in obj, true); // (A)
assert.equal(Object.hasOwn(obj, 'protoProp'), false); // (B)
assert.equal(Object.hasOwn(proto, 'protoProp'), true); // (C)
const jane = {
firstName: 'Jane',
describe() {
return 'Person named '+this.firstName;
},
};
const tarzan = {
firstName: 'Tarzan',
describe() {
return 'Person named '+this.firstName;
30.10 Prototype chains 339
},
};
We have two objects that are very similar. Both have two properties whose names are
.firstName and .describe. Additionally, method .describe() is the same. How can we
avoid duplicating that method?
We can move it to an object PersonProto and make that object a prototype of both jane and
tarzan:
const PersonProto = {
describe() {
return 'Person named ' + this.firstName;
},
};
const jane = {
__proto__: PersonProto,
firstName: 'Jane',
};
const tarzan = {
__proto__: PersonProto,
firstName: 'Tarzan',
};
The name of the prototype reflects that both jane and tarzan are persons. Figure 30.4
PersonProto
describe function() {···}
jane tarzan
__proto__ __proto__
firstName 'Jane' firstName 'Tarzan'
Figure 30.4: Objects jane and tarzan share method .describe(), via their common proto-
type PersonProto.
illustrates how the three objects are connected: The objects at the bottom now contain the
properties that are specific to jane and tarzan. The object at the top contains the properties
that are shared between them.
When we make the method call jane.describe(), this points to the receiver of that method
call, jane (in the bottom-left corner of the diagram). That’s why the method still works.
tarzan.describe() works similarly.
Looking ahead to the next chapter on classes – this is how classes are organized internally:
In the following example, we define own properties via the second parameter:
• Object.getPrototypeOf(obj) [ES5]
30.12 Quick reference: Object 341
assert.equal(
Object.getPrototypeOf({__proto__: null}), null
);
assert.equal(
Object.getPrototypeOf({}), Object.prototype
);
assert.equal(
Object.getPrototypeOf(Object.prototype), null
);
Sets the prototype of obj to proto (which must be null or an object) and returns the
former.
– Defines one property in obj, as specified by the property key propKey and the
property descriptor propDesc.
– Returns obj.
– Returns a property descriptor for the own property of obj whose key is prop-
Key. If no such property exists, it returns undefined.
– More information on property descriptors: “Property attributes and property
descriptors” (§30.8)
• Object.getOwnPropertyDescriptors(obj) [ES2017]
– Returns an object with property descriptors, one for each own property of obj.
– More information on property descriptors: “Property attributes and property
descriptors” (§30.8)
• Object.keys(obj) [ES5]
Returns an Array with all own enumerable property keys that are strings.
• Object.getOwnPropertyNames(obj) [ES5]
Returns an Array with all own property keys that are strings (enumerable and non-
enumerable ones).
},
[nonEnumSymbolKey]: {
value: 4, enumerable: false,
},
}
);
assert.deepEqual(
Object.getOwnPropertyNames(obj),
['enumStringKey', 'nonEnumStringKey']
);
• Object.getOwnPropertySymbols(obj) [ES6]
Returns an Array with all own property keys that are symbols (enumerable and
non-enumerable ones).
• Object.values(obj) [ES2017]
Returns an Array with the values of all enumerable own string-keyed properties.
• Object.entries(obj) [ES2017]
const obj = {
a: 1,
b: 2,
[Symbol('myKey')]: 3,
};
assert.deepEqual(
Object.entries(obj),
[
['a', 1],
['b', 2],
// Property with symbol key is ignored
]
);
• Object.fromEntries(keyValueIterable) [ES2019]
– Returns true if obj has an own property whose key is key. If not, it returns
false.
• Object.preventExtensions(obj) [ES5]
• Object.isExtensible(obj) [ES5]
– Related: Object.preventExtensions()
• Object.seal(obj) [ES5]
• Object.isSealed(obj) [ES5]
• Object.freeze(obj) [ES5]
• Object.isFrozen(obj) [ES5]
Assigns all enumerable own string-keyed properties of each of the sources to target
and returns target.
30.12 Quick reference: Object 347
– The callback computeGroupKey returns a group key for each of the items.
– The result of Object.groupBy() is an object where:
* The key of each property is a group key and
* its value is an Array with all items that have that group key.
assert.deepEqual(
Object.groupBy(
['orange', 'apricot', 'banana', 'apple', 'blueberry'],
(str) => str[0] // compute group key
),
{
__proto__: null,
'o': ['orange'],
'a': ['apricot', 'apple'],
'b': ['banana', 'blueberry'],
}
);
> -0 === 0
true
> Object.is(-0, 0)
false
– Considering all NaN values to be equal can be useful – e.g., when searching for
a value in an Array.
– The value -0 is rare and it’s usually best to pretend it is the same as 0.
30.12.6 Object.prototype.*
Object.prototype has the following properties:
348 30 Objects
– Invokes target with the arguments provided by argumentsList and this set
to thisArgument.
– Equivalent to target.apply(thisArgument, argumentsList)
– Similar to Object.defineProperty().
– Returns a boolean indicating whether or not the operation succeeded.
• Reflect.deleteProperty(target, propertyKey)
In sloppy mode, the delete operator returns the same results as this method. But in
strict mode, it throws a TypeError instead of returning false.
The only way to protect properties from deletion is by making them non-config-
urable.
A function that gets properties. The optional parameter receiver is needed if get
reaches a getter (somewhere in the prototype chain). Then it provides the value for
this.
• Reflect.getOwnPropertyDescriptor(target, propertyKey)
30.13 Quick reference: Reflect 349
Same as Object.getOwnPropertyDescriptor().
• Reflect.getPrototypeOf(target)
Same as Object.getPrototypeOf().
• Reflect.has(target, propertyKey)
• Reflect.isExtensible(target)
Same as Object.isExtensible().
• Reflect.ownKeys(target)
• Reflect.preventExtensions(target)
– Similar to Object.preventExtensions().
– Returns a boolean indicating whether or not the operation succeeded.
– Sets properties.
– Returns a boolean indicating whether or not the operation succeeded.
• Reflect.setPrototypeOf(target, proto)
– Same as Object.setPrototypeOf().
– Returns a boolean indicating whether or not the operation succeeded.
• Reflect.ownKeys() lists all own property keys – functionality that isn’t provided
anywhere else.
• Same functionality as Object but different return values: Reflect duplicates the fol-
lowing methods of Object, but its methods return booleans indicating whether the
operation succeeded (where the Object methods return the object that was modi-
fied).
• No exceptions when deleting properties: the delete operator throws in strict mode
if we try to delete a non-configurable own property. Reflect.deleteProperty() re-
turns false in that case.
Chapter 31
Classes [ES6]
351
352 31 Classes [ES6]
1. Single objects (previous chapter): How do objects, JavaScript’s basic OOP building
blocks, work in isolation?
2. Prototype chains (previous chapter): Each object has a chain of zero or more proto-
type objects. Prototypes are JavaScript’s core inheritance mechanism.
3. Classes (this chapter): JavaScript’s classes are factories for objects. The relationship
between a class and its instances is based on prototypal inheritance (step 2).
4. Subclassing (this chapter): The relationship between a subclass and its superclass is
also based on prototypal inheritance.
class Person {
constructor(firstName) { // (A)
this.firstName = firstName; // (B)
31.1 Cheat sheet: classes 353
SuperClass
superData
superMthd
mthd ƒ
MyClass SubClass
mthd ƒ __proto__ data subData
data 4 data 4 mthd subMthd
Figure 31.1: This book introduces object-oriented programming in JavaScript in four steps.
}
describe() { // (C)
return 'Person named ' + this.firstName;
}
}
const tarzan = new Person('Tarzan');
assert.equal(
tarzan.firstName, 'Tarzan'
);
assert.equal(
tarzan.describe(),
'Person named Tarzan'
);
// One property (public slot)
assert.deepEqual(
Reflect.ownKeys(tarzan), ['firstName']
);
Explanations:
class Person {
#firstName; // (A)
constructor(firstName) {
this.#firstName = firstName; // (B)
}
describe() {
return 'Person named ' + this.#firstName;
354 31 Classes [ES6]
}
}
const tarzan = new Person('Tarzan');
assert.equal(
tarzan.describe(),
'Person named Tarzan'
);
// No properties, only a private field
assert.deepEqual(
Reflect.ownKeys(tarzan), []
);
Explanations:
constructor(firstName, title) {
super(firstName); // (A)
this.#title = title;
}
describe() {
return `${super.describe()} (${this.#title})`; // (B)
}
}
The next class demonstrates how to create properties via public fields (line A):
class StringBuilderClass {
string = ''; // (A)
add(str) {
this.string += str;
return this;
}
}
31.2 The essentials of classes 355
JavaScript also supports static members, but external functions and variables are often
preferred.
Note that we don’t need classes to create objects. We can also do so via object literals.
That’s why the singleton pattern isn’t needed in JavaScript and classes are used less than
in many other languages that have them.
class Person {
#firstName; // (A)
constructor(firstName) {
this.#firstName = firstName; // (B)
}
describe() {
return `Person named ${this.#firstName}`;
}
static extractNames(persons) {
return persons.map(person => person.#firstName);
}
}
• .constructor() is a special method that is called after the creation of a new instance.
Inside it, this refers to that instance.
• .#firstName [ES2022] is an instance private field: Such fields are stored in instances.
They are accessed similarly to properties, but their names are separate – they always
356 31 Classes [ES6]
start with hash symbols (#). And they are invisible to the world outside the class:
assert.deepEqual(
Reflect.ownKeys(jane),
[]
);
Before we can initialize .#firstName in the constructor (line B), we need to declare
it by mentioning it in the class body (line A).
assert.equal(
jane.describe(), 'Person named Jane'
);
assert.equal(
tarzan.describe(), 'Person named Tarzan'
);
• .extractName() is a static method. “Static” means that it belongs to the class, not to
instances:
assert.deepEqual(
Person.extractNames([jane, tarzan]),
['Jane', 'Tarzan']
);
class Container {
constructor(value) {
this.value = value;
}
}
const abcContainer = new Container('abc');
assert.equal(
abcContainer.value, 'abc'
);
In contrast to instance private fields, instance properties don’t have to be declared in class
bodies.
The name of a named class expression works similarly to the name of a named function
expression: It can only be accessed inside the body of a class and stays the same, regardless
of what the class is assigned to.
We’ll explore the instanceof operator in more detail later, after we have looked at sub-
classing.
• Public slots (which are are also called properties). For example, methods are public
slots.
• Private slots [ES2022] . For example, private fields are private slots.
These are the most important rules we need to know about properties and private slots:
• In classes, we can use public and private versions of fields, methods, getters and
setters. All of them are slots in objects. Which objects they are placed in depends on
whether the keyword static is used and other factors.
• A getter and a setter that have the same key create a single accessor slot. An Accessor
can also have only a getter or only a setter.
• Properties and private slots are very different – for example:
– They are stored separately.
– Their keys are different. The keys of private slots can’t even be accessed di-
rectly (see “Each private slot has a unique key (a private name)” (§31.2.5.2) later
in this chapter).
– Properties are inherited from prototypes, private slots aren’t.
– Private slots can only be created via classes.
The following class demonstrates the two kinds of slots. Each of its instances has one
private field and one property:
class MyClass {
#instancePrivateField = 1;
358 31 Classes [ES6]
instanceProperty = 2;
getInstanceValues() {
return [
this.#instancePrivateField,
this.instanceProperty,
];
}
}
const inst = new MyClass();
assert.deepEqual(
inst.getInstanceValues(), [1, 2]
);
assert.deepEqual(
Reflect.ownKeys(inst),
['instanceProperty']
);
A private slot really can only be accessed inside the class that declares it. We can’t even
access it from a subclass:
class SuperClass {
#superProp = 'superProp';
}
class SubClass extends SuperClass {
getSuperProp() {
return this.#superProp;
}
}
// SyntaxError: Private field '#superProp'
// must be declared in an enclosing class
Subclassing via extends is explained later in this chapter. How to work around this limi-
tation is explained in “Simulating protected visibility and friend visibility via WeakMaps”
(§31.5.4).
31.2 The essentials of classes 359
Private slots have unique keys that are similar to symbols. Consider the following class
from earlier:
class MyClass {
#instancePrivateField = 1;
instanceProperty = 2;
getInstanceValues() {
return [
this.#instancePrivateField,
this.instanceProperty,
];
}
}
let MyClass;
{ // Scope of the body of the class
const instancePrivateFieldKey = Symbol();
MyClass = class {
__PrivateElements__ = new Map([
[instancePrivateFieldKey, 1],
]);
instanceProperty = 2;
getInstanceValues() {
return [
this.__PrivateElements__.get(instancePrivateFieldKey),
this.instanceProperty,
];
}
}
}
The value of instancePrivateFieldKey is called a private name. We can’t use private names
directly in JavaScript, we can only use them indirectly, via the fixed identifiers of private
fields, private methods, and private accessors. Where the fixed identifiers of public slots
(such as getInstanceValues) are interpreted as string keys, the fixed identifiers of private
slots (such as #instancePrivateField) refer to private names (similarly to how variable
names refer to values).
A callable entity can only access the name of a private slot if it was born inside the scope
where the name was declared. However, it doesn’t lose this ability if it moves somewhere
else later on:
class MyClass {
#privateData = 'hello';
static createGetter() {
return (obj) => obj.#privateData; // (A)
}
}
The arrow function getter was born inside MyClass (line A), but it can still access the
private name #privateData after it left its birth scope (line B).
The same private identifier refers to different private names in different classes
Because the identifiers of private slots aren’t used as keys, using the same identifier in
different classes produces different slots (line A and line C):
class Color {
#name; // (A)
constructor(name) {
this.#name = name; // (B)
}
static getName(obj) {
return obj.#name;
}
}
class Person {
#name; // (C)
constructor(name) {
this.#name = name;
}
}
assert.equal(
Color.getName(new Color('green')), 'green'
);
{
name: 'TypeError',
message: 'Cannot read private member #name from'
+ ' an object whose class did not declare it',
}
);
Even if a subclass uses the same name for a private field, the two names never clash because
they refer to private names (which are always unique). In the following example, .#pri-
vateField in SuperClass does not clash with .#privateField in SubClass, even though
both slots are stored directly in inst:
class SuperClass {
#privateField = 'super';
getSuperPrivateField() {
return this.#privateField;
}
}
class SubClass extends SuperClass {
#privateField = 'sub';
getSubPrivateField() {
return this.#privateField;
}
}
const inst = new SubClass();
assert.equal(
inst.getSuperPrivateField(), 'super'
);
assert.equal(
inst.getSubPrivateField(), 'sub'
);
The in operator can be used to check if a private slot exists (line A):
class Color {
#name;
constructor(name) {
this.#name = name;
}
static check(obj) {
return #name in obj; // (A)
}
}
Private methods. The following code shows that private methods create private slots in
instances:
class C1 {
#priv() {}
static check(obj) {
return #priv in obj;
}
}
assert.equal(C1.check(new C1()), true);
Static private fields. We can also use in for a static private field:
class C2 {
static #priv = 1;
static check(obj) {
return #priv in obj;
}
}
assert.equal(C2.check(C2), true);
assert.equal(C2.check(new C2()), false);
Static private methods. And we can check for the slot of a static private method:
class C3 {
static #priv() {}
static check(obj) {
return #priv in obj;
}
}
assert.equal(C3.check(C3), true);
Using the same private identifier in different classes. In the next example, the two classes
Color and Person both have a slot whose identifier is #name. The in operator distinguishes
them correctly:
class Color {
#name;
constructor(name) {
this.#name = name;
}
static check(obj) {
return #name in obj;
}
}
class Person {
#name;
constructor(name) {
this.#name = name;
}
static check(obj) {
31.2 The essentials of classes 363
• Classes are a common standard for object creation and inheritance that is now widely
supported across libraries and frameworks. This is an improvement compared to
how things were before, when almost every framework had its own inheritance li-
brary.
• They help tools such as IDEs and type checkers with their work and enable new
features there.
• If you come from another language to JavaScript and are used to classes, then you
can get started more quickly.
• JavaScript engines optimize them. That is, code that uses classes is almost always
faster than code that uses a custom inheritance library.
• There is a risk of putting too much functionality in classes (when some of it is often
better put in functions).
• Classes look familiar to programmers coming from other languages, but they work
differently and are used differently (see next subsection). Therefore, there is a risk
of those programmers writing code that doesn’t feel like JavaScript.
• How classes seem to work superficially is quite different from how they actually
work. In other words, there is a disconnect between syntax and semantics. Two
364 31 Classes [ES6]
examples are:
The motivation for the disconnect is backward compatibility. Thankfully, the dis-
connect causes few problems in practice; we are usually OK if we go along with
what classes pretend to be.
This was a first look at classes. We’ll explore more features soon.
class Person {
#firstName;
constructor(firstName) {
this.#firstName = firstName;
}
describe() {
return `Person named ${this.#firstName}`;
}
static extractNames(persons) {
return persons.map(person => person.#firstName);
}
}
The first object created by the class is stored in Person. It has four properties:
31.3 The internals of classes 365
assert.deepEqual(
Reflect.ownKeys(Person),
['length', 'name', 'prototype', 'extractNames']
);
assert.deepEqual(
Reflect.ownKeys(Person.prototype),
['constructor', 'describe']
);
That explains how the instances get their methods: They inherit them from the object Per-
son.prototype.
Person Person.prototype
prototype constructor
extractNames function() {···} describe function() {···}
jane tarzan
__proto__ __proto__
#firstName 'Jane' #firstName 'Tarzan'
Figure 31.2: The class Person has the property .prototype that points to an object that is the
prototype of all instances of Person. The objects jane and tarzan are two such instances.
someObj.__proto__
Object.getPrototypeOf(someObj)
someObj.__proto__ = anotherObj
Object.setPrototypeOf(someObj, anotherObj)
• SomeClass.prototype holds the object that becomes the prototype of all instances of
SomeClass. A better name for .prototype would be .instancePrototype. This prop-
erty is only special because the new operator uses it to set up instances of SomeClass.
class SomeClass {}
const inst = new SomeClass();
assert.equal(
Object.getPrototypeOf(inst), SomeClass.prototype
);
This setup exists due to backward compatibility. But it has two additional benefits.
First, each instance of a class inherits property .constructor. Therefore, given an instance,
we can make “similar” objects via it:
Second, we can get the name of the class that created a given instance:
Understanding both of them will give us important insights into how methods work.
We’ll also need the second way later in this chapter: It will allow us to borrow useful
methods from Object.prototype.
Let’s examine how method calls work with classes. We are revisiting jane from earlier:
class Person {
#firstName;
constructor(firstName) {
this.#firstName = firstName;
}
describe() {
return 'Person named '+this.#firstName;
}
}
const jane = new Person('Jane');
Figure 31.3 has a diagram with jane’s prototype chain. Normal method calls are dispatched
– the method call
jane.describe()
• Dispatch: JavaScript traverses the prototype chain starting with jane to find the
first object that has an own property with the key 'describe': It first looks at jane
and doesn’t find an own property .describe. It continues with jane’s prototype,
Person.prototype and finds an own property describe whose value it returns.
368 31 Classes [ES6]
...
Person.prototype
__proto__
describe function() {···}
jane
__proto__
#firstName 'Jane'
Figure 31.3: The prototype chain of jane starts with jane and continues with Per-
son.prototype.
func.call(jane);
This way of dynamically looking for a method and invoking it is called dynamic dispatch.
Person.prototype.describe.call(jane)
This time, we directly point to the method via Person.prototype.describe and don’t search
for it in the prototype chain. We also specify this differently – via .call().
When are direct method calls useful? Whenever we want to borrow a method from else-
where that a given object doesn’t have – for example:
assert.throws(
() => obj.toString(),
/^TypeError: obj.toString is not a function$/
);
assert.equal(
Object.prototype.toString.call(obj),
'[object Object]'
);
function StringBuilderConstr(initialString) {
this.string = initialString;
}
StringBuilderConstr.prototype.add = function (str) {
this.string += str;
return this;
};
class StringBuilderClass {
constructor(initialString) {
this.string = initialString;
}
add(str) {
this.string += str;
return this;
}
}
const sb = new StringBuilderClass('¡');
sb.add('Hola').add('!');
assert.equal(
sb.string, '¡Hola!'
);
Subclassing is especially tricky with constructor functions. Classes also offer benefits that
go beyond more convenient syntax:
Classes are so compatible with constructor functions that they can even extend them:
function SuperConstructor() {}
class SubClass extends SuperConstructor {}
assert.equal(
new SubClass() instanceof SuperConstructor, true
);
class PublicProtoClass {
constructor(args) {
// (Do something with `args` here.)
}
publicProtoMethod() {
return 'publicProtoMethod';
}
get publicProtoAccessor() {
return 'publicProtoGetter';
}
set publicProtoAccessor(value) {
31.4 Prototype members of classes 371
assert.equal(value, 'publicProtoSetter');
}
}
assert.deepEqual(
Reflect.ownKeys(PublicProtoClass.prototype),
['constructor', 'publicProtoMethod', 'publicProtoAccessor']
);
class PublicProtoClass2 {
// Identifier keys
get accessor() {}
set accessor(value) {}
syncMethod() {}
* syncGeneratorMethod() {}
async asyncMethod() {}
async * asyncGeneratorMethod() {}
// Quoted keys
get 'an accessor'() {}
set 'an accessor'(value) {}
'sync method'() {}
* 'sync generator method'() {}
async 'async method'() {}
async * 'async generator method'() {}
// Computed keys
get [accessorKey]() {}
set [accessorKey](value) {}
[syncMethodKey]() {}
* [syncGenMethodKey]() {}
372 31 Classes [ES6]
async [asyncMethodKey]() {}
async * [asyncGenMethodKey]() {}
}
More information on accessors (defined via getters and/or setters), generators, async meth-
ods, and async generator methods:
On one hand, private methods are stored in slots in instances (line A):
class MyClass {
#privateMethod() {}
static check() {
const inst = new MyClass();
assert.equal(
#privateMethod in inst, true // (A)
);
assert.equal(
#privateMethod in MyClass.prototype, false
);
assert.equal(
#privateMethod in MyClass, false
);
}
}
MyClass.check();
Why are they not stored in .prototype objects? Private slots are not inherited, only prop-
erties are.
On the other hand, private methods are shared between instances – like prototype public
methods:
31.4 Prototype members of classes 373
class MyClass {
#privateMethod() {}
static check() {
const inst1 = new MyClass();
const inst2 = new MyClass();
assert.equal(
inst1.#privateMethod,
inst2.#privateMethod
);
}
}
Due to that and due to their syntax being similar to prototype public methods, they are
covered here.
The following code demonstrates how private methods and accessors work:
class PrivateMethodClass {
#privateMethod() {
return 'privateMethod';
}
get #privateAccessor() {
return 'privateGetter';
}
set #privateAccessor(value) {
assert.equal(value, 'privateSetter');
}
callPrivateMembers() {
assert.equal(this.#privateMethod(), 'privateMethod');
assert.equal(this.#privateAccessor, 'privateGetter');
this.#privateAccessor = 'privateSetter';
}
}
assert.deepEqual(
Reflect.ownKeys(new PrivateMethodClass()), []
);
class PrivateMethodClass2 {
get #accessor() {}
set #accessor(value) {}
#syncMethod() {}
* #syncGeneratorMethod() {}
async #asyncMethod() {}
async * #asyncGeneratorMethod() {}
}
374 31 Classes [ES6]
More information on accessors (defined via getters and/or setters), generators, async meth-
ods, and async generator methods:
class InstPublicClass {
// Instance public field
instancePublicField = 0; // (A)
constructor(value) {
// We don’t need to mention .property elsewhere!
this.property = value; // (B)
}
}
If we create an instance property inside the constructor (line B), we don’t need to “declare”
it elsewhere. As we have already seen, that is different for instance private fields.
Note that instance properties are relatively common in JavaScript; much more so than in,
e.g., Java, where most instance state is private.
In the initializer of a instance public field, this refers to the newly created instance:
class MyClass {
instancePublicField = this;
}
const inst = new MyClass();
assert.equal(
inst.instancePublicField, inst
);
The execution of instance public fields roughly follows these two rules:
• In base classes (classes without superclasses), instance public fields are executed
immediately before the constructor.
• In derived classes (classes with superclasses):
– The superclass sets up its instance slots when super() is called.
– Instance public fields are executed immediately after super().
class SuperClass {
superProp = console.log('superProp');
constructor() {
console.log('super-constructor');
}
}
class SubClass extends SuperClass {
subProp = console.log('subProp');
constructor() {
console.log('BEFORE super()');
super();
console.log('AFTER super()');
}
}
new SubClass();
Output:
BEFORE super()
superProp
super-constructor
subProp
AFTER super()
class InstPrivateClass {
#privateField1 = 'private field 1'; // (A)
#privateField2; // (B) required!
constructor(value) {
this.#privateField2 = value; // (C)
}
/**
* Private fields are not accessible outside the class body.
*/
checkPrivateValues() {
assert.equal(
this.#privateField1, 'private field 1'
);
assert.equal(
this.#privateField2, 'constructor argument'
);
}
}
Note that we can only use .#privateField2 in line C if we declare it in the class body.
The first technique makes a property private by prefixing its name with an underscore.
This doesn’t protect the property in any way; it merely signals to the outside: “You don’t
need to know about this property.”
In the following code, the properties ._counter and ._action are private.
class Countdown {
constructor(counter, action) {
this._counter = counter;
31.5 Instance members of classes [ES2022] 377
this._action = action;
}
dec() {
this._counter--;
if (this._counter === 0) {
this._action();
}
}
}
With this technique, we don’t get any protection and private names can clash. On the plus
side, it is easy to use.
Private methods work similarly: They are normal methods whose names start with un-
derscores.
class Countdown {
constructor(counter, action) {
_counter.set(this, counter);
_action.set(this, action);
}
dec() {
let counter = _counter.get(this);
counter--;
_counter.set(this, counter);
if (counter === 0) {
_action.get(this)();
}
}
}
This technique offers us considerable protection from outside access and there can’t be any
378 31 Classes [ES6]
We control the visibility of the pseudo-property _superProp by controlling who has access
to it – for example: If the variable exists inside a module and isn’t exported, everyone
inside the module and no one outside the module can access it. In other words: The scope
of privacy isn’t the class in this case, it’s the module. We could narrow the scope, though:
let Countdown;
{ // class scope
const _counter = new WeakMap();
const _action = new WeakMap();
Countdown = class {
// ···
}
}
This technique doesn’t really support private methods. But module-local functions that
have access to _superProp are the next best thing:
class Countdown {
constructor(counter, action) {
_counter.set(this, counter);
_action.set(this, action);
}
dec() {
privateDec(this);
}
}
Note that this becomes the explicit function parameter _this (line A).
• Protected visibility: A class and all of its subclasses can access a piece instance data.
31.6 Static members of classes 379
• Friend visibility: A class and its “friends” (designated functions, objects, or classes)
can access a piece of instance data.
• If we put a class and its subclasses into the same module, we get protected visibility.
• If we put a class and its friends into the same module, we get friend visibility.
class StaticPublicMethodsClass {
static staticMethod() {
return 'staticMethod';
}
static get staticAccessor() {
return 'staticGetter';
}
static set staticAccessor(value) {
assert.equal(value, 'staticSetter');
}
}
assert.equal(
StaticPublicMethodsClass.staticMethod(), 'staticMethod'
);
assert.equal(
380 31 Classes [ES6]
StaticPublicMethodsClass.staticAccessor, 'staticGetter'
);
StaticPublicMethodsClass.staticAccessor = 'staticSetter';
class StaticPublicMethodsClass2 {
// Identifier keys
static get accessor() {}
static set accessor(value) {}
static syncMethod() {}
static * syncGeneratorMethod() {}
static async asyncMethod() {}
static async * asyncGeneratorMethod() {}
// Quoted keys
static get 'an accessor'() {}
static set 'an accessor'(value) {}
static 'sync method'() {}
static * 'sync generator method'() {}
static async 'async method'() {}
static async * 'async generator method'() {}
// Computed keys
static get [accessorKey]() {}
static set [accessorKey](value) {}
static [syncMethodKey]() {}
static * [syncGenMethodKey]() {}
static async [asyncMethodKey]() {}
static async * [asyncGenMethodKey]() {}
}
More information on accessors (defined via getters and/or setters), generators, async meth-
ods, and async generator methods:
31.6 Static members of classes 381
assert.deepEqual(
Reflect.ownKeys(StaticPublicFieldClass),
[
'length', // number of constructor parameters
'name', // 'StaticPublicFieldClass'
'prototype',
'identifierFieldKey',
'quoted field key',
computedFieldKey,
],
);
assert.equal(StaticPublicFieldClass.identifierFieldKey, 1);
assert.equal(StaticPublicFieldClass['quoted field key'], 2);
assert.equal(StaticPublicFieldClass[computedFieldKey], 3);
class StaticPrivateClass {
// Declare and initialize
static #staticPrivateField = 'hello'; // (A)
static #twice() { // (B)
const str = StaticPrivateClass.#staticPrivateField;
return str + ' ' + str;
}
static getResultOfTwice() {
return StaticPrivateClass.#twice();
}
}
382 31 Classes [ES6]
assert.deepEqual(
Reflect.ownKeys(StaticPrivateClass),
[
'length', // number of constructor parameters
'name', // 'StaticPublicFieldClass'
'prototype',
'getResultOfTwice',
],
);
assert.equal(
StaticPrivateClass.getResultOfTwice(),
'hello hello'
);
class MyClass {
static #staticPrivateMethod() {}
static * #staticPrivateGeneratorMethod() {}
• Static fields
• Static blocks that are executed when a class is created
class Translator {
static translations = {
yes: 'ja',
no: 'nein',
maybe: 'vielleicht',
};
static englishWords = [];
static germanWords = [];
static { // (A)
for (const [english, german] of Object.entries(this.translations)) {
31.6 Static members of classes 383
this.englishWords.push(english);
this.germanWords.push(german);
}
}
}
We could also execute the code inside the static block after the class (at the top level).
However, using a static block has two benefits:
The rules for how static initialization blocks work, are relatively simple:
class SuperClass {
static superField1 = console.log('superField1');
static {
assert.equal(this, SuperClass);
console.log('static block 1 SuperClass');
}
static superField2 = console.log('superField2');
static {
console.log('static block 2 SuperClass');
}
}
Output:
superField1
static block 1 SuperClass
384 31 Classes [ES6]
superField2
static block 2 SuperClass
subField1
static block 1 SubClass
subField2
static block 2 SubClass
class SuperClass {
static publicData = 1;
static getPublicViaThis() {
return this.publicData;
}
}
class SubClass extends SuperClass {
}
assert.equal(SuperClass.getPublicViaThis(), 1);
then this points to SuperClass and everything works as expected. We can also invoke
.getPublicViaThis() via the subclass:
assert.equal(SubClass.getPublicViaThis(), 1);
SubClass inherits .getPublicViaThis() from its prototype SuperClass. this points to Sub-
Class and things continue to work, because SubClass also inherits the property .public-
Data.
class SuperClass {
static #privateData = 2;
static getPrivateDataViaThis() {
31.6 Static members of classes 385
return this.#privateData;
}
static getPrivateDataViaClassName() {
return SuperClass.#privateData;
}
}
class SubClass extends SuperClass {
}
assert.equal(SuperClass.getPrivateDataViaThis(), 2);
However, invoking .getPrivateDataViaThis() via SubClass does not work, because this
now points to SubClass and SubClass has no static private field .#privateData (private
slots in prototype chains are not inherited):
assert.throws(
() => SubClass.getPrivateDataViaThis(),
{
name: 'TypeError',
message: 'Cannot read private member #privateData from'
+ ' an object whose class did not declare it',
}
);
assert.equal(SubClass.getPrivateDataViaClassName(), 2);
31.6.6 All members (static, prototype, instance) can access all private
members
Every member inside a class can access all other members inside that class – both public
and private ones:
class DemoClass {
static #staticPrivateField = 1;
#instPrivField = 2;
static staticMethod(inst) {
// A static method can access static private fields
// and instance private fields
assert.equal(DemoClass.#staticPrivateField, 1);
assert.equal(inst.#instPrivField, 2);
}
protoMethod() {
// A prototype method can access instance private fields
386 31 Classes [ES6]
class StaticClass {
static #secret = 'Rumpelstiltskin';
static #getSecretInParens() {
return `(${StaticClass.#secret})`;
}
static callStaticPrivateMethod() {
return StaticClass.#getSecretInParens();
}
}
Since private slots only exist once per class, we can move #secret and #getSecretInParens
to the scope surrounding the class and use a module to hide them from the world outside
the module.
class Point {
static fromPolar(radius, angle) {
const x = radius * Math.cos(angle);
const y = radius * Math.sin(angle);
return new Point(x, y);
}
constructor(x=0, y=0) {
this.x = x;
this.y = y;
}
}
assert.deepEqual(
Point.fromPolar(13, 0.39479111969976155),
new Point(12, 5)
);
I like how descriptive static factory methods are: fromPolar describes how an instance is
created. JavaScript’s standard library also has such factory methods – for example:
• Array.from()
• Object.create()
I prefer to either have no static factory methods or only static factory methods. Things to
consider in the latter case:
• One factory method will probably directly call the constructor (but have a descrip-
tive name).
• We need to find a way to prevent the constructor being called from outside.
In the following code, we use a secret token (line A) to prevent the constructor being called
from outside the current module.
31.7 Subclassing
Classes can also extend existing classes. For example, the following class Employee extends
Person:
class Person {
#firstName;
constructor(firstName) {
this.#firstName = firstName;
}
describe() {
return `Person named ${this.#firstName}`;
}
static extractNames(persons) {
return persons.map(person => person.#firstName);
}
}
Inside the .constructor() of a derived class, we must call the super-constructor via su-
per() before we can access this. Why is that?
• Base class A
• Class B extends A.
• Class C extends B.
If we invoke new C(), C’s constructor super-calls B’s constructor which super-calls A’s con-
structor. Instances are always created in base classes, before the constructors of subclasses
add their slots. Therefore, the instance doesn’t exist before we call super() and we can’t
access it via this, yet.
Note that static public slots are inherited. For example, Employee inherits the static method
.extractNames():
Exercise: Subclassing
exercises/classes/color_point_class_test.mjs
Function.prototype Object.prototype
__proto__ __proto__
prototype
Person Person.prototype
__proto__ __proto__
prototype
Employee Employee.prototype
__proto__
jane
Figure 31.4: These are the objects that make up class Person and its subclass, Employee.
The left column is about classes. The right column is about the Employee instance jane and
its prototype chain.
The instance prototype chain starts with jane and continues with Employee.prototype and
Person.prototype. In principle, the prototype chain ends at this point, but we get one more
object: Object.prototype. This prototype provides services to virtually all objects, which
is why it is included here, too:
In the class prototype chain, Employee comes first, Person next. Afterward, the chain con-
tinues with Function.prototype, which is only there because Person is a function and func-
tions need the services of Function.prototype.
x instanceof C
C.prototype.isPrototypeOf(x)
31.7 Subclassing 391
If we go back to figure 31.4, we can confirm that the prototype chain does lead us to the
following correct answers:
Note that instanceof always returns false if its self-hand side is a primitive value:
assert.equal(
{a: 1} instanceof Object, true
);
assert.equal(
['a'] instanceof Object, true
);
assert.equal(
/abc/g instanceof Object, true
);
assert.equal(
new Map() instanceof Object, true
);
class C {}
assert.equal(
new C() instanceof Object, true
);
In the next example, obj1 and obj2 are both objects (line A and line C), but they are not
instances of Object (line B and line D): Object.prototype is not in their prototype chains
because they don’t have any prototypes.
);
Object.prototype is the object that ends most prototype chains. Its prototype is null,
which means it isn’t an instance of Object either:
const p = Object.getPrototypeOf.bind(Object);
null
__proto__
Object.prototype
__proto__
{}
Figure 31.5: The prototype chain of an object created via an object literal starts with that
object, continues with Object.prototype, and ends with null.
31.7 Subclassing 393
Figure 31.5 shows a diagram for this prototype chain. We can see that {} really is an in-
stance of Object – Object.prototype is in its prototype chain.
null
__proto__
Object.prototype
__proto__
Array.prototype
__proto__
[]
Figure 31.6: The prototype chain of an Array has these members: the Array instance, Ar-
ray.prototype, Object.prototype, null.
This prototype chain (visualized in figure 31.6) tells us that an Array object is an instance
of Array and of Object.
Lastly, the prototype chain of an ordinary function tells us that all functions are objects:
The prototype of a base class is Function.prototype which means that it is a function (an
instance of Function):
394 31 Classes [ES6]
class A {}
assert.equal(
Object.getPrototypeOf(A),
Function.prototype
);
assert.equal(
Object.getPrototypeOf(class {}),
Function.prototype
);
class B extends A {}
assert.equal(
Object.getPrototypeOf(B),
A
);
assert.equal(
Object.getPrototypeOf(class extends Object {}),
Object
);
However, as we have seen, even the instances of base classes have Object.prototype in
their prototype chains because it provides services that all objects need.
The idea is as follows: Let’s say we want a class C to inherit from two superclasses S1 and
S2. That would be multiple inheritance, which JavaScript doesn’t support.
31.7 Subclassing 395
Each of these two functions returns a class that extends a given superclass Sup. We create
class C as follows:
We now have a class C that extends the class returned by S2() which extends the class
returned by S1() which extends Object.
We implement a mixin Named adds a property .name and a method .toString() to its su-
perclass:
• The same class can extend a single superclass and zero or more mixins.
• The same mixin can be used by multiple classes.
396 31 Classes [ES6]
• Configuring how objects are converted to primitive values (e.g. by the + operator):
The following methods have default implementations but are often overridden in
subclasses or instances.
– .toString(): Configures how an object is converted to a string.
– .toLocaleString(): A version of .toString() that can be configured in vari-
ous ways via arguments (language, region, etc.).
– .valueOf(): Configures how an object is converted to a non-string primitive
value (often a number).
• Useful methods (with pitfalls – see next subsection):
– .isPrototypeOf(): Is the receiver in the prototype chain of a given object?
– .propertyIsEnumerable(): Does the receiver have an enumerable own prop-
erty with the given key?
• Avoid these features (there are better alternatives):
– .__proto__: Get and set the prototype of the receiver.
* Using this accessor is not recommended. Alternatives:
· Object.getPrototypeOf()
· Object.setPrototypeOf()
– .hasOwnProperty(): Does the receiver have an own property with a given key?
* Using this method is not recommended. Alternative in ES2022 and later:
Object.hasOwn().
Before we take a closer look at each of these features, we’ll learn about an important pit-
fall (and how to work around it): We can’t use the features of Object.prototype with all
objects.
Invoking .hasOwnProperty() on an arbitrary object can fail in two ways. On one hand,
this method isn’t available if an object is not an instance of Object (see “Not all objects are
instances of Object” (§31.7.3)):
() => obj.hasOwnProperty('prop'),
{
name: 'TypeError',
message: 'obj.hasOwnProperty is not a function',
}
);
On the other hand, we can’t use .hasOwnProperty() if an object overrides it with an own
property (line A):
const obj = {
hasOwnProperty: 'yes' // (A)
};
assert.throws(
() => obj.hasOwnProperty('prop'),
{
name: 'TypeError',
message: 'obj.hasOwnProperty is not a function',
}
);
The method invocation in line A is explained in “Dispatched vs. direct method calls”
(§31.3.5).
How does this code work? In line A in the example before the code above, we used the
function method .call() to turn the function hasOwnProperty with one implicit parameter
(this) and one explicit parameter (propName) into a function that has two explicit parame-
ters (obj and propName).
In other words – method .call() invokes the function f referred to by its receiver (this):
• Etc.
We use .bind() to create a version .call() whose this always refers to Object.prototype.hasOwnProperty.
That new version invokes .hasOwnProperty() in the same manner as we did in line A –
which is what we want.
31.8.3 Object.prototype.toString()
By overriding .toString() (in a subclass or an instance), we can configure how objects are
converted to strings:
For converting objects to strings it’s better to use String() because that also works with
undefined and null:
> undefined.toString()
TypeError: Cannot read properties of undefined (reading 'toString')
> null.toString()
TypeError: Cannot read properties of null (reading 'toString')
> String(undefined)
'undefined'
> String(null)
'null'
31.8.4 Object.prototype.toLocaleString()
.toLocaleString() is a version of .toString() that can be configured via a locale and often
additional options. Any class or instance can implement this method. In the standard
library, the following classes do:
• Array.prototype.toLocaleString()
• Number.prototype.toLocaleString()
• Date.prototype.toLocaleString()
• TypedArray.prototype.toLocaleString()
• BigInt.prototype.toLocaleString()
As an example, this is how numbers with decimal fractions are converted to string differ-
ently, depending on locale ('fr' is French, 'en' is English):
31.8 The methods and accessors of Object.prototype (advanced) 399
> 123.45.toLocaleString('fr')
'123,45'
> 123.45.toLocaleString('en')
'123.45'
31.8.5 Object.prototype.valueOf()
By overriding .valueOf() (in a subclass or an instance), we can configure how objects are
converted to non-string values (often numbers):
31.8.6 Object.prototype.isPrototypeOf()
proto.isPrototypeOf(obj) returns true if proto is in the prototype chain of obj and false
otherwise.
const a = {};
const b = {__proto__: a};
const c = {__proto__: b};
assert.equal(a.isPrototypeOf(b), true);
assert.equal(a.isPrototypeOf(c), true);
assert.equal(a.isPrototypeOf(a), false);
assert.equal(c.isPrototypeOf(a), false);
This is how to use this method safely (for details see “Using Object.prototype methods
safely” (§31.8.2)):
const obj = {
// Overrides Object.prototype.isPrototypeOf
isPrototypeOf: true,
};
// Doesn’t work in this case:
assert.throws(
() => obj.isPrototypeOf(Object.prototype),
{
name: 'TypeError',
message: 'obj.isPrototypeOf is not a function',
}
);
// Safe way of using .isPrototypeOf():
assert.equal(
Object.prototype.isPrototypeOf.call(obj, Object.prototype), false
);
400 31 Classes [ES6]
31.8.7 Object.prototype.propertyIsEnumerable()
obj.propertyIsEnumerable(propKey) returns true if obj has an own enumerable property
whose key is propKey and false otherwise.
const proto = {
enumerableProtoProp: true,
};
const obj = {
__proto__: proto,
enumerableObjProp: true,
nonEnumObjProp: true,
};
Object.defineProperty(
obj, 'nonEnumObjProp',
{
enumerable: false,
}
);
assert.equal(
obj.propertyIsEnumerable('enumerableProtoProp'),
false // not an own property
);
assert.equal(
obj.propertyIsEnumerable('enumerableObjProp'),
true
);
assert.equal(
obj.propertyIsEnumerable('nonEnumObjProp'),
false // not enumerable
);
assert.equal(
obj.propertyIsEnumerable('unknownProp'),
false // not a property
);
This is how to use this method safely (for details see “Using Object.prototype methods
safely” (§31.8.2)):
const obj = {
// Overrides Object.prototype.propertyIsEnumerable
propertyIsEnumerable: true,
enumerableProp: 'yes',
};
// Doesn’t work in this case:
assert.throws(
() => obj.propertyIsEnumerable('enumerableProp'),
{
name: 'TypeError',
31.8 The methods and accessors of Object.prototype (advanced) 401
assert.deepEqual(
Object.getOwnPropertyDescriptor(obj, 'enumerableProp'),
{
value: 'yes',
writable: true,
enumerable: true,
configurable: true,
}
);
class Object {
get __proto__() {
return Object.getPrototypeOf(this);
}
set __proto__(other) {
Object.setPrototypeOf(this, other);
}
// ···
}
Since __proto__ is inherited from Object.prototype, we can remove this feature by cre-
ating an object that doesn’t have Object.prototype in its prototype chain (see “Not all
402 31 Classes [ES6]
> '__proto__' in {}
true
> '__proto__' in Object.create(null)
false
31.8.9 Object.prototype.hasOwnProperty()
This is how to use this method safely (for details see “Using Object.prototype methods
safely” (§31.8.2)):
const obj = {
// Overrides Object.prototype.hasOwnProperty
hasOwnProperty: true,
};
// Doesn’t work in this case:
assert.throws(
() => obj.hasOwnProperty('anyPropKey'),
{
name: 'TypeError',
message: 'obj.hasOwnProperty is not a function',
}
);
// Safe way of using .hasOwnProperty():
assert.equal(
Object.prototype.hasOwnProperty.call(obj, 'anyPropKey'), false
);
31.9 FAQ: classes 403
31.9.2 Why the identifier prefix #? Why not declare private fields via
private?
Could private fields be declared via private and use normal identifiers? Let’s examine
what would happen if that were possible:
class MyClass {
private value; // (A)
compare(other) {
return this.value === other.value;
}
}
• Is .value a property?
• Is .value a private field?
At compile time, JavaScript doesn’t know if the declaration in line A applies to other (due
to it being an instance of MyClass) or not. That leaves two options for making the decision:
• With option (1), we can’t use .value as a property, anymore – for any object.
• With option (2), performance is affected negatively.
That’s why the name prefix # was introduced. The decision is now easy: If we use #, we
want to access a private field. If we don’t, we want to access a property.
private works for statically typed languages (such as TypeScript) because they know at
compile time if other is an instance of MyClass and can then treat .value as private or
public.
404 31 Classes [ES6]
Chapter 32
You are reading a preview version of this book. You can either read all chapters online or
you can buy the full version.
405