From 3dc9373475c80f39bd063408934f2b1bea85547e Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Tue, 14 Jan 2020 09:44:35 +0100
Subject: [PATCH 001/242] Remove confusing phrasing
Issue #510
---
11_async.md | 5 ++---
1 file changed, 2 insertions(+), 3 deletions(-)
diff --git a/11_async.md b/11_async.md
index c916ed79a..b184d7a0f 100644
--- a/11_async.md
+++ b/11_async.md
@@ -515,9 +515,8 @@ function request(nest, target, type, content) {
Because promises can be resolved (or rejected) only once, this will
work. The first time `resolve` or `reject` is called determines the
-outcome of the promise, and any further calls, such as the timeout
-arriving after the request finishes or a request coming back after
-another request finished, are ignored.
+outcome of the promise, and further calls caused by a request coming
+back after another request finished are ignored.
{{index recursion}}
From 9ae2daec41ad8256a2cc1ec3b64af597edb971a6 Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Wed, 15 Jan 2020 08:06:59 +0100
Subject: [PATCH 002/242] Fix inconsistency between definition of `request` and
text
Closes #511
---
11_async.md | 4 ++--
html/errata.html | 7 +++++++
2 files changed, 9 insertions(+), 2 deletions(-)
diff --git a/11_async.md b/11_async.md
index b184d7a0f..1076173f2 100644
--- a/11_async.md
+++ b/11_async.md
@@ -525,13 +525,13 @@ recursive function—a regular loop doesn't allow us to stop and wait
for an asynchronous action. The `attempt` function makes a single
attempt to send a request. It also sets a timeout that, if no response
has come back after 250 milliseconds, either starts the next attempt
-or, if this was the fourth attempt, rejects the promise with an
+or, if this was the third attempt, rejects the promise with an
instance of `Timeout` as the reason.
{{index idempotence}}
Retrying every quarter-second and giving up when no response has come
-in after a second is definitely somewhat arbitrary. It is even
+in after three-quarter second is definitely somewhat arbitrary. It is even
possible, if the request did come through but the handler is just
taking a bit longer, for requests to be delivered multiple times.
We'll write our handlers with that problem in mind—duplicate messages
diff --git a/html/errata.html b/html/errata.html
index 00389b522..081e11bc4 100644
--- a/html/errata.html
+++ b/html/errata.html
@@ -58,6 +58,13 @@
Chapter 10
needs it own private scope“, it should say “its own private
scope“.
+
Chapter 11
+
+
Page 189/190Networks are Hard: The text
+under the code that defines request claims the function
+will give up after four attempts and a second. In fact, it gives up
+after three attempts, in three-quarter second.
+
Chapter 14
Page 234 (2nd) Creating Nodes: In the
From 5b6a42408126f945b9ef81a4c2a0e3072caa3b90 Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Thu, 16 Jan 2020 14:55:23 +0100
Subject: [PATCH 003/242] Avoid calling string values objects
---
04_data.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/04_data.md b/04_data.md
index 15b5768bc..52bc92c7e 100644
--- a/04_data.md
+++ b/04_data.md
@@ -189,7 +189,7 @@ advance, so to find the length of an array, you typically write
{{index [function, "as property"], method, string}}
-Both string and array objects contain, in addition to the `length`
+Both string and array values contain, in addition to the `length`
property, a number of properties that hold function values.
```
From 175b28c92e94ea2cdb35e4609747c87d4767f67e Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Sat, 4 Apr 2020 23:03:07 +0200
Subject: [PATCH 004/242] Fix linking of zip files from code/index.html
---
20_node.md | 2 +-
21_skillsharing.md | 2 +-
src/chapter_info.js | 13 +++++++------
3 files changed, 9 insertions(+), 8 deletions(-)
diff --git a/20_node.md b/20_node.md
index 88b8bca38..b85661be3 100644
--- a/20_node.md
+++ b/20_node.md
@@ -1,4 +1,4 @@
-{{meta {code_links: "[\"code/file_server.js\"]"}}}
+{{meta {code_links: ["code/file_server.js"]}}}
# Node.js
diff --git a/21_skillsharing.md b/21_skillsharing.md
index 64718e188..71cac0bda 100644
--- a/21_skillsharing.md
+++ b/21_skillsharing.md
@@ -1,4 +1,4 @@
-{{meta {code_links: "[\"code/skillsharing.zip\"]"}}}
+{{meta {code_links: ["code/skillsharing.zip"]}}}
# Project: Skill-Sharing Website
diff --git a/src/chapter_info.js b/src/chapter_info.js
index 0a08e4036..294570156 100644
--- a/src/chapter_info.js
+++ b/src/chapter_info.js
@@ -23,7 +23,7 @@ for (let file of fs.readdirSync(".").sort()) {
start_code: getStartCode(text, includes),
exercises: [],
include: includes};
- let zip = chapterZipFile(text, chapter);
+ let zip = chapterZipFile(meta, chapter);
let extraLinks = meta.match(/\bcode_links: (\[.*?\])/);
if (extraLinks) extraLinks = JSON.parse(extraLinks[1]);
if (extraLinks || zip)
@@ -180,12 +180,13 @@ function getStartCode(text, includes) {
return snippet;
}
-function chapterZipFile(text, chapter) {
- let spec = text.match(/\n:zip: (\S+)(?: include=(.*))?/);
+function chapterZipFile(meta, chapter) {
+ let spec = meta.match(/\bzip: ("(?:\\.|[^"\\])*")/);
if (!spec) return null;
if (!chapter.start_code) throw new Error("zip but no start code");
+ let data = /(\S+)(?:\s+include=(.*))?/.exec(JSON.parse(spec[1]))
let name = "code/chapter/" + chapter.id + ".zip";
- let files = (chapter.include || []).concat(spec[2] ? JSON.parse(spec[2]) : []);
+ let files = (chapter.include || []).concat(data[2] ? JSON.parse(data[2]) : []);
let exists = fs.existsSync(name) && fs.statSync(name).mtime;
if (exists && files.every(file => fs.statSync("html/" + file).mtime < exists))
return name;
@@ -194,13 +195,13 @@ function chapterZipFile(text, chapter) {
for (let file of files) {
zip.file(chapter.id + "/" + file, fs.readFileSync("html/" + file));
}
- if (spec[1].indexOf("html") != -1) {
+ if (data[1].indexOf("html") != -1) {
let html = chapter.start_code;
if (guessType(html) != "html")
html = prepareHTML("", chapter.include);
zip.file(chapter.id + "/index.html", html);
}
- if (spec[1].indexOf("node") != -1) {
+ if (data[1].indexOf("node") != -1) {
zip.file(chapter.id + "/code/load.js", fs.readFileSync("code/load.js", "utf8"));
let js = chapter.start_code;
if (chapter.include) js = "// load dependencies\nrequire(\"./code/load\")(" + chapter.include.map(JSON.stringify).join(", ") + ");\n\n" + js;
From cfa509f373ce8ba0658a9bca1947a0fae6b70f95 Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Mon, 20 Apr 2020 22:12:18 +0200
Subject: [PATCH 005/242] Add MIT license text
---
code/LICENSE | 19 +++++++++++++++++++
epub/frontmatter.xhtml | 2 +-
html/index.html | 2 +-
pdf/book.tex | 2 +-
4 files changed, 22 insertions(+), 3 deletions(-)
create mode 100644 code/LICENSE
diff --git a/code/LICENSE b/code/LICENSE
new file mode 100644
index 000000000..b03a229d6
--- /dev/null
+++ b/code/LICENSE
@@ -0,0 +1,19 @@
+Copyright (C) 2008-2020 by Marijn Haverbeke
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/epub/frontmatter.xhtml b/epub/frontmatter.xhtml
index 9a80e8a0b..81b48445c 100644
--- a/epub/frontmatter.xhtml
+++ b/epub/frontmatter.xhtml
@@ -15,7 +15,7 @@
a Creative
Commons attribution-noncommercial license. All code in this book
may also be considered licensed under
- an MIT license.
Illustrations by various artists: Cover
and chapter illustrations by Madalina Tantareanu. Pixel art in
diff --git a/html/index.html b/html/index.html
index c7702175a..e10e65d37 100644
--- a/html/index.html
+++ b/html/index.html
@@ -41,7 +41,7 @@
Illustrations by various artists: Cover and chapter illustrations
by Madalina Tantareanu.
diff --git a/pdf/book.tex b/pdf/book.tex
index 1b8dbaa67..7f0ce7ad4 100644
--- a/pdf/book.tex
+++ b/pdf/book.tex
@@ -95,7 +95,7 @@
attribution-noncommercial license
(\url{http://creativecommons.org/licenses/by-nc/3.0/}). All code in
the book may also be considered licensed under an MIT license
- (\url{http://opensource.org/licenses/MIT}).
+ (\url{https://eloquentjavascript.net/code/LICENSE}).
The illustrations are contributed by various artists: Cover and
chapter illustrations by Madalina Tantareanu. Pixel art in Chapters
From 7ce94f406895a01a4c7ddcb5f27cf5e56a091ab3 Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Sun, 24 May 2020 21:38:32 +0200
Subject: [PATCH 006/242] Fix incorrect chapter number in frontmatter
---
epub/frontmatter.xhtml | 2 +-
html/index.html | 2 +-
pdf/book.tex | 2 +-
3 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/epub/frontmatter.xhtml b/epub/frontmatter.xhtml
index 81b48445c..604723fdb 100644
--- a/epub/frontmatter.xhtml
+++ b/epub/frontmatter.xhtml
@@ -23,7 +23,7 @@
diagrams in Chapter 9 generated
with regexper.com by Jeff
Avallone. Village photograph in Chapter 11 by Fabrice Creuzot.
- Game concept for Chapter 15
+ Game concept for Chapter 16
by Thomas Palef.
The third edition was made possible
diff --git a/html/index.html b/html/index.html
index e10e65d37..d7c40cd03 100644
--- a/html/index.html
+++ b/html/index.html
@@ -49,7 +49,7 @@
The third edition was made possible
diff --git a/pdf/book.tex b/pdf/book.tex
index 7f0ce7ad4..cef6062fa 100644
--- a/pdf/book.tex
+++ b/pdf/book.tex
@@ -102,7 +102,7 @@
7 and 16 by Antonio Perdomo Pastor. Regular expression diagrams in
Chapter 9 generated with \href{http://regexper.com}{regexper.com} by
Jeff Avallone. Village photograph in Chapter 11 by Fabrice Creuzot.
- Game concept for Chapter 15 by \href{http://lessmilk.com}{Thomas
+ Game concept for Chapter 16 by \href{http://lessmilk.com}{Thomas
Palef}.
The third edition of Eloquent JavaScript was made possible
From 08f0f2a898f08a172ed78264c3dc2869054c20ad Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Tue, 26 May 2020 10:06:31 +0200
Subject: [PATCH 007/242] Add parens after new expression in Chapter 11
For consistency
---
11_async.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/11_async.md b/11_async.md
index 1076173f2..9ee8bd96b 100644
--- a/11_async.md
+++ b/11_async.md
@@ -747,7 +747,7 @@ function broadcastConnections(nest, name, exceptFor = null) {
}
everywhere(nest => {
- nest.state.connections = new Map;
+ nest.state.connections = new Map();
nest.state.connections.set(nest.name, nest.neighbors);
broadcastConnections(nest, nest.name);
});
From 00cc6ce5c0f16e0fdb4d73f0b9b3a19b3700f00e Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Tue, 26 May 2020 10:07:25 +0200
Subject: [PATCH 008/242] Mark one errata as fixed in the 4th reprint
---
html/errata.html | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/html/errata.html b/html/errata.html
index 081e11bc4..79df33b60 100644
--- a/html/errata.html
+++ b/html/errata.html
@@ -60,7 +60,7 @@
Chapter 10
Chapter 11
-
Page 189/190Networks are Hard: The text
+
Page 189/190 (4th) Networks are Hard: The text
under the code that defines request claims the function
will give up after four attempts and a second. In fact, it gives up
after three attempts, in three-quarter second.
From f6ef8c46539554c00e790cb41e7e6fff31b24484 Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Sun, 14 Jun 2020 18:18:30 +0200
Subject: [PATCH 009/242] Fix misnamed property in Chapter 19
---
19_paint.md | 4 ++--
html/errata.html | 5 +++++
2 files changed, 7 insertions(+), 2 deletions(-)
diff --git a/19_paint.md b/19_paint.md
index 84297e2bf..3bc43f266 100644
--- a/19_paint.md
+++ b/19_paint.md
@@ -183,14 +183,14 @@ number to create an empty array of the given length. The `fill`
method can then be used to fill this array with a given value. These
are used to create an array in which all pixels have the same color.
-{{index "hexadecimal number", "color component", "color field", "fillColor property"}}
+{{index "hexadecimal number", "color component", "color field", "fillStyle property"}}
Colors are stored as strings containing traditional ((CSS)) ((color
code))s made up of a ((hash sign)) (`#`) followed by six hexadecimal (base-16)
digits—two for the ((red)) component, two for the ((green))
component, and two for the ((blue)) component. This is a somewhat
cryptic and inconvenient way to write colors, but it is the format the
-HTML color input field uses, and it can be used in the `fillColor`
+HTML color input field uses, and it can be used in the `fillStyle`
property of a canvas drawing context, so for the ways we'll use colors
in this program, it is practical enough.
diff --git a/html/errata.html b/html/errata.html
index 79df33b60..ff665fb86 100644
--- a/html/errata.html
+++ b/html/errata.html
@@ -85,6 +85,11 @@
Chapter 16
refers to the arrow binding, where it should
say arrowKeys.
+
Chapter 19
+
+
Page 336The State: The text mentions the
+property `fillColor` where it should say `fillStyle` instead.
+
Chapter 20
Page 369 (1st) Directory
From 996c2bc3ad626eb5d9e2eaf8456fa77fef73c4cf Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Thu, 9 Jul 2020 17:40:10 +0200
Subject: [PATCH 010/242] Add a cache-control header to Chapter 21 responses
To work around a Chrome issue where it'd hold up a request in one
tab when another tab was still polling the same URL.
---
21_skillsharing.md | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/21_skillsharing.md b/21_skillsharing.md
index 71cac0bda..d53308d7e 100644
--- a/21_skillsharing.md
+++ b/21_skillsharing.md
@@ -570,7 +570,8 @@ SkillShareServer.prototype.talkResponse = function() {
return {
body: JSON.stringify(talks),
headers: {"Content-Type": "application/json",
- "ETag": `"${this.version}"`}
+ "ETag": `"${this.version}"`,
+ "Cache-Control": "no-store"}
};
};
```
From bdff0df4fcf4e6448de5feff97ddc973aeb59164 Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Thu, 30 Jul 2020 08:12:35 +0200
Subject: [PATCH 011/242] Fix a mistake in the solution to ex. 21.2
---
code/solutions/21_2_comment_field_resets.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/code/solutions/21_2_comment_field_resets.js b/code/solutions/21_2_comment_field_resets.js
index 57bbf1338..2c345d33a 100644
--- a/code/solutions/21_2_comment_field_resets.js
+++ b/code/solutions/21_2_comment_field_resets.js
@@ -56,7 +56,7 @@ class SkillShareApp {
for (let talk of state.talks) {
let cmp = this.talkMap[talk.title];
- if (cmp && cmp.talk.author == talk.author &&
+ if (cmp && cmp.talk.presenter == talk.presenter &&
cmp.talk.summary == talk.summary) {
cmp.syncState(talk);
} else {
From 7896534f94988f244b3dfa853ecbbd0a9378535d Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Wed, 26 Aug 2020 09:08:36 +0200
Subject: [PATCH 012/242] Drop use of 'hottentottententen'
Due to colonial connotations
---
09_regexp.md | 4 ++--
code/solutions/09_1_regexp_golf.js | 4 ++--
2 files changed, 4 insertions(+), 4 deletions(-)
diff --git a/09_regexp.md b/09_regexp.md
index f8f8291f0..75307dc9e 100644
--- a/09_regexp.md
+++ b/09_regexp.md
@@ -1305,8 +1305,8 @@ verify(/.../,
["escape the period"]);
verify(/.../,
- ["hottentottententen"],
- ["no", "hotten totten tenten"]);
+ ["Siebentausenddreihundertzweiundzwanzig"],
+ ["no", "three small words"]);
verify(/.../,
["red platypus", "wobbling nest"],
diff --git a/code/solutions/09_1_regexp_golf.js b/code/solutions/09_1_regexp_golf.js
index 72a6af16a..402450353 100644
--- a/code/solutions/09_1_regexp_golf.js
+++ b/code/solutions/09_1_regexp_golf.js
@@ -21,8 +21,8 @@ verify(/\s[.,:;]/,
["escape the dot"]);
verify(/\w{7}/,
- ["hottentottententen"],
- ["no", "hotten totten tenten"]);
+ ["Siebentausenddreihundertzweiundzwanzig"],
+ ["no", "three small words"]);
verify(/\b[^\We]+\b/i,
["red platypus", "wobbling nest"],
From fe5c717570bcfa9069344d6d764f848df6915735 Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Sat, 5 Sep 2020 11:09:14 +0200
Subject: [PATCH 013/242] Add link to Arabic translation
---
html/index.html | 1 +
1 file changed, 1 insertion(+)
diff --git a/html/index.html b/html/index.html
index d7c40cd03..ac484f5f7 100644
--- a/html/index.html
+++ b/html/index.html
@@ -137,6 +137,7 @@
From f258e5dc9f0d83095df7449c0ef9e8f2ee7be58c Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Thu, 10 Sep 2020 08:20:25 +0200
Subject: [PATCH 014/242] Remove incorrect claim that node lists aren't
iterable
Closes #529
---
14_dom.md | 10 ++--------
html/errata.html | 6 ++++++
2 files changed, 8 insertions(+), 8 deletions(-)
diff --git a/14_dom.md b/14_dom.md
index 0b058553a..50f49cde0 100644
--- a/14_dom.md
+++ b/14_dom.md
@@ -221,8 +221,8 @@ it has found one:
```{sandbox: "homepage"}
function talksAbout(node, string) {
if (node.nodeType == Node.ELEMENT_NODE) {
- for (let i = 0; i < node.childNodes.length; i++) {
- if (talksAbout(node.childNodes[i], string)) {
+ for (let child of node.childNodes) {
+ if (talksAbout(child, string)) {
return true;
}
}
@@ -236,12 +236,6 @@ console.log(talksAbout(document.body, "book"));
// → true
```
-{{index "childNodes property", "array-like object", "Array.from function"}}
-
-Because `childNodes` is not a real array, we cannot loop over it with
-`for`/`of` and have to run over the index range using a regular `for`
-loop or use `Array.from`.
-
{{index "nodeValue property"}}
The `nodeValue` property of a text node holds the string of text that
diff --git a/html/errata.html b/html/errata.html
index ff665fb86..6971d7d64 100644
--- a/html/errata.html
+++ b/html/errata.html
@@ -67,6 +67,12 @@
Chapter 11
Chapter 14
+
Page 231Moving Through the Tree: Below
+the code example, the text claims
+that for/of loops don't work on DOM child
+lists. But in current (even as of the book's release) browsers they
+do.
+
Page 234 (2nd) Creating Nodes: In the
code, “edition” is misspelled as “editon”.
Page 336The State: The text mentions the
-property `fillColor` where it should say `fillStyle` instead.
+property fillColor where it should
+say fillStyle instead.
Chapter 20
From 17d39ddffde507941c4884fef392dae10055d805 Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Fri, 11 Sep 2020 14:05:59 +0200
Subject: [PATCH 016/242] Assign ids even to blocks whose hash is duplicated
To avoid breaking the localStorage backing for the editors, which is keyed
by ID.
---
src/render_html.js | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/src/render_html.js b/src/render_html.js
index 015547b85..21ade2685 100644
--- a/src/render_html.js
+++ b/src/render_html.js
@@ -54,7 +54,10 @@ function maybeSplitInlineCode(html) {
const seenIDs = Object.create(null)
function anchor(token) {
let id = token.hashID
- if (!id || id in seenIDs) return ""
+ if (id in seenIDs) for (let i = 1;; i++) {
+ let ext = id + "_" + i
+ if (!(ext in seenIDs)) { id = ext; break }
+ }
seenIDs[id] = true
return ``
}
From 01e0d2d9a0192e0c3236463ee869715c46fb108f Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Fri, 11 Sep 2020 17:34:14 +0200
Subject: [PATCH 017/242] Mark errata fixed in the 5th print
---
html/errata.html | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/html/errata.html b/html/errata.html
index 5d0b7067a..78dcb77c2 100644
--- a/html/errata.html
+++ b/html/errata.html
@@ -67,7 +67,7 @@
Chapter 11
Chapter 14
-
Page 231Moving Through the Tree: Below
+
Page 231 (5th) Moving Through the Tree: Below
the code example, the text claims
that for/of loops don't work on DOM child
lists. But in current (even as of the book's release) browsers they
@@ -93,7 +93,7 @@
Chapter 16
Chapter 19
-
Page 336The State: The text mentions the
+
Page 336 (5th) The State: The text mentions the
property fillColor where it should
say fillStyle instead.
From 7f07a68efedaf88f55ad8788070272fe312af3dc Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Wed, 28 Oct 2020 14:23:00 +0100
Subject: [PATCH 018/242] Mention year in edition header
---
html/index.html | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/html/index.html b/html/index.html
index ac484f5f7..1b56174d5 100644
--- a/html/index.html
+++ b/html/index.html
@@ -27,7 +27,7 @@
-
Eloquent JavaScript
3rd edition
+
Eloquent JavaScript
3rd edition (2018)
This is a book about JavaScript, programming, and the wonders of
the digital. You can read it online here, or get your own
From c53245263c9425fc7bd9e38a9d7af903bf1f8e9d Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Thu, 29 Oct 2020 22:28:45 +0100
Subject: [PATCH 019/242] Get rid of counter reset in title list
Since it triggers a bug in Firefox 82
Issue #535
---
epub/toc.xhtml.src | 2 +-
html/index.html | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/epub/toc.xhtml.src b/epub/toc.xhtml.src
index dab740725..00a08636d 100644
--- a/epub/toc.xhtml.src
+++ b/epub/toc.xhtml.src
@@ -42,7 +42,7 @@
From eaa1655ecea726f4aa92b6c9ed8f722cc869ffd8 Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Tue, 29 Dec 2020 08:53:08 +0100
Subject: [PATCH 020/242] Remove confusing claim about remainder and bitmasks
in Chapter 15
---
15_event.md | 5 ++---
html/errata.html | 6 ++++++
2 files changed, 8 insertions(+), 3 deletions(-)
diff --git a/15_event.md b/15_event.md
index e25cee793..ce35adb00 100644
--- a/15_event.md
+++ b/15_event.md
@@ -508,9 +508,8 @@ that, we can use the `buttons` property (note the plural), which tells
us about the buttons that are currently held down. When this is zero,
no buttons are down. When buttons are held, its value is the sum of
the codes for those buttons—the left button has code 1, the right
-button 2, and the middle one 4. That way, you can check whether a given
-button is pressed by taking the remainder of the value of `buttons`
-and its code.
+button 2, and the middle one 4. With the left and right buttons held,
+for example, the value of `buttons` will be 3.
Note that the order of these codes is different from the one used by
`button`, where the middle button came before the right one. As
diff --git a/html/errata.html b/html/errata.html
index 78dcb77c2..c38d534e3 100644
--- a/html/errata.html
+++ b/html/errata.html
@@ -78,6 +78,12 @@
Chapter 14
Chapter 15
+
Page 255Mouse Motion: The second
+paragraph on the page claims that you can isolate a button from
+the buttons bitmask with the remainder operator, but that
+doesn't really work (you'd also need a division and a floor, which
+gets too obscure to go into in this chapter).
+
Page 258 (3rd) Load Event: The description of
the beforeunload claims that you just need to return a
string from your event handler. For handlers registered
From 62736e374357ccecddeb7bdb0632569df3b781c7 Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Tue, 9 Feb 2021 15:47:12 +0100
Subject: [PATCH 021/242] Provide international store links on the frontpage
---
html/index.html | 7 +++----
1 file changed, 3 insertions(+), 4 deletions(-)
diff --git a/html/index.html b/html/index.html
index 8e1b606a5..16d4fc3e4 100644
--- a/html/index.html
+++ b/html/index.html
@@ -22,7 +22,7 @@
This is a book about JavaScript, programming, and the wonders of
the digital. You can read it online here, or buy your own
- paperback copy. (Store links: 🇺🇸🇬🇧🇮🇳🇨🇦🇩🇪🇫🇷🇧🇷🇳🇱)
From 3518b1ba75f28776403eccd1de93946f776425b5 Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Wed, 10 Feb 2021 13:25:49 +0100
Subject: [PATCH 023/242] Remove a leftover use of var in Chapter 16
---
16_game.md | 12 ++++++------
html/errata.html | 5 +++++
2 files changed, 11 insertions(+), 6 deletions(-)
diff --git a/16_game.md b/16_game.md
index 3cdeef7b2..e73667980 100644
--- a/16_game.md
+++ b/16_game.md
@@ -847,13 +847,13 @@ and a size) touches a grid element of the given type.
```{includeCode: true}
Level.prototype.touches = function(pos, size, type) {
- var xStart = Math.floor(pos.x);
- var xEnd = Math.ceil(pos.x + size.x);
- var yStart = Math.floor(pos.y);
- var yEnd = Math.ceil(pos.y + size.y);
+ let xStart = Math.floor(pos.x);
+ let xEnd = Math.ceil(pos.x + size.x);
+ let yStart = Math.floor(pos.y);
+ let yEnd = Math.ceil(pos.y + size.y);
- for (var y = yStart; y < yEnd; y++) {
- for (var x = xStart; x < xEnd; x++) {
+ for (let y = yStart; y < yEnd; y++) {
+ for (let x = xStart; x < xEnd; x++) {
let isOutside = x < 0 || x >= this.width ||
y < 0 || y >= this.height;
let here = isOutside ? "wall" : this.rows[y][x];
diff --git a/html/errata.html b/html/errata.html
index c38d534e3..6ff2a6836 100644
--- a/html/errata.html
+++ b/html/errata.html
@@ -93,6 +93,11 @@
Chapter 15
Chapter 16
+
Page 278Motion and Collision: The code
+that defines the touches method unintentionally (though
+harmlessly) used var instead of let to
+define variables.
+
Page 285 (2nd) Pausing the Game: The text
refers to the arrow binding, where it should
say arrowKeys.
From f6cb0451cdaeb23b5a748131ce70fcfdc85ce8cc Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Thu, 4 Mar 2021 14:50:35 +0100
Subject: [PATCH 025/242] Fix inconsistent sentence in Chapter 5
Closes #546
---
06_object.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/06_object.md b/06_object.md
index be462cb38..eea6f8c4a 100644
--- a/06_object.md
+++ b/06_object.md
@@ -603,7 +603,7 @@ I mentioned in [Chapter ?](data#for_of_loop) that a `for`/`of` loop
can loop over several kinds of data structures. This is another case
of polymorphism—such loops expect the data structure to expose a
specific interface, which arrays and strings do. And we can also add
-this interface to your own objects! But before we can do that, we need
+this interface to our own objects! But before we can do that, we need
to know what symbols are.
## Symbols
From b4e5c3b5f59cbbddb40ec54bd23b3620ab2956d3 Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Fri, 19 Mar 2021 09:56:06 +0100
Subject: [PATCH 026/242] Fix misuse of 'phase' wrt to wave functions in
Chapter 16
Closes #547
---
16_game.md | 2 +-
html/errata.html | 4 ++++
2 files changed, 5 insertions(+), 1 deletion(-)
diff --git a/16_game.md b/16_game.md
index e73667980..00f34d05e 100644
--- a/16_game.md
+++ b/16_game.md
@@ -417,7 +417,7 @@ the sine function useful for modeling a wavy motion.
{{index pi}}
To avoid a situation where all coins move up and down synchronously,
-the starting phase of each coin is randomized. The _((phase))_ of
+the starting phase of each coin is randomized. The period of
`Math.sin`'s wave, the width of a wave it produces, is 2π. We multiply
the value returned by `Math.random` by that number to give the coin a
random starting position on the wave.
diff --git a/html/errata.html b/html/errata.html
index 6ff2a6836..e509270b6 100644
--- a/html/errata.html
+++ b/html/errata.html
@@ -93,6 +93,10 @@
Chapter 15
Chapter 16
+
Page 271Actors: Near the bottom of the
+page, the book incorrectly uses the term phase (of a sinus
+wave) where it should say period.
+
Page 278Motion and Collision: The code
that defines the touches method unintentionally (though
harmlessly) used var instead of let to
From 2e1d46a7027de394203aa44abbfddd614c5076b5 Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Sat, 3 Apr 2021 20:24:43 +0200
Subject: [PATCH 027/242] More precise language in Chapter 2 section on 'if'
---
02_program_structure.md | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/02_program_structure.md b/02_program_structure.md
index a2ee7a377..18e78db9f 100644
--- a/02_program_structure.md
+++ b/02_program_structure.md
@@ -461,9 +461,9 @@ if (num < 10) {
The program will first check whether `num` is less than 10. If it is,
it chooses that branch, shows `"Small"`, and is done. If it isn't, it
takes the `else` branch, which itself contains a second `if`. If the
-second condition (`< 100`) holds, that means the number is between 10
-and 100, and `"Medium"` is shown. If it doesn't, the second and last
-`else` branch is chosen.
+second condition (`< 100`) holds, that means the number is at least 10
+but below 100, and `"Medium"` is shown. If it doesn't, the second and
+last `else` branch is chosen.
The schema for this program looks something like this:
From 8599c3059eb23e3994dbef585e2f45d2eb7a77a5 Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Mon, 3 May 2021 10:15:01 +0200
Subject: [PATCH 028/242] Avoid horizontal scrollbar in block comment example
in Chapter 2
---
02_program_structure.md | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/02_program_structure.md b/02_program_structure.md
index 18e78db9f..89ad72485 100644
--- a/02_program_structure.md
+++ b/02_program_structure.md
@@ -872,10 +872,10 @@ information about a file or a chunk of program.
```
/*
- I first found this number scrawled on the back of an old notebook.
- Since then, it has often dropped by, showing up in phone numbers
- and the serial numbers of products that I've bought. It obviously
- likes me, so I've decided to keep it.
+ I first found this number scrawled on the back of an old
+ notebook. Since then, it has often dropped by, showing up in
+ phone numbers and the serial numbers of products that I've
+ bought. It obviously likes me, so I've decided to keep it.
*/
const myNumber = 11213;
```
From 251b1a743d0c42e11fa77d45a965993fe0d4b93b Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Wed, 14 Jul 2021 21:32:42 +0200
Subject: [PATCH 029/242] Mark some errata with reprint numbers
---
html/errata.html | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/html/errata.html b/html/errata.html
index e509270b6..c081bb01c 100644
--- a/html/errata.html
+++ b/html/errata.html
@@ -78,7 +78,7 @@
Chapter 14
Chapter 15
-
Page 255Mouse Motion: The second
+
Page 255 (6th) Mouse Motion: The second
paragraph on the page claims that you can isolate a button from
the buttons bitmask with the remainder operator, but that
doesn't really work (you'd also need a division and a floor, which
@@ -93,11 +93,11 @@
Chapter 15
Chapter 16
-
Page 271Actors: Near the bottom of the
+
Page 271 (7th) Actors: Near the bottom of the
page, the book incorrectly uses the term phase (of a sinus
wave) where it should say period.
-
Page 278Motion and Collision: The code
+
Page 278 (7th) Motion and Collision: The code
that defines the touches method unintentionally (though
harmlessly) used var instead of let to
define variables.
Page 255 (7th) Mouse Motion: The second
paragraph on the page claims that you can isolate a button from
the buttons bitmask with the remainder operator, but that
doesn't really work (you'd also need a division and a floor, which
@@ -93,11 +93,11 @@
Chapter 15
Chapter 16
-
Page 271 (7th) Actors: Near the bottom of the
+
Page 271 (8th) Actors: Near the bottom of the
page, the book incorrectly uses the term phase (of a sinus
wave) where it should say period.
-
Page 278 (7th) Motion and Collision: The code
+
Page 278 (8th) Motion and Collision: The code
that defines the touches method unintentionally (though
harmlessly) used var instead of let to
define variables.
From 9b1dabc843ec32f67d8f7016fbadeff67b71d2fd Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Mon, 4 Oct 2021 10:23:09 +0200
Subject: [PATCH 031/242] Fix incorrect description of request stream in
Chapter 20
Closes https://github.com/marijnh/Eloquent-JavaScript/issues/560
---
20_node.md | 4 ++--
html/errata.html | 4 ++++
2 files changed, 6 insertions(+), 2 deletions(-)
diff --git a/20_node.md b/20_node.md
index b85661be3..4f801aaeb 100644
--- a/20_node.md
+++ b/20_node.md
@@ -994,8 +994,8 @@ outcome of calling `pipe`.
When something goes wrong when opening the file, `createWriteStream`
will still return a stream, but that stream will fire an `"error"`
-event. The output stream to the request may also fail, for example if
-the network goes down. So we wire up both streams' `"error"` events to
+event. The stream from the request may also fail, for example if the
+network goes down. So we wire up both streams' `"error"` events to
reject the promise. When `pipe` is done, it will close the output
stream, which causes it to fire a `"finish"` event. That's the point
where we can successfully resolve the promise (returning nothing).
diff --git a/html/errata.html b/html/errata.html
index adbd5b597..899fd7bf7 100644
--- a/html/errata.html
+++ b/html/errata.html
@@ -114,6 +114,10 @@
Chapter 19
Chapter 20
+
Page 367A File Server: The part that
+talks about “the output stream to the request” should say “the stream
+from the request” instead.
+
Page 369 (1st) Directory
Creation: MKCOL stands for “make collection”, not “make
column” as the book claims.
From dc6dd001e7a91b9bb290be658ec8a2e4fa96d640 Mon Sep 17 00:00:00 2001
From: Vitor
Date: Sun, 16 Jan 2022 17:57:09 +0000
Subject: [PATCH 032/242] fix portuguese book link
Uses the new link to the book in portuguese.
---
html/index.html | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/html/index.html b/html/index.html
index e84ffccc9..02e0d7eff 100644
--- a/html/index.html
+++ b/html/index.html
@@ -139,7 +139,7 @@
From f8f004fd3ac104c7b5abdd76cab5192ee86f5c46 Mon Sep 17 00:00:00 2001
From: Marijn Haverbeke
Date: Thu, 28 Jul 2022 14:17:54 +0200
Subject: [PATCH 038/242] Remove paragraph-internal line breaks
---
00_intro.md | 356 +++--------------
01_values.md | 397 ++++---------------
02_program_structure.md | 532 +++++---------------------
03_functions.md | 521 +++++--------------------
04_data.md | 826 ++++++++--------------------------------
05_higher_order.md | 399 ++++---------------
06_object.md | 584 ++++++----------------------
07_robot.md | 363 ++++--------------
08_error.md | 492 +++++-------------------
09_regexp.md | 674 +++++++-------------------------
10_modules.md | 563 ++++++---------------------
11_async.md | 768 +++++++------------------------------
12_language.md | 393 ++++---------------
13_browser.md | 301 +++------------
14_dom.md | 553 +++++----------------------
15_event.md | 561 ++++++---------------------
16_game.md | 634 ++++++------------------------
17_canvas.md | 686 +++++++--------------------------
18_http.md | 727 +++++++----------------------------
19_paint.md | 610 ++++++-----------------------
20_node.md | 667 ++++++--------------------------
21_skillsharing.md | 460 +++++-----------------
22 files changed, 2290 insertions(+), 9777 deletions(-)
diff --git a/00_intro.md b/00_intro.md
index 380511d79..29b992180 100644
--- a/00_intro.md
+++ b/00_intro.md
@@ -4,151 +4,77 @@
{{quote {author: "Ellen Ullman", title: "Close to the Machine: Technophilia and its Discontents", chapter: true}
-We think we are creating the system for our own purposes. We believe
-we are making it in our own image... But the computer is not really
-like us. It is a projection of a very slim part of ourselves: that
-portion devoted to logic, order, rule, and clarity.
+We think we are creating the system for our own purposes. We believe we are making it in our own image... But the computer is not really like us. It is a projection of a very slim part of ourselves: that portion devoted to logic, order, rule, and clarity.
quote}}
{{figure {url: "img/chapter_picture_00.jpg", alt: "Picture of a screwdriver and a circuit board", chapter: "framed"}}}
-This is a book about instructing ((computer))s. Computers are about as
-common as screwdrivers today, but they are quite a bit more complex,
-and making them do what you want them to do isn't always easy.
+This is a book about instructing ((computer))s. Computers are about as common as screwdrivers today, but they are quite a bit more complex, and making them do what you want them to do isn't always easy.
-If the task you have for your computer is a common, well-understood
-one, such as showing you your email or acting like a calculator, you
-can open the appropriate ((application)) and get to work. But for
-unique or open-ended tasks, there probably is no application.
+If the task you have for your computer is a common, well-understood one, such as showing you your email or acting like a calculator, you can open the appropriate ((application)) and get to work. But for unique or open-ended tasks, there probably is no application.
-That is where ((programming)) may come in. _Programming_ is the act of
-constructing a _program_—a set of precise instructions telling a
-computer what to do. Because computers are dumb, pedantic beasts,
-programming is fundamentally tedious and frustrating.
+That is where ((programming)) may come in. _Programming_ is the act of constructing a _program_—a set of precise instructions telling a computer what to do. Because computers are dumb, pedantic beasts, programming is fundamentally tedious and frustrating.
{{index [programming, "joy of"], speed}}
-Fortunately, if you can get over that fact, and maybe even enjoy the rigor
-of thinking in terms that dumb machines can deal with, programming can
-be rewarding. It allows you to do things in seconds that would take
-_forever_ by hand. It is a way to make your computer tool
-do things that it couldn't do before. And it provides a wonderful
-exercise in abstract thinking.
-
-Most programming is done with ((programming language))s. A _programming
-language_ is an artificially constructed language used to instruct
-computers. It is interesting that the most effective way we've found
-to communicate with a computer borrows so heavily from the way we
-communicate with each other. Like human languages, computer languages
-allow words and phrases to be combined in new ways, making it possible to
-express ever new concepts.
+Fortunately, if you can get over that fact, and maybe even enjoy the rigor of thinking in terms that dumb machines can deal with, programming can be rewarding. It allows you to do things in seconds that would take _forever_ by hand. It is a way to make your computer tool do things that it couldn't do before. And it provides a wonderful exercise in abstract thinking.
+
+Most programming is done with ((programming language))s. A _programming language_ is an artificially constructed language used to instruct computers. It is interesting that the most effective way we've found to communicate with a computer borrows so heavily from the way we communicate with each other. Like human languages, computer languages allow words and phrases to be combined in new ways, making it possible to express ever new concepts.
{{index [JavaScript, "availability of"], "casual computing"}}
-At one point language-based interfaces, such as the BASIC and DOS
-prompts of the 1980s and 1990s, were the main method of interacting with
-computers. They have largely been replaced with visual interfaces,
-which are easier to learn but offer less freedom. Computer languages
-are still there, if you know where to look. One such language,
-JavaScript, is built into every modern web ((browser)) and is thus
-available on almost every device.
+At one point language-based interfaces, such as the BASIC and DOS prompts of the 1980s and 1990s, were the main method of interacting with computers. They have largely been replaced with visual interfaces, which are easier to learn but offer less freedom. Computer languages are still there, if you know where to look. One such language, JavaScript, is built into every modern web ((browser)) and is thus available on almost every device.
{{indexsee "web browser", browser}}
-This book will try to make you familiar enough with this language to
-do useful and amusing things with it.
+This book will try to make you familiar enough with this language to do useful and amusing things with it.
## On programming
{{index [programming, "difficulty of"]}}
-Besides explaining JavaScript, I will introduce the basic
-principles of programming. Programming, it turns out, is hard. The
-fundamental rules are simple and clear, but programs built on top of
-these rules tend to become complex enough to introduce their own rules
-and complexity. You're building your own maze, in a way, and you might
-just get lost in it.
+Besides explaining JavaScript, I will introduce the basic principles of programming. Programming, it turns out, is hard. The fundamental rules are simple and clear, but programs built on top of these rules tend to become complex enough to introduce their own rules and complexity. You're building your own maze, in a way, and you might just get lost in it.
{{index learning}}
-There will be times when reading this book feels terribly frustrating.
-If you are new to programming, there will be a lot of new material to
-digest. Much of this material will then be _combined_ in ways that
-require you to make additional connections.
+There will be times when reading this book feels terribly frustrating. If you are new to programming, there will be a lot of new material to digest. Much of this material will then be _combined_ in ways that require you to make additional connections.
-It is up to you to make the necessary effort. When you are struggling
-to follow the book, do not jump to any conclusions about your own
-capabilities. You are fine—you just need to keep at it. Take a break,
-reread some material, and make sure you read and understand the
-example programs and ((exercises)). Learning is hard work, but
-everything you learn is yours and will make subsequent learning
-easier.
+It is up to you to make the necessary effort. When you are struggling to follow the book, do not jump to any conclusions about your own capabilities. You are fine—you just need to keep at it. Take a break, reread some material, and make sure you read and understand the example programs and ((exercises)). Learning is hard work, but everything you learn is yours and will make subsequent learning easier.
{{quote {author: "Ursula K. Le Guin", title: "The Left Hand of Darkness"}
{{index "Le Guin, Ursula K."}}
-When action grows unprofitable, gather information; when information
-grows unprofitable, sleep.
+When action grows unprofitable, gather information; when information grows unprofitable, sleep.
quote}}
{{index [program, "nature of"], data}}
-A program is many things. It is a piece of text typed by a programmer,
-it is the directing force that makes the computer do what it does, it
-is data in the computer's memory, yet it controls the actions
-performed on this same memory. Analogies that try to compare programs
-to objects we are familiar with tend to fall short. A superficially
-fitting one is that of a machine—lots of separate parts tend to be
-involved, and to make the whole thing tick, we have to consider the
-ways in which these parts interconnect and contribute to the operation
-of the whole.
-
-A ((computer)) is a physical machine that acts as a host for these immaterial
-machines. Computers themselves can do only stupidly straightforward
-things. The reason they are so useful is that they do these things at
-an incredibly high ((speed)). A program can ingeniously combine an
-enormous number of these simple actions to do very
-complicated things.
+A program is many things. It is a piece of text typed by a programmer, it is the directing force that makes the computer do what it does, it is data in the computer's memory, yet it controls the actions performed on this same memory. Analogies that try to compare programs to objects we are familiar with tend to fall short. A superficially fitting one is that of a machine—lots of separate parts tend to be involved, and to make the whole thing tick, we have to consider the ways in which these parts interconnect and contribute to the operation of the whole.
+
+A ((computer)) is a physical machine that acts as a host for these immaterial machines. Computers themselves can do only stupidly straightforward things. The reason they are so useful is that they do these things at an incredibly high ((speed)). A program can ingeniously combine an enormous number of these simple actions to do very complicated things.
{{index [programming, "joy of"]}}
-A program is a building of thought. It is costless to build, it is
-weightless, and it grows easily under our typing hands.
+A program is a building of thought. It is costless to build, it is weightless, and it grows easily under our typing hands.
-But without care, a program's size and ((complexity)) will grow out of
-control, confusing even the person who created it. Keeping programs
-under control is the main problem of programming. When a program
-works, it is beautiful. The art of programming is the skill of
-controlling complexity. The great program is subdued—made simple in
-its complexity.
+But without care, a program's size and ((complexity)) will grow out of control, confusing even the person who created it. Keeping programs under control is the main problem of programming. When a program works, it is beautiful. The art of programming is the skill of controlling complexity. The great program is subdued—made simple in its complexity.
{{index "programming style", "best practices"}}
-Some programmers believe that this complexity is best managed by using
-only a small set of well-understood techniques in their programs. They
-have composed strict rules ("best practices") prescribing the form
-programs should have and carefully stay within their safe little
-zone.
+Some programmers believe that this complexity is best managed by using only a small set of well-understood techniques in their programs. They have composed strict rules ("best practices") prescribing the form programs should have and carefully stay within their safe little zone.
{{index experiment}}
-This is not only boring, it is ineffective. New problems often
-require new solutions. The field of programming is young and still
-developing rapidly, and it is varied enough to have room for wildly
-different approaches. There are many terrible mistakes to make in
-program design, and you should go ahead and make them so that you
-understand them. A sense of what a good program looks like is
-developed in practice, not learned from a list of rules.
+This is not only boring, it is ineffective. New problems often require new solutions. The field of programming is young and still developing rapidly, and it is varied enough to have room for wildly different approaches. There are many terrible mistakes to make in program design, and you should go ahead and make them so that you understand them. A sense of what a good program looks like is developed in practice, not learned from a list of rules.
## Why language matters
{{index "programming language", "machine code", "binary data"}}
-In the beginning, at the birth of computing, there were no programming
-languages. Programs looked something like this:
+In the beginning, at the birth of computing, there were no programming languages. Programs looked something like this:
```{lang: null}
00110001 00000000 00000000
@@ -164,33 +90,21 @@ languages. Programs looked something like this:
{{index [programming, "history of"], "punch card", complexity}}
-That is a program to add the numbers from 1 to 10 together and print
-out the result: `1 + 2 + ... + 10 = 55`. It could run on a simple,
-hypothetical machine. To program early computers, it was necessary to
-set large arrays of switches in the right position or punch holes in
-strips of cardboard and feed them to the computer. You can probably
-imagine how tedious and error-prone this procedure was. Even writing
-simple programs required much cleverness and discipline. Complex ones
-were nearly inconceivable.
+That is a program to add the numbers from 1 to 10 together and print out the result: `1 + 2 + ... + 10 = 55`. It could run on a simple, hypothetical machine. To program early computers, it was necessary to set large arrays of switches in the right position or punch holes in strips of cardboard and feed them to the computer. You can probably imagine how tedious and error-prone this procedure was. Even writing simple programs required much cleverness and discipline. Complex ones were nearly inconceivable.
{{index bit, "wizard (mighty)"}}
-Of course, manually entering these arcane patterns of bits (the ones
-and zeros) did give the programmer a profound sense of being a mighty
-wizard. And that has to be worth something in terms of job
-satisfaction.
+Of course, manually entering these arcane patterns of bits (the ones and zeros) did give the programmer a profound sense of being a mighty wizard. And that has to be worth something in terms of job satisfaction.
{{index memory, instruction}}
-Each line of the previous program contains a single instruction. It
-could be written in English like this:
+Each line of the previous program contains a single instruction. It could be written in English like this:
1. Store the number 0 in memory location 0.
2. Store the number 1 in memory location 1.
3. Store the value of memory location 1 in memory location 2.
4. Subtract the number 11 from the value in memory location 2.
- 5. If the value in memory location 2 is the number 0,
- continue with instruction 9.
+ 5. If the value in memory location 2 is the number 0, continue with instruction 9.
6. Add the value of memory location 1 to memory location 0.
7. Add the number 1 to the value of memory location 1.
8. Continue with instruction 3.
@@ -198,9 +112,7 @@ could be written in English like this:
{{index readability, naming, binding}}
-Although that is already more readable than the soup of bits, it is
-still rather obscure. Using names instead of numbers for the
-instructions and memory locations helps.
+Although that is already more readable than the soup of bits, it is still rather obscure. Using names instead of numbers for the instructions and memory locations helps.
```{lang: "text/plain"}
Set “total” to 0.
@@ -218,19 +130,7 @@ instructions and memory locations helps.
{{index loop, jump, "summing example"}}
-Can you see how the program works at this point? The first two lines
-give two memory locations their starting values: `total` will be used
-to build up the result of the computation, and `count` will keep track
-of the number that we are currently looking at. The lines using
-`compare` are probably the weirdest ones. The program wants to see
-whether `count` is equal to 11 to decide whether it can stop
-running. Because our hypothetical machine is rather primitive, it can
-only test whether a number is zero and make a decision based
-on that. So it uses the memory location labeled `compare` to compute
-the value of `count - 11` and makes a decision based on that value.
-The next two lines add the value of `count` to the result and
-increment `count` by 1 every time the program has decided that `count`
-is not 11 yet.
+Can you see how the program works at this point? The first two lines give two memory locations their starting values: `total` will be used to build up the result of the computation, and `count` will keep track of the number that we are currently looking at. The lines using `compare` are probably the weirdest ones. The program wants to see whether `count` is equal to 11 to decide whether it can stop running. Because our hypothetical machine is rather primitive, it can only test whether a number is zero and make a decision based on that. So it uses the memory location labeled `compare` to compute the value of `count - 11` and makes a decision based on that value. The next two lines add the value of `count` to the result and increment `count` by 1 every time the program has decided that `count` is not 11 yet.
Here is the same program in JavaScript:
@@ -246,27 +146,15 @@ console.log(total);
{{index "while loop", loop, [braces, block]}}
-This version gives us a few more improvements. Most important, there
-is no need to specify the way we want the program to jump back and
-forth anymore. The `while` construct takes care of that. It continues
-executing the block (wrapped in braces) below it as long as the
-condition it was given holds. That condition is `count <= 10`, which
-means “_count_ is less than or equal to 10”. We no longer have to
-create a temporary value and compare that to zero, which was just an
-uninteresting detail. Part of the power of programming languages is
-that they can take care of uninteresting details for us.
+This version gives us a few more improvements. Most important, there is no need to specify the way we want the program to jump back and forth anymore. The `while` construct takes care of that. It continues executing the block (wrapped in braces) below it as long as the condition it was given holds. That condition is `count <= 10`, which means “_count_ is less than or equal to 10”. We no longer have to create a temporary value and compare that to zero, which was just an uninteresting detail. Part of the power of programming languages is that they can take care of uninteresting details for us.
{{index "console.log"}}
-At the end of the program, after the `while` construct has finished,
-the `console.log` operation is used to write out the result.
+At the end of the program, after the `while` construct has finished, the `console.log` operation is used to write out the result.
{{index "sum function", "range function", abstraction, function}}
-Finally, here is what the program could look like if we happened to
-have the convenient operations `range` and `sum` available, which
-respectively create a ((collection)) of numbers within a range and
-compute the sum of a collection of numbers:
+Finally, here is what the program could look like if we happened to have the convenient operations `range` and `sum` available, which respectively create a ((collection)) of numbers within a range and compute the sum of a collection of numbers:
```{startCode: true}
console.log(sum(range(1, 10)));
@@ -275,21 +163,11 @@ console.log(sum(range(1, 10)));
{{index readability}}
-The moral of this story is that the same program can be expressed in
-both long and short, unreadable and readable ways. The first version of the
-program was extremely obscure, whereas this last one is almost
-English: `log` the `sum` of the `range` of numbers from 1 to 10. (We
-will see in [later chapters](data) how to define operations like `sum`
-and `range`.)
+The moral of this story is that the same program can be expressed in both long and short, unreadable and readable ways. The first version of the program was extremely obscure, whereas this last one is almost English: `log` the `sum` of the `range` of numbers from 1 to 10. (We will see in [later chapters](data) how to define operations like `sum` and `range`.)
{{index ["programming language", "power of"], composability}}
-A good programming language helps the programmer by allowing them to
-talk about the actions that the computer has to perform on a higher
-level. It helps omit details, provides convenient building blocks
-(such as `while` and `console.log`), allows you to define your own
-building blocks (such as `sum` and `range`), and makes those blocks
-easy to compose.
+A good programming language helps the programmer by allowing them to talk about the actions that the computer has to perform on a higher level. It helps omit details, provides convenient building blocks (such as `while` and `console.log`), allows you to define your own building blocks (such as `sum` and `range`), and makes those blocks easy to compose.
## What is JavaScript?
@@ -299,111 +177,47 @@ easy to compose.
{{indexsee Web, "World Wide Web"}}
-JavaScript was introduced in 1995 as a way to add programs to web
-pages in the Netscape Navigator browser. The language has since been
-adopted by all other major graphical web browsers. It has made modern
-web applications possible—applications with which you can interact
-directly without doing a page reload for every action. JavaScript is also
-used in more traditional websites to provide various forms of
-interactivity and cleverness.
+JavaScript was introduced in 1995 as a way to add programs to web pages in the Netscape Navigator browser. The language has since been adopted by all other major graphical web browsers. It has made modern web applications possible—applications with which you can interact directly without doing a page reload for every action. JavaScript is also used in more traditional websites to provide various forms of interactivity and cleverness.
{{index Java, naming}}
-It is important to note that JavaScript has almost nothing to do with
-the programming language named Java. The similar name was inspired by
-marketing considerations rather than good judgment. When JavaScript
-was being introduced, the Java language was being heavily marketed and
-was gaining popularity. Someone thought it was a good idea to try to
-ride along on this success. Now we are stuck with the name.
+It is important to note that JavaScript has almost nothing to do with the programming language named Java. The similar name was inspired by marketing considerations rather than good judgment. When JavaScript was being introduced, the Java language was being heavily marketed and was gaining popularity. Someone thought it was a good idea to try to ride along on this success. Now we are stuck with the name.
{{index ECMAScript, compatibility}}
-After its adoption outside of Netscape, a ((standard)) document was
-written to describe the way the JavaScript language should work so
-that the various pieces of software that claimed to support JavaScript
-were actually talking about the same language. This is called the
-ECMAScript standard, after the Ecma International organization that
-did the standardization. In practice, the terms ECMAScript and
-JavaScript can be used interchangeably—they are two names for the same
-language.
+After its adoption outside of Netscape, a ((standard)) document was written to describe the way the JavaScript language should work so that the various pieces of software that claimed to support JavaScript were actually talking about the same language. This is called the ECMAScript standard, after the Ecma International organization that did the standardization. In practice, the terms ECMAScript and JavaScript can be used interchangeably—they are two names for the same language.
{{index [JavaScript, "weaknesses of"], debugging}}
-There are those who will say _terrible_ things about JavaScript. Many
-of these things are true. When I was required to write something in
-JavaScript for the first time, I quickly came to despise it. It would
-accept almost anything I typed but interpret it in a way that was
-completely different from what I meant. This had a lot to do with the
-fact that I did not have a clue what I was doing, of course, but there
-is a real issue here: JavaScript is ridiculously liberal in what it
-allows. The idea behind this design was that it would make programming
-in JavaScript easier for beginners. In actuality, it mostly makes
-finding problems in your programs harder because the system will not
-point them out to you.
+There are those who will say _terrible_ things about JavaScript. Many of these things are true. When I was required to write something in JavaScript for the first time, I quickly came to despise it. It would accept almost anything I typed but interpret it in a way that was completely different from what I meant. This had a lot to do with the fact that I did not have a clue what I was doing, of course, but there is a real issue here: JavaScript is ridiculously liberal in what it allows. The idea behind this design was that it would make programming in JavaScript easier for beginners. In actuality, it mostly makes finding problems in your programs harder because the system will not point them out to you.
{{index [JavaScript, "flexibility of"], flexibility}}
-This flexibility also has its advantages, though. It leaves space for
-a lot of techniques that are impossible in more rigid languages, and
-as you will see (for example in [Chapter ?](modules)), it can be used
-to overcome some of JavaScript's shortcomings. After ((learning)) the
-language properly and working with it for a while, I have learned to
-actually _like_ JavaScript.
+This flexibility also has its advantages, though. It leaves space for a lot of techniques that are impossible in more rigid languages, and as you will see (for example in [Chapter ?](modules)), it can be used to overcome some of JavaScript's shortcomings. After ((learning)) the language properly and working with it for a while, I have learned to actually _like_ JavaScript.
{{index future, [JavaScript, "versions of"], ECMAScript, "ECMAScript 6"}}
-There have been several versions of JavaScript. ECMAScript version 3
-was the widely supported version in the time of JavaScript's ascent to
-dominance, roughly between 2000 and 2010. During this time, work was
-underway on an ambitious version 4, which planned a number of radical
-improvements and extensions to the language. Changing a living, widely
-used language in such a radical way turned out to be politically
-difficult, and work on the version 4 was abandoned in 2008, leading to
-a much less ambitious version 5, which made only some uncontroversial
-improvements, coming out in 2009. Then in 2015 version 6 came out, a
-major update that included some of the ideas planned for version 4.
-Since then we've had new, small updates every year.
-
-The fact that the language is evolving means that browsers have to
-constantly keep up, and if you're using an older browser, it may not
-support every feature. The language designers are careful to not make
-any changes that could break existing programs, so new browsers can
-still run old programs. In this book, I'm using the 2017 version of
-JavaScript.
+There have been several versions of JavaScript. ECMAScript version 3 was the widely supported version in the time of JavaScript's ascent to dominance, roughly between 2000 and 2010. During this time, work was underway on an ambitious version 4, which planned a number of radical improvements and extensions to the language. Changing a living, widely used language in such a radical way turned out to be politically difficult, and work on the version 4 was abandoned in 2008, leading to a much less ambitious version 5, which made only some uncontroversial improvements, coming out in 2009. Then in 2015 version 6 came out, a major update that included some of the ideas planned for version 4. Since then we've had new, small updates every year.
+
+The fact that the language is evolving means that browsers have to constantly keep up, and if you're using an older browser, it may not support every feature. The language designers are careful to not make any changes that could break existing programs, so new browsers can still run old programs. In this book, I'm using the 2017 version of JavaScript.
{{index [JavaScript, "uses of"]}}
-Web browsers are not the only platforms on which JavaScript is used.
-Some databases, such as MongoDB and CouchDB, use JavaScript as their
-scripting and query language. Several platforms for desktop and server
-programming, most notably the ((Node.js)) project (the subject of
-[Chapter ?](node)), provide an environment for programming JavaScript
-outside of the browser.
+Web browsers are not the only platforms on which JavaScript is used. Some databases, such as MongoDB and CouchDB, use JavaScript as their scripting and query language. Several platforms for desktop and server programming, most notably the ((Node.js)) project (the subject of [Chapter ?](node)), provide an environment for programming JavaScript outside of the browser.
## Code, and what to do with it
{{index "reading code", "writing code"}}
-_Code_ is the text that makes up programs. Most chapters in this book
-contain quite a lot of code. I believe reading code and writing ((code))
-are indispensable parts of ((learning)) to program. Try to not just
-glance over the examples—read them attentively and understand them.
-This may be slow and confusing at first, but I promise that you'll
-quickly get the hang of it. The same goes for the ((exercises)). Don't
-assume you understand them until you've actually written a working
-solution.
+_Code_ is the text that makes up programs. Most chapters in this book contain quite a lot of code. I believe reading code and writing ((code)) are indispensable parts of ((learning)) to program. Try to not just glance over the examples—read them attentively and understand them. This may be slow and confusing at first, but I promise that you'll quickly get the hang of it. The same goes for the ((exercises)). Don't assume you understand them until you've actually written a working solution.
{{index interpretation}}
-I recommend you try your solutions to exercises in an actual
-JavaScript interpreter. That way, you'll get immediate feedback on
-whether what you are doing is working, and, I hope, you'll be tempted
-to ((experiment)) and go beyond the exercises.
+I recommend you try your solutions to exercises in an actual JavaScript interpreter. That way, you'll get immediate feedback on whether what you are doing is working, and, I hope, you'll be tempted to ((experiment)) and go beyond the exercises.
{{if interactive
-When reading this book in your browser, you can edit (and run) all
-example programs by clicking them.
+When reading this book in your browser, you can edit (and run) all example programs by clicking them.
if}}
@@ -411,76 +225,31 @@ if}}
{{index download, sandbox, "running code"}}
-The easiest way to run the example code in the book, and to experiment
-with it, is to look it up in the online version of the book at
-[_https://eloquentjavascript.net_](https://eloquentjavascript.net/). There,
-you can click any code example to edit and run it and to see the
-output it produces. To work on the exercises, go to
-[_https://eloquentjavascript.net/code_](https://eloquentjavascript.net/code),
-which provides starting code for each coding exercise and allows you
-to look at the solutions.
+The easiest way to run the example code in the book, and to experiment with it, is to look it up in the online version of the book at [_https://eloquentjavascript.net_](https://eloquentjavascript.net/). There, you can click any code example to edit and run it and to see the output it produces. To work on the exercises, go to [_https://eloquentjavascript.net/code_](https://eloquentjavascript.net/code), which provides starting code for each coding exercise and allows you to look at the solutions.
if}}
{{index "developer tools", "JavaScript console"}}
-If you want to run the programs defined in this book outside of the
-book's website, some care will be required. Many examples stand on their
-own and should work in any JavaScript environment. But code in later
-chapters is often written for a specific environment (the browser or
-Node.js) and can run only there. In addition, many chapters define
-bigger programs, and the pieces of code that appear in them depend on
-each other or on external files. The
-[sandbox](https://eloquentjavascript.net/code) on the website provides
-links to Zip files containing all the scripts and data files
-necessary to run the code for a given chapter.
+If you want to run the programs defined in this book outside of the book's website, some care will be required. Many examples stand on their own and should work in any JavaScript environment. But code in later chapters is often written for a specific environment (the browser or Node.js) and can run only there. In addition, many chapters define bigger programs, and the pieces of code that appear in them depend on each other or on external files. The [sandbox](https://eloquentjavascript.net/code) on the website provides links to Zip files containing all the scripts and data files necessary to run the code for a given chapter.
## Overview of this book
-This book contains roughly three parts. The first 12 chapters discuss
-the JavaScript language. The next seven chapters are about web
-((browsers)) and the way JavaScript is used to program them. Finally,
-two chapters are devoted to ((Node.js)), another environment to
-program JavaScript in.
-
-Throughout the book, there are five _project chapters_, which describe
-larger example programs to give you a taste of actual programming. In
-order of appearance, we will work through building a [delivery
-robot](robot), a [programming language](language), a [platform
-game](game), a [pixel paint program](paint), and a [dynamic
-website](skillsharing).
-
-The language part of the book starts with four chapters that introduce
-the basic structure of the JavaScript language. They introduce
-[control structures](program_structure) (such as the `while` word you
-saw in this introduction), [functions](functions) (writing your own
-building blocks), and [data structures](data). After these, you will
-be able to write basic programs. Next, Chapters [?](higher_order) and
-[?](object) introduce techniques to use functions and objects to write
-more _abstract_ code and keep complexity under control.
-
-After a [first project chapter](robot), the language part of the book
-continues with chapters on [error handling and bug fixing](error),
-[regular expressions](regexp) (an important tool for working with
-text), [modularity](modules) (another defense against complexity), and
-[asynchronous programming](async) (dealing with events that take
-time). The [second project chapter](language) concludes the first part
-of the book.
-
-The second part, Chapters [?](browser) to [?](paint), describes the
-tools that browser JavaScript has access to. You'll learn to display
-things on the screen (Chapters [?](dom) and [?](canvas)), respond to
-user input ([Chapter ?](event)), and communicate over the network
-([Chapter ?](http)). There are again two project chapters in this
-part.
-
-After that, [Chapter ?](node) describes Node.js, and [Chapter
-?](skillsharing) builds a small website using that tool.
+This book contains roughly three parts. The first 12 chapters discuss the JavaScript language. The next seven chapters are about web ((browsers)) and the way JavaScript is used to program them. Finally, two chapters are devoted to ((Node.js)), another environment to program JavaScript in.
+
+Throughout the book, there are five _project chapters_, which describe larger example programs to give you a taste of actual programming. In order of appearance, we will work through building a [delivery robot](robot), a [programming language](language), a [platform game](game), a [pixel paint program](paint), and a [dynamic website](skillsharing).
+
+The language part of the book starts with four chapters that introduce the basic structure of the JavaScript language. They introduce [control structures](program_structure) (such as the `while` word you saw in this introduction), [functions](functions) (writing your own building blocks), and [data structures](data). After these, you will be able to write basic programs. Next, Chapters [?](higher_order) and [?](object) introduce techniques to use functions and objects to write more _abstract_ code and keep complexity under control.
+
+After a [first project chapter](robot), the language part of the book continues with chapters on [error handling and bug fixing](error), [regular expressions](regexp) (an important tool for working with text), [modularity](modules) (another defense against complexity), and [asynchronous programming](async) (dealing with events that take time). The [second project chapter](language) concludes the first part of the book.
+
+The second part, Chapters [?](browser) to [?](paint), describes the tools that browser JavaScript has access to. You'll learn to display things on the screen (Chapters [?](dom) and [?](canvas)), respond to user input ([Chapter ?](event)), and communicate over the network ([Chapter ?](http)). There are again two project chapters in this part.
+
+After that, [Chapter ?](node) describes Node.js, and [Chapter ?](skillsharing) builds a small website using that tool.
{{if commercial
-Finally, [Chapter ?](fast) describes some of the considerations that
-come up when optimizing JavaScript programs for speed.
+Finally, [Chapter ?](fast) describes some of the considerations that come up when optimizing JavaScript programs for speed.
if}}
@@ -488,10 +257,7 @@ if}}
{{index "factorial function"}}
-In this book, text written in a `monospaced` font will represent
-elements of programs—sometimes they are self-sufficient fragments, and
-sometimes they just refer to part of a nearby program. Programs (of
-which you have already seen a few) are written as follows:
+In this book, text written in a `monospaced` font will represent elements of programs—sometimes they are self-sufficient fragments, and sometimes they just refer to part of a nearby program. Programs (of which you have already seen a few) are written as follows:
```
function factorial(n) {
@@ -505,9 +271,7 @@ function factorial(n) {
{{index "console.log"}}
-Sometimes, to show the output that a program produces, the
-expected output is written after it, with two slashes and an arrow in
-front.
+Sometimes, to show the output that a program produces, the expected output is written after it, with two slashes and an arrow in front.
```
console.log(factorial(8));
diff --git a/01_values.md b/01_values.md
index 63cb2533d..d975a69a2 100644
--- a/01_values.md
+++ b/01_values.md
@@ -4,10 +4,7 @@
{{quote {author: "Master Yuan-Ma", title: "The Book of Programming", chapter: true}
-Below the surface of the machine, the program moves. Without effort,
-it expands and contracts. In great harmony, electrons scatter and
-regroup. The forms on the monitor are but ripples on the water. The
-essence stays invisibly below.
+Below the surface of the machine, the program moves. Without effort, it expands and contracts. In great harmony, electrons scatter and regroup. The forms on the monitor are but ripples on the water. The essence stays invisibly below.
quote}}
@@ -17,74 +14,42 @@ quote}}
{{index "binary data", data, bit, memory}}
-Inside the computer's world, there is only data. You can read data,
-modify data, create new data—but that which isn't data cannot be
-mentioned. All this data is stored as long sequences of bits and is
-thus fundamentally alike.
+Inside the computer's world, there is only data. You can read data, modify data, create new data—but that which isn't data cannot be mentioned. All this data is stored as long sequences of bits and is thus fundamentally alike.
{{index CD, signal}}
-_Bits_ are any kind of two-valued things, usually described as zeros and
-ones. Inside the computer, they take forms such as a high or low
-electrical charge, a strong or weak signal, or a shiny or dull spot on
-the surface of a CD. Any piece of discrete information can be reduced
-to a sequence of zeros and ones and thus represented in bits.
+_Bits_ are any kind of two-valued things, usually described as zeros and ones. Inside the computer, they take forms such as a high or low electrical charge, a strong or weak signal, or a shiny or dull spot on the surface of a CD. Any piece of discrete information can be reduced to a sequence of zeros and ones and thus represented in bits.
{{index "binary number", radix, "decimal number"}}
-For example, we can express the number 13 in bits. It works the same
-way as a decimal number, but instead of 10 different ((digit))s, you
-have only 2, and the weight of each increases by a factor of 2 from
-right to left. Here are the bits that make up the number 13, with the
-weights of the digits shown below them:
+For example, we can express the number 13 in bits. It works the same way as a decimal number, but instead of 10 different ((digit))s, you have only 2, and the weight of each increases by a factor of 2 from right to left. Here are the bits that make up the number 13, with the weights of the digits shown below them:
```{lang: null}
0 0 0 0 1 1 0 1
128 64 32 16 8 4 2 1
```
-So that's the binary number 00001101. Its non-zero digits stand for
-8, 4, and 1, and add up to 13.
+So that's the binary number 00001101. Its non-zero digits stand for 8, 4, and 1, and add up to 13.
## Values
{{index [memory, organization], "volatile data storage", "hard drive"}}
-Imagine a sea of bits—an ocean of them. A typical modern computer has
-more than 30 billion bits in its volatile data storage (working
-memory). Nonvolatile storage (the hard disk or equivalent) tends to
-have yet a few orders of magnitude more.
+Imagine a sea of bits—an ocean of them. A typical modern computer has more than 30 billion bits in its volatile data storage (working memory). Nonvolatile storage (the hard disk or equivalent) tends to have yet a few orders of magnitude more.
-To be able to work with such quantities of bits without getting lost,
-we must separate them into chunks that represent pieces of
-information. In a JavaScript environment, those chunks are called
-_((value))s_. Though all values are made of bits, they play different
-roles. Every value has a ((type)) that determines its role. Some
-values are numbers, some values are pieces of text, some values are
-functions, and so on.
+To be able to work with such quantities of bits without getting lost, we must separate them into chunks that represent pieces of information. In a JavaScript environment, those chunks are called _((value))s_. Though all values are made of bits, they play different roles. Every value has a ((type)) that determines its role. Some values are numbers, some values are pieces of text, some values are functions, and so on.
{{index "garbage collection"}}
-To create a value, you must merely invoke its name. This is
-convenient. You don't have to gather building material for your values
-or pay for them. You just call for one, and _whoosh_, you have it. They
-are not really created from thin air, of course. Every value has to be
-stored somewhere, and if you want to use a gigantic amount of them at
-the same time, you might run out of memory. Fortunately, this is a
-problem only if you need them all simultaneously. As soon as you no
-longer use a value, it will dissipate, leaving behind its bits to be
-recycled as building material for the next generation of values.
+To create a value, you must merely invoke its name. This is convenient. You don't have to gather building material for your values or pay for them. You just call for one, and _whoosh_, you have it. They are not really created from thin air, of course. Every value has to be stored somewhere, and if you want to use a gigantic amount of them at the same time, you might run out of memory. Fortunately, this is a problem only if you need them all simultaneously. As soon as you no longer use a value, it will dissipate, leaving behind its bits to be recycled as building material for the next generation of values.
-This chapter introduces the atomic elements of JavaScript programs,
-that is, the simple value types and the operators that can act on such
-values.
+This chapter introduces the atomic elements of JavaScript programs, that is, the simple value types and the operators that can act on such values.
## Numbers
{{index [syntax, number], number, [number, notation]}}
-Values of the _number_ type are, unsurprisingly, numeric values. In a
-JavaScript program, they are written as follows:
+Values of the _number_ type are, unsurprisingly, numeric values. In a JavaScript program, they are written as follows:
```
13
@@ -92,36 +57,17 @@ JavaScript program, they are written as follows:
{{index "binary number"}}
-Use that in a program, and it will cause the bit pattern for the
-number 13 to come into existence inside the computer's memory.
+Use that in a program, and it will cause the bit pattern for the number 13 to come into existence inside the computer's memory.
{{index [number, representation], bit}}
-JavaScript uses a fixed number of bits, 64 of them, to store a
-single number value. There are only so many patterns you can make with
-64 bits, which means that the number of different numbers that can be
-represented is limited. With _N_ decimal ((digit))s, you can represent
-10^N^ numbers. Similarly, given 64 binary
-digits, you can represent 2^64^ different numbers, which is about 18
-quintillion (an 18 with 18 zeros after it). That's a lot.
-
-Computer memory used to be much smaller, and people tended to use
-groups of 8 or 16 bits to represent their numbers. It was easy to
-accidentally _((overflow))_ such small numbers—to end up with a number
-that did not fit into the given number of bits. Today, even computers
-that fit in your pocket have plenty of memory, so you are free to use
-64-bit chunks, and you need to worry about overflow only when dealing
-with truly astronomical numbers.
+JavaScript uses a fixed number of bits, 64 of them, to store a single number value. There are only so many patterns you can make with 64 bits, which means that the number of different numbers that can be represented is limited. With _N_ decimal ((digit))s, you can represent 10^N^ numbers. Similarly, given 64 binary digits, you can represent 2^64^ different numbers, which is about 18 quintillion (an 18 with 18 zeros after it). That's a lot.
+
+Computer memory used to be much smaller, and people tended to use groups of 8 or 16 bits to represent their numbers. It was easy to accidentally _((overflow))_ such small numbers—to end up with a number that did not fit into the given number of bits. Today, even computers that fit in your pocket have plenty of memory, so you are free to use 64-bit chunks, and you need to worry about overflow only when dealing with truly astronomical numbers.
{{index sign, "floating-point number", "sign bit"}}
-Not all whole numbers less than 18 quintillion fit in a JavaScript number,
-though. Those bits also store negative numbers, so one bit indicates
-the sign of the number. A bigger issue is that nonwhole numbers must
-also be represented. To do this, some of the bits are used to store
-the position of the decimal point. The actual maximum whole number
-that can be stored is more in the range of 9 quadrillion (15
-zeros)—which is still pleasantly huge.
+Not all whole numbers less than 18 quintillion fit in a JavaScript number, though. Those bits also store negative numbers, so one bit indicates the sign of the number. A bigger issue is that nonwhole numbers must also be represented. To do this, some of the bits are used to store the position of the decimal point. The actual maximum whole number that can be stored is more in the range of 9 quadrillion (15 zeros)—which is still pleasantly huge.
{{index [number, notation], "fractional number"}}
@@ -133,9 +79,7 @@ Fractional numbers are written by using a dot.
{{index exponent, "scientific notation", [number, notation]}}
-For very big or very small numbers, you may also use scientific
-notation by adding an _e_ (for _exponent_), followed by the exponent
-of the number.
+For very big or very small numbers, you may also use scientific notation by adding an _e_ (for _exponent_), followed by the exponent of the number.
```
2.998e8
@@ -145,23 +89,13 @@ That is 2.998 × 10^8^ = 299,800,000.
{{index pi, [number, "precision of"], "floating-point number"}}
-Calculations with whole numbers (also called _((integer))s_) smaller
-than the aforementioned 9 quadrillion are guaranteed to always be
-precise. Unfortunately, calculations with fractional numbers are
-generally not. Just as π (pi) cannot be precisely expressed by a
-finite number of decimal digits, many numbers lose some precision when
-only 64 bits are available to store them. This is a shame, but it
-causes practical problems only in specific situations. The important
-thing is to be aware of it and treat fractional digital numbers as
-approximations, not as precise values.
+Calculations with whole numbers (also called _((integer))s_) smaller than the aforementioned 9 quadrillion are guaranteed to always be precise. Unfortunately, calculations with fractional numbers are generally not. Just as π (pi) cannot be precisely expressed by a finite number of decimal digits, many numbers lose some precision when only 64 bits are available to store them. This is a shame, but it causes practical problems only in specific situations. The important thing is to be aware of it and treat fractional digital numbers as approximations, not as precise values.
### Arithmetic
{{index [syntax, operator], operator, "binary operator", arithmetic, addition, multiplication}}
-The main thing to do with numbers is arithmetic. Arithmetic operations
-such as addition or multiplication take two number values and produce
-a new number from them. Here is what they look like in JavaScript:
+The main thing to do with numbers is arithmetic. Arithmetic operations such as addition or multiplication take two number values and produce a new number from them. Here is what they look like in JavaScript:
```
100 + 4 * 11
@@ -169,17 +103,11 @@ a new number from them. Here is what they look like in JavaScript:
{{index [operator, application], asterisk, "plus character", "* operator", "+ operator"}}
-The `+` and `*` symbols are called _operators_. The first stands for
-addition, and the second stands for multiplication. Putting an
-operator between two values will apply it to those values and produce
-a new value.
+The `+` and `*` symbols are called _operators_. The first stands for addition, and the second stands for multiplication. Putting an operator between two values will apply it to those values and produce a new value.
{{index grouping, parentheses, precedence}}
-But does the example mean "add 4 and 100, and multiply the result by 11,"
-or is the multiplication done before the adding? As you might have
-guessed, the multiplication happens first. But as in mathematics, you
-can change this by wrapping the addition in parentheses.
+But does the example mean "add 4 and 100, and multiply the result by 11," or is the multiplication done before the adding? As you might have guessed, the multiplication happens first. But as in mathematics, you can change this by wrapping the addition in parentheses.
```
(100 + 4) * 11
@@ -187,51 +115,29 @@ can change this by wrapping the addition in parentheses.
{{index "hyphen character", "slash character", division, subtraction, minus, "- operator", "/ operator"}}
-For subtraction, there is the `-` operator, and division can be done
-with the `/` operator.
+For subtraction, there is the `-` operator, and division can be done with the `/` operator.
-When operators appear together without parentheses, the order in which
-they are applied is determined by the _((precedence))_ of the
-operators. The example shows that multiplication comes before
-addition. The `/` operator has the same precedence as `*`. Likewise
-for `+` and `-`. When multiple operators with the same precedence
-appear next to each other, as in `1 - 2 + 1`, they are applied left to
-right: `(1 - 2) + 1`.
+When operators appear together without parentheses, the order in which they are applied is determined by the _((precedence))_ of the operators. The example shows that multiplication comes before addition. The `/` operator has the same precedence as `*`. Likewise for `+` and `-`. When multiple operators with the same precedence appear next to each other, as in `1 - 2 + 1`, they are applied left to right: `(1 - 2) + 1`.
-These rules of precedence are not something you should worry about.
-When in doubt, just add parentheses.
+These rules of precedence are not something you should worry about. When in doubt, just add parentheses.
{{index "modulo operator", division, "remainder operator", "% operator"}}
-There is one more arithmetic operator, which you might not immediately
-recognize. The `%` symbol is used to represent the _remainder_
-operation. `X % Y` is the remainder of dividing `X` by `Y`. For
-example, `314 % 100` produces `14`, and `144 % 12` gives `0`.
-The remainder operator's precedence is the same as that of multiplication and
-division. You'll also often see this operator referred to as _modulo_.
+There is one more arithmetic operator, which you might not immediately recognize. The `%` symbol is used to represent the _remainder_ operation. `X % Y` is the remainder of dividing `X` by `Y`. For example, `314 % 100` produces `14`, and `144 % 12` gives `0`. The remainder operator's precedence is the same as that of multiplication and division. You'll also often see this operator referred to as _modulo_.
### Special numbers
{{index [number, "special values"]}}
-There are three special values in JavaScript that are considered
-numbers but don't behave like normal numbers.
+There are three special values in JavaScript that are considered numbers but don't behave like normal numbers.
{{index infinity}}
-The first two are `Infinity` and `-Infinity`, which represent the
-positive and negative infinities. `Infinity - 1` is still `Infinity`,
-and so on. Don't put too much trust in infinity-based computation,
-though. It isn't mathematically sound, and it will quickly lead to the
-next special number: `NaN`.
+The first two are `Infinity` and `-Infinity`, which represent the positive and negative infinities. `Infinity - 1` is still `Infinity`, and so on. Don't put too much trust in infinity-based computation, though. It isn't mathematically sound, and it will quickly lead to the next special number: `NaN`.
{{index NaN, "not a number", "division by zero"}}
-`NaN` stands for "not a number", even though it _is_ a value of the
-number type. You'll get this result when you, for example, try to
-calculate `0 / 0` (zero divided by zero), `Infinity - Infinity`, or
-any number of other numeric operations that don't yield a meaningful
-result.
+`NaN` stands for "not a number", even though it _is_ a value of the number type. You'll get this result when you, for example, try to calculate `0 / 0` (zero divided by zero), `Infinity - Infinity`, or any number of other numeric operations that don't yield a meaningful result.
## Strings
@@ -239,8 +145,7 @@ result.
{{index [syntax, string], text, character, [string, notation], "single-quote character", "double-quote character", "quotation mark", backtick}}
-The next basic data type is the _((string))_. Strings are used to
-represent text. They are written by enclosing their content in quotes.
+The next basic data type is the _((string))_. Strings are used to represent text. They are written by enclosing their content in quotes.
```
`Down on the sea`
@@ -248,29 +153,15 @@ represent text. They are written by enclosing their content in quotes.
'Float on the ocean'
```
-You can use single quotes, double quotes, or backticks to mark
-strings, as long as the quotes at the start and the end of the string
-match.
+You can use single quotes, double quotes, or backticks to mark strings, as long as the quotes at the start and the end of the string match.
{{index "line break", "newline character"}}
-Almost anything can be put between quotes, and JavaScript will make a
-string value out of it. But a few characters are more difficult. You
-can imagine how putting quotes between quotes might be hard.
-_Newlines_ (the characters you get when you press [enter]{keyname}) can be
-included without escaping only when the string is quoted with backticks
-(`` ` ``).
+Almost anything can be put between quotes, and JavaScript will make a string value out of it. But a few characters are more difficult. You can imagine how putting quotes between quotes might be hard. _Newlines_ (the characters you get when you press [enter]{keyname}) can be included without escaping only when the string is quoted with backticks (`` ` ``).
{{index [escaping, "in strings"], ["backslash character", "in strings"]}}
-To make it possible to include such characters in a string, the
-following notation is used: whenever a backslash (`\`) is found inside
-quoted text, it indicates that the character after it has a special
-meaning. This is called _escaping_ the character. A quote that is
-preceded by a backslash will not end the string but be part of it.
-When an `n` character occurs after a backslash, it is interpreted as a
-newline. Similarly, a `t` after a backslash means a ((tab character)).
-Take the following string:
+To make it possible to include such characters in a string, the following notation is used: whenever a backslash (`\`) is found inside quoted text, it indicates that the character after it has a special meaning. This is called _escaping_ the character. A quote that is preceded by a backslash will not end the string but be part of it. When an `n` character occurs after a backslash, it is interpreted as a newline. Similarly, a `t` after a backslash means a ((tab character)). Take the following string:
```
"This is the first line\nAnd this is the second"
@@ -283,11 +174,7 @@ This is the first line
And this is the second
```
-There are, of course, situations where you want a backslash in a
-string to be just a backslash, not a special code. If two backslashes
-follow each other, they will collapse together, and only one will be
-left in the resulting string value. This is how the string "_A newline
-character is written like `"`\n`"`._" can be expressed:
+There are, of course, situations where you want a backslash in a string to be just a backslash, not a special code. If two backslashes follow each other, they will collapse together, and only one will be left in the resulting string value. This is how the string "_A newline character is written like `"`\n`"`._" can be expressed:
```
"A newline character is written like \"\\n\"."
@@ -297,62 +184,37 @@ character is written like `"`\n`"`._" can be expressed:
{{index [string, representation], Unicode, character}}
-Strings, too, have to be modeled as a series of bits to be able to
-exist inside the computer. The way JavaScript does this is based on
-the _((Unicode))_ standard. This standard assigns a number to
-virtually every character you would ever need, including characters
-from Greek, Arabic, Japanese, Armenian, and so on. If we have a number
-for every character, a string can be described by a sequence of
-numbers.
+Strings, too, have to be modeled as a series of bits to be able to exist inside the computer. The way JavaScript does this is based on the _((Unicode))_ standard. This standard assigns a number to virtually every character you would ever need, including characters from Greek, Arabic, Japanese, Armenian, and so on. If we have a number for every character, a string can be described by a sequence of numbers.
{{index "UTF-16", emoji}}
-And that's what JavaScript does. But there's a complication:
-JavaScript's representation uses 16 bits per string element, which can
-describe up to 2^16^ different characters. But Unicode defines more
-characters than that—about twice as many, at this point. So some
-characters, such as many emoji, take up two "character positions" in
-JavaScript strings. We'll come back to this in [Chapter
-?](higher_order#code_units).
+And that's what JavaScript does. But there's a complication: JavaScript's representation uses 16 bits per string element, which can describe up to 2^16^ different characters. But Unicode defines more characters than that—about twice as many, at this point. So some characters, such as many emoji, take up two "character positions" in JavaScript strings. We'll come back to this in [Chapter ?](higher_order#code_units).
{{index "+ operator", concatenation}}
-Strings cannot be divided, multiplied, or subtracted, but the `+`
-operator _can_ be used on them. It does not add, but it
-_concatenates_—it glues two strings together. The following line will
-produce the string `"concatenate"`:
+Strings cannot be divided, multiplied, or subtracted, but the `+` operator _can_ be used on them. It does not add, but it _concatenates_—it glues two strings together. The following line will produce the string `"concatenate"`:
```
"con" + "cat" + "e" + "nate"
```
-String values have a number of associated functions (_methods_) that
-can be used to perform other operations on them. I'll say more about
-these in [Chapter ?](data#methods).
+String values have a number of associated functions (_methods_) that can be used to perform other operations on them. I'll say more about these in [Chapter ?](data#methods).
{{index interpolation, backtick}}
-Strings written with single or double quotes behave very much the
-same—the only difference is in which type of quote you need to escape
-inside of them. Backtick-quoted strings, usually called _((template
-literals))_, can do a few more tricks. Apart from being able to span
-lines, they can also embed other values.
+Strings written with single or double quotes behave very much the same—the only difference is in which type of quote you need to escape inside of them. Backtick-quoted strings, usually called _((template literals))_, can do a few more tricks. Apart from being able to span lines, they can also embed other values.
```
`half of 100 is ${100 / 2}`
```
-When you write something inside `${}` in a template literal, its
-result will be computed, converted to a string, and included at that
-position. The example produces "_half of 100 is 50_".
+When you write something inside `${}` in a template literal, its result will be computed, converted to a string, and included at that position. The example produces "_half of 100 is 50_".
## Unary operators
{{index operator, "typeof operator", type}}
-Not all operators are symbols. Some are written as words. One example
-is the `typeof` operator, which produces a string value naming the
-type of the value you give it.
+Not all operators are symbols. Some are written as words. One example is the `typeof` operator, which produces a string value naming the type of the value you give it.
```
console.log(typeof 4.5)
@@ -365,17 +227,11 @@ console.log(typeof "x")
{{id "console.log"}}
-We will use `console.log` in example code to indicate that we want to
-see the result of evaluating something. More about that in the [next
-chapter](program_structure).
+We will use `console.log` in example code to indicate that we want to see the result of evaluating something. More about that in the [next chapter](program_structure).
{{index negation, "- operator", "binary operator", "unary operator"}}
-The other operators shown all operated on two values, but `typeof`
-takes only one. Operators that use two values are called _binary_
-operators, while those that take one are called _unary_ operators. The
-minus operator can be used both as a binary operator and as a unary
-operator.
+The other operators shown all operated on two values, but `typeof` takes only one. Operators that use two values are called _binary_ operators, while those that take one are called _unary_ operators. The minus operator can be used both as a binary operator and as a unary operator.
```
console.log(- (10 - 2))
@@ -386,10 +242,7 @@ console.log(- (10 - 2))
{{index Boolean, operator, true, false, bit}}
-It is often useful to have a value that distinguishes between only two
-possibilities, like "yes" and "no" or "on" and "off". For this
-purpose, JavaScript has a _Boolean_ type, which has just two values,
-true and false, which are written as those words.
+It is often useful to have a value that distinguishes between only two possibilities, like "yes" and "no" or "on" and "off". For this purpose, JavaScript has a _Boolean_ type, which has just two values, true and false, which are written as those words.
### Comparison
@@ -406,10 +259,7 @@ console.log(3 < 2)
{{index [comparison, "of numbers"], "> operator", "< operator", "greater than", "less than"}}
-The `>` and `<` signs are the traditional symbols for "is greater
-than" and "is less than", respectively. They are binary operators.
-Applying them results in a Boolean value that indicates whether they
-hold true in this case.
+The `>` and `<` signs are the traditional symbols for "is greater than" and "is less than", respectively. They are binary operators. Applying them results in a Boolean value that indicates whether they hold true in this case.
Strings can be compared in the same way.
@@ -420,17 +270,11 @@ console.log("Aardvark" < "Zoroaster")
{{index [comparison, "of strings"]}}
-The way strings are ordered is roughly alphabetic but not really what
-you'd expect to see in a dictionary: uppercase letters are always
-"less" than lowercase ones, so `"Z" < "a"`, and nonalphabetic
-characters (!, -, and so on) are also included in the ordering. When
-comparing strings, JavaScript goes over the characters from left to
-right, comparing the ((Unicode)) codes one by one.
+The way strings are ordered is roughly alphabetic but not really what you'd expect to see in a dictionary: uppercase letters are always "less" than lowercase ones, so `"Z" < "a"`, and nonalphabetic characters (!, -, and so on) are also included in the ordering. When comparing strings, JavaScript goes over the characters from left to right, comparing the ((Unicode)) codes one by one.
{{index equality, ">= operator", "<= operator", "== operator", "!= operator"}}
-Other similar operators are `>=` (greater than or equal to), `<=`
-(less than or equal to), `==` (equal to), and `!=` (not equal to).
+Other similar operators are `>=` (greater than or equal to), `<=` (less than or equal to), `==` (equal to), and `!=` (not equal to).
```
console.log("Itchy" != "Scratchy")
@@ -441,30 +285,24 @@ console.log("Apple" == "Orange")
{{index [comparison, "of NaN"], NaN}}
-There is only one value in JavaScript that is not equal to itself, and
-that is `NaN` ("not a number").
+There is only one value in JavaScript that is not equal to itself, and that is `NaN` ("not a number").
```
console.log(NaN == NaN)
// → false
```
-`NaN` is supposed to denote the result of a nonsensical computation,
-and as such, it isn't equal to the result of any _other_ nonsensical
-computations.
+`NaN` is supposed to denote the result of a nonsensical computation, and as such, it isn't equal to the result of any _other_ nonsensical computations.
### Logical operators
{{index reasoning, "logical operators"}}
-There are also some operations that can be applied to Boolean values
-themselves. JavaScript supports three logical operators: _and_, _or_,
-and _not_. These can be used to "reason" about Booleans.
+There are also some operations that can be applied to Boolean values themselves. JavaScript supports three logical operators: _and_, _or_, and _not_. These can be used to "reason" about Booleans.
{{index "&& operator", "logical and"}}
-The `&&` operator represents logical _and_. It is a binary operator,
-and its result is true only if both the values given to it are true.
+The `&&` operator represents logical _and_. It is a binary operator, and its result is true only if both the values given to it are true.
```
console.log(true && false)
@@ -475,8 +313,7 @@ console.log(true && true)
{{index "|| operator", "logical or"}}
-The `||` operator denotes logical _or_. It produces true if either of
-the values given to it is true.
+The `||` operator denotes logical _or_. It produces true if either of the values given to it is true.
```
console.log(false || true)
@@ -487,19 +324,11 @@ console.log(false || false)
{{index negation, "! operator"}}
-_Not_ is written as an exclamation mark (`!`). It is a unary operator
-that flips the value given to it—`!true` produces `false`, and `!false`
-gives `true`.
+_Not_ is written as an exclamation mark (`!`). It is a unary operator that flips the value given to it—`!true` produces `false`, and `!false` gives `true`.
{{index precedence}}
-When mixing these Boolean operators with arithmetic and other
-operators, it is not always obvious when parentheses are needed. In
-practice, you can usually get by with knowing that of the operators we
-have seen so far, `||` has the lowest precedence, then comes `&&`,
-then the comparison operators (`>`, `==`, and so on), and then the
-rest. This order has been chosen such that, in typical expressions
-like the following one, as few parentheses as possible are necessary:
+When mixing these Boolean operators with arithmetic and other operators, it is not always obvious when parentheses are needed. In practice, you can usually get by with knowing that of the operators we have seen so far, `||` has the lowest precedence, then comes `&&`, then the comparison operators (`>`, `==`, and so on), and then the rest. This order has been chosen such that, in typical expressions like the following one, as few parentheses as possible are necessary:
```
1 + 1 == 2 && 10 * 10 > 50
@@ -507,9 +336,7 @@ like the following one, as few parentheses as possible are necessary:
{{index "conditional execution", "ternary operator", "?: operator", "conditional operator", "colon character", "question mark"}}
-The last logical operator I will discuss is not unary, not binary, but
-_ternary_, operating on three values. It is written with a question
-mark and a colon, like this:
+The last logical operator I will discuss is not unary, not binary, but _ternary_, operating on three values. It is written with a question mark and a colon, like this:
```
console.log(true ? 1 : 2);
@@ -518,36 +345,23 @@ console.log(false ? 1 : 2);
// → 2
```
-This one is called the _conditional_ operator (or sometimes just
-the _ternary_ operator since it is the only such operator in the
-language). The value on the left of the question mark "picks" which of
-the other two values will come out. When it is true, it chooses the
-middle value, and when it is false, it chooses the value on the right.
+This one is called the _conditional_ operator (or sometimes just the _ternary_ operator since it is the only such operator in the language). The value on the left of the question mark "picks" which of the other two values will come out. When it is true, it chooses the middle value, and when it is false, it chooses the value on the right.
## Empty values
{{index undefined, null}}
-There are two special values, written `null` and `undefined`, that are
-used to denote the absence of a _meaningful_ value. They are
-themselves values, but they carry no information.
+There are two special values, written `null` and `undefined`, that are used to denote the absence of a _meaningful_ value. They are themselves values, but they carry no information.
-Many operations in the language that don't produce a meaningful value
-(you'll see some later) yield `undefined` simply because they have to
-yield _some_ value.
+Many operations in the language that don't produce a meaningful value (you'll see some later) yield `undefined` simply because they have to yield _some_ value.
-The difference in meaning between `undefined` and `null` is an accident
-of JavaScript's design, and it doesn't matter most of the time. In cases
-where you actually have to concern yourself with these values, I
-recommend treating them as mostly interchangeable.
+The difference in meaning between `undefined` and `null` is an accident of JavaScript's design, and it doesn't matter most of the time. In cases where you actually have to concern yourself with these values, I recommend treating them as mostly interchangeable.
## Automatic type conversion
{{index NaN, "type coercion"}}
-In the Introduction, I mentioned that JavaScript goes out of its way
-to accept almost any program you give it, even programs that do odd
-things. This is nicely demonstrated by the following expressions:
+In the Introduction, I mentioned that JavaScript goes out of its way to accept almost any program you give it, even programs that do odd things. This is nicely demonstrated by the following expressions:
```
console.log(8 * null)
@@ -564,33 +378,15 @@ console.log(false == 0)
{{index "+ operator", arithmetic, "* operator", "- operator"}}
-When an operator is applied to the "wrong" type of value, JavaScript
-will quietly convert that value to the type it needs, using a set of
-rules that often aren't what you want or expect. This is called
-_((type coercion))_. The `null` in the first expression becomes `0`,
-and the `"5"` in the second expression becomes `5` (from string to
-number). Yet in the third expression, `+` tries string concatenation
-before numeric addition, so the `1` is converted to `"1"` (from number
-to string).
+When an operator is applied to the "wrong" type of value, JavaScript will quietly convert that value to the type it needs, using a set of rules that often aren't what you want or expect. This is called _((type coercion))_. The `null` in the first expression becomes `0`, and the `"5"` in the second expression becomes `5` (from string to number). Yet in the third expression, `+` tries string concatenation before numeric addition, so the `1` is converted to `"1"` (from number to string).
{{index "type coercion", [number, "conversion to"]}}
-When something that doesn't map to a number in an obvious way (such as
-`"five"` or `undefined`) is converted to a number, you get the value
-`NaN`. Further arithmetic operations on `NaN` keep producing `NaN`, so
-if you find yourself getting one of those in an unexpected place, look
-for accidental type conversions.
+When something that doesn't map to a number in an obvious way (such as `"five"` or `undefined`) is converted to a number, you get the value `NaN`. Further arithmetic operations on `NaN` keep producing `NaN`, so if you find yourself getting one of those in an unexpected place, look for accidental type conversions.
{{index null, undefined, [comparison, "of undefined values"], "== operator"}}
-When comparing values of the same type using `==`, the outcome is easy
-to predict: you should get true when both values are the same, except
-in the case of `NaN`. But when the types differ, JavaScript uses a
-complicated and confusing set of rules to determine what to do. In
-most cases, it just tries to convert one of the values to the other
-value's type. However, when `null` or `undefined` occurs on either
-side of the operator, it produces true only if both sides are one of
-`null` or `undefined`.
+When comparing values of the same type using `==`, the outcome is easy to predict: you should get true when both values are the same, except in the case of `NaN`. But when the types differ, JavaScript uses a complicated and confusing set of rules to determine what to do. In most cases, it just tries to convert one of the values to the other value's type. However, when `null` or `undefined` occurs on either side of the operator, it produces true only if both sides are one of `null` or `undefined`.
```
console.log(null == undefined);
@@ -599,41 +395,23 @@ console.log(null == 0);
// → false
```
-That behavior is often useful. When you want to test whether a value
-has a real value instead of `null` or `undefined`, you can compare it
-to `null` with the `==` (or `!=`) operator.
+That behavior is often useful. When you want to test whether a value has a real value instead of `null` or `undefined`, you can compare it to `null` with the `==` (or `!=`) operator.
{{index "type coercion", [Boolean, "conversion to"], "=== operator", "!== operator", comparison}}
-But what if you want to test whether something refers to the precise
-value `false`? Expressions like `0 == false` and `"" == false` are
-also true because of automatic type conversion. When you do _not_ want
-any type conversions to happen, there are two additional operators:
-`===` and `!==`. The first tests whether a value is _precisely_ equal
-to the other, and the second tests whether it is not precisely equal.
-So `"" === false` is false as expected.
+But what if you want to test whether something refers to the precise value `false`? Expressions like `0 == false` and `"" == false` are also true because of automatic type conversion. When you do _not_ want any type conversions to happen, there are two additional operators: `===` and `!==`. The first tests whether a value is _precisely_ equal to the other, and the second tests whether it is not precisely equal. So `"" === false` is false as expected.
-I recommend using the three-character comparison operators defensively to
-prevent unexpected type conversions from tripping you up. But when you're
-certain the types on both sides will be the same, there is no problem with
-using the shorter operators.
+I recommend using the three-character comparison operators defensively to prevent unexpected type conversions from tripping you up. But when you're certain the types on both sides will be the same, there is no problem with using the shorter operators.
### Short-circuiting of logical operators
{{index "type coercion", [Boolean, "conversion to"], operator}}
-The logical operators `&&` and `||` handle values of different types
-in a peculiar way. They will convert the value on their left side to
-Boolean type in order to decide what to do, but depending on the
-operator and the result of that conversion, they will return either the
-_original_ left-hand value or the right-hand value.
+The logical operators `&&` and `||` handle values of different types in a peculiar way. They will convert the value on their left side to Boolean type in order to decide what to do, but depending on the operator and the result of that conversion, they will return either the _original_ left-hand value or the right-hand value.
{{index "|| operator"}}
-The `||` operator, for example, will return the value to its left when
-that can be converted to true and will return the value on its right
-otherwise. This has the expected effect when the values are Boolean
-and does something analogous for values of other types.
+The `||` operator, for example, will return the value to its left when that can be converted to true and will return the value on its right otherwise. This has the expected effect when the values are Boolean and does something analogous for values of other types.
```
console.log(null || "user")
@@ -644,47 +422,22 @@ console.log("Agnes" || "user")
{{index "default value"}}
-We can use this functionality as a way to fall back on a default
-value. If you have a value that might be empty, you can put `||` after
-it with a replacement value. If the initial value can be converted to
-false, you'll get the replacement instead. The rules for converting
-strings and numbers to Boolean values state that `0`, `NaN`, and the
-empty string (`""`) count as `false`, while all the other values count
-as `true`. So `0 || -1` produces `-1`, and `"" || "!?"` yields `"!?"`.
+We can use this functionality as a way to fall back on a default value. If you have a value that might be empty, you can put `||` after it with a replacement value. If the initial value can be converted to false, you'll get the replacement instead. The rules for converting strings and numbers to Boolean values state that `0`, `NaN`, and the empty string (`""`) count as `false`, while all the other values count as `true`. So `0 || -1` produces `-1`, and `"" || "!?"` yields `"!?"`.
{{index "&& operator"}}
-The `&&` operator works similarly but the other way around. When the
-value to its left is something that converts to false, it returns that
-value, and otherwise it returns the value on its right.
+The `&&` operator works similarly but the other way around. When the value to its left is something that converts to false, it returns that value, and otherwise it returns the value on its right.
-Another important property of these two operators is that the part to
-their right is evaluated only when necessary. In the case of `true ||
-X`, no matter what `X` is—even if it's a piece of program that does
-something _terrible_—the result will be true, and `X` is never
-evaluated. The same goes for `false && X`, which is false and will
-ignore `X`. This is called _((short-circuit evaluation))_.
+Another important property of these two operators is that the part to their right is evaluated only when necessary. In the case of `true || X`, no matter what `X` is—even if it's a piece of program that does something _terrible_—the result will be true, and `X` is never evaluated. The same goes for `false && X`, which is false and will ignore `X`. This is called _((short-circuit evaluation))_.
{{index "ternary operator", "?: operator", "conditional operator"}}
-The conditional operator works in a similar way. Of the second and
-third values, only the one that is selected is evaluated.
+The conditional operator works in a similar way. Of the second and third values, only the one that is selected is evaluated.
## Summary
-We looked at four types of JavaScript values in this chapter: numbers,
-strings, Booleans, and undefined values.
-
-Such values are created by typing in their name (`true`, `null`) or
-value (`13`, `"abc"`). You can combine and transform values with
-operators. We saw binary operators for arithmetic (`+`, `-`, `*`, `/`,
-and `%`), string concatenation (`+`), comparison (`==`, `!=`, `===`,
-`!==`, `<`, `>`, `<=`, `>=`), and logic (`&&`, `||`), as well as
-several unary operators (`-` to negate a number, `!` to negate
-logically, and `typeof` to find a value's type) and a ternary operator
-(`?:`) to pick one of two values based on a third value.
-
-This gives you enough information to use JavaScript as a pocket
-calculator but not much more. The [next
-chapter](program_structure) will start tying
-these expressions together into basic programs.
+We looked at four types of JavaScript values in this chapter: numbers, strings, Booleans, and undefined values.
+
+Such values are created by typing in their name (`true`, `null`) or value (`13`, `"abc"`). You can combine and transform values with operators. We saw binary operators for arithmetic (`+`, `-`, `*`, `/`, and `%`), string concatenation (`+`), comparison (`==`, `!=`, `===`, `!==`, `<`, `>`, `<=`, `>=`), and logic (`&&`, `||`), as well as several unary operators (`-` to negate a number, `!` to negate logically, and `typeof` to find a value's type) and a ternary operator (`?:`) to pick one of two values based on a third value.
+
+This gives you enough information to use JavaScript as a pocket calculator but not much more. The [next chapter](program_structure) will start tying these expressions together into basic programs.
diff --git a/02_program_structure.md b/02_program_structure.md
index 89ad72485..6c41055c6 100644
--- a/02_program_structure.md
+++ b/02_program_structure.md
@@ -2,10 +2,7 @@
{{quote {author: "_why", title: "Why's (Poignant) Guide to Ruby", chapter: true}
-And my heart glows bright red under my filmy, translucent skin and
-they have to administer 10cc of JavaScript to get me to come back. (I
-respond well to toxins in the blood.) Man, that stuff will kick the
-peaches right out your gills!
+And my heart glows bright red under my filmy, translucent skin and they have to administer 10cc of JavaScript to get me to come back. (I respond well to toxins in the blood.) Man, that stuff will kick the peaches right out your gills!
quote}}
@@ -13,82 +10,47 @@ quote}}
{{figure {url: "img/chapter_picture_2.jpg", alt: "Picture of tentacles holding objects", chapter: framed}}}
-In this chapter, we will start to do things that can actually be called
-_programming_. We will expand our command of the JavaScript language
-beyond the nouns and sentence fragments we've seen so far, to the
-point where we can express meaningful prose.
+In this chapter, we will start to do things that can actually be called _programming_. We will expand our command of the JavaScript language beyond the nouns and sentence fragments we've seen so far, to the point where we can express meaningful prose.
## Expressions and statements
{{index grammar, [syntax, expression], [code, "structure of"], grammar, [JavaScript, syntax]}}
-In [Chapter ?](values), we made values and applied operators to them
-to get new values. Creating values like this is the main substance of
-any JavaScript program. But that substance has to be framed in a
-larger structure to be useful. So that's what we'll cover next.
+In [Chapter ?](values), we made values and applied operators to them to get new values. Creating values like this is the main substance of any JavaScript program. But that substance has to be framed in a larger structure to be useful. So that's what we'll cover next.
{{index "literal expression", [parentheses, expression]}}
-A fragment of code that produces a value is called an
-_((expression))_. Every value that is written literally (such as `22`
-or `"psychoanalysis"`) is an expression. An expression between
-parentheses is also an expression, as is a ((binary operator))
-applied to two expressions or a ((unary operator)) applied to one.
+A fragment of code that produces a value is called an _((expression))_. Every value that is written literally (such as `22` or `"psychoanalysis"`) is an expression. An expression between parentheses is also an expression, as is a ((binary operator)) applied to two expressions or a ((unary operator)) applied to one.
{{index [nesting, "of expressions"], "human language"}}
-This shows part of the beauty of a language-based interface.
-Expressions can contain other expressions in a way similar to how subsentences in human languages are nested—a subsentence can
-contain its own subsentences, and so on. This allows us to build
-expressions that describe arbitrarily complex computations.
+This shows part of the beauty of a language-based interface. Expressions can contain other expressions in a way similar to how subsentences in human languages are nested—a subsentence can contain its own subsentences, and so on. This allows us to build expressions that describe arbitrarily complex computations.
{{index statement, semicolon, program}}
-If an expression corresponds to a sentence fragment, a JavaScript
-_statement_ corresponds to a full sentence. A program is a list of
-statements.
+If an expression corresponds to a sentence fragment, a JavaScript _statement_ corresponds to a full sentence. A program is a list of statements.
{{index [syntax, statement]}}
-The simplest kind of statement is an expression with a semicolon after
-it. This is a program:
+The simplest kind of statement is an expression with a semicolon after it. This is a program:
```
1;
!false;
```
-It is a useless program, though. An ((expression)) can be content to
-just produce a value, which can then be used by the enclosing code. A
-((statement)) stands on its own, so it amounts to something only if it
-affects the world. It could display something on the screen—that
-counts as changing the world—or it could change the internal state of
-the machine in a way that will affect the statements that come after
-it. These changes are called _((side effect))s_. The statements in the
-previous example just produce the values `1` and `true` and then
-immediately throw them away. This leaves no impression on the world at
-all. When you run this program, nothing observable happens.
+It is a useless program, though. An ((expression)) can be content to just produce a value, which can then be used by the enclosing code. A ((statement)) stands on its own, so it amounts to something only if it affects the world. It could display something on the screen—that counts as changing the world—or it could change the internal state of the machine in a way that will affect the statements that come after it. These changes are called _((side effect))s_. The statements in the previous example just produce the values `1` and `true` and then immediately throw them away. This leaves no impression on the world at all. When you run this program, nothing observable happens.
{{index "programming style", "automatic semicolon insertion", semicolon}}
-In some cases, JavaScript allows you to omit the semicolon at the end
-of a statement. In other cases, it has to be there, or the next
-((line)) will be treated as part of the same statement. The rules for
-when it can be safely omitted are somewhat complex and error-prone. So
-in this book, every statement that needs a semicolon will always get
-one. I recommend you do the same, at least until you've learned more
-about the subtleties of missing semicolons.
+In some cases, JavaScript allows you to omit the semicolon at the end of a statement. In other cases, it has to be there, or the next ((line)) will be treated as part of the same statement. The rules for when it can be safely omitted are somewhat complex and error-prone. So in this book, every statement that needs a semicolon will always get one. I recommend you do the same, at least until you've learned more about the subtleties of missing semicolons.
## Bindings
{{indexsee variable, binding}}
{{index [syntax, statement], [binding, definition], "side effect", [memory, organization], [state, in binding]}}
-How does a program keep an internal state? How does it remember
-things? We have seen how to produce new values from old values, but
-this does not change the old values, and the new value has to be
-immediately used or it will dissipate again. To catch and hold values,
-JavaScript provides a thing called a _binding_, or _variable_:
+How does a program keep an internal state? How does it remember things? We have seen how to produce new values from old values, but this does not change the old values, and the new value has to be immediately used or it will dissipate again. To catch and hold values, JavaScript provides a thing called a _binding_, or _variable_:
```
let caught = 5 * 5;
@@ -96,17 +58,11 @@ let caught = 5 * 5;
{{index "let keyword"}}
-That's a second kind of ((statement)). The special word
-(_((keyword))_) `let` indicates that this sentence is going to define
-a binding. It is followed by the name of the binding and, if we want
-to immediately give it a value, by an `=` operator and an expression.
+That's a second kind of ((statement)). The special word (_((keyword))_) `let` indicates that this sentence is going to define a binding. It is followed by the name of the binding and, if we want to immediately give it a value, by an `=` operator and an expression.
-The previous statement creates a binding called `caught` and uses it
-to grab hold of the number that is produced by multiplying 5 by 5.
+The previous statement creates a binding called `caught` and uses it to grab hold of the number that is produced by multiplying 5 by 5.
-After a binding has been defined, its name can be used as an
-((expression)). The value of such an expression is the value the
-binding currently holds. Here's an example:
+After a binding has been defined, its name can be used as an ((expression)). The value of such an expression is the value the binding currently holds. Here's an example:
```
let ten = 10;
@@ -116,10 +72,7 @@ console.log(ten * ten);
{{index "= operator", assignment, [binding, assignment]}}
-When a binding points at a value, that does not mean it is tied to
-that value forever. The `=` operator can be used at any time on
-existing bindings to disconnect them from their current value and have
-them point to a new one.
+When a binding points at a value, that does not mean it is tied to that value forever. The `=` operator can be used at any time on existing bindings to disconnect them from their current value and have them point to a new one.
```
let mood = "light";
@@ -132,15 +85,9 @@ console.log(mood);
{{index [binding, "model of"], "tentacle (analogy)"}}
-You should imagine bindings as tentacles, rather than boxes. They do
-not _contain_ values; they _grasp_ them—two bindings can refer to the
-same value. A program can access only the values that it still has a
-reference to. When you need to remember something, you grow a tentacle
-to hold on to it or you reattach one of your existing tentacles to it.
+You should imagine bindings as tentacles, rather than boxes. They do not _contain_ values; they _grasp_ them—two bindings can refer to the same value. A program can access only the values that it still has a reference to. When you need to remember something, you grow a tentacle to hold on to it or you reattach one of your existing tentacles to it.
-Let's look at another example. To remember the number of dollars that
-Luigi still owes you, you create a binding. And then when he pays back
-$35, you give this binding a new value.
+Let's look at another example. To remember the number of dollars that Luigi still owes you, you create a binding. And then when he pays back $35, you give this binding a new value.
```
let luigisDebt = 140;
@@ -151,14 +98,11 @@ console.log(luigisDebt);
{{index undefined}}
-When you define a binding without giving it a value, the tentacle has
-nothing to grasp, so it ends in thin air. If you ask for the value of
-an empty binding, you'll get the value `undefined`.
+When you define a binding without giving it a value, the tentacle has nothing to grasp, so it ends in thin air. If you ask for the value of an empty binding, you'll get the value `undefined`.
{{index "let keyword"}}
-A single `let` statement may define multiple bindings. The
-definitions must be separated by commas.
+A single `let` statement may define multiple bindings. The definitions must be separated by commas.
```
let one = 1, two = 2;
@@ -166,8 +110,7 @@ console.log(one + two);
// → 3
```
-The words `var` and `const` can also be used to create bindings, in a
-way similar to `let`.
+The words `var` and `const` can also be used to create bindings, in a way similar to `let`.
```
var name = "Ayda";
@@ -178,35 +121,21 @@ console.log(greeting + name);
{{index "var keyword"}}
-The first, `var` (short for "variable"), is the way bindings were
-declared in pre-2015 JavaScript. I'll get back to the precise way it
-differs from `let` in the [next chapter](functions). For now,
-remember that it mostly does the same thing, but we'll rarely use it
-in this book because it has some confusing properties.
+The first, `var` (short for "variable"), is the way bindings were declared in pre-2015 JavaScript. I'll get back to the precise way it differs from `let` in the [next chapter](functions). For now, remember that it mostly does the same thing, but we'll rarely use it in this book because it has some confusing properties.
{{index "const keyword", naming}}
-The word `const` stands for _((constant))_. It defines a constant
-binding, which points at the same value for as long as it lives. This
-is useful for bindings that give a name to a value so that you can
-easily refer to it later.
+The word `const` stands for _((constant))_. It defines a constant binding, which points at the same value for as long as it lives. This is useful for bindings that give a name to a value so that you can easily refer to it later.
## Binding names
{{index "underscore character", "dollar sign", [binding, naming]}}
-Binding names can be any word. Digits can be part of binding
-names—`catch22` is a valid name, for example—but the name must not
-start with a digit. A binding name may include dollar signs (`$`) or
-underscores (`_`) but no other punctuation or special characters.
+Binding names can be any word. Digits can be part of binding names—`catch22` is a valid name, for example—but the name must not start with a digit. A binding name may include dollar signs (`$`) or underscores (`_`) but no other punctuation or special characters.
{{index [syntax, identifier], "implements (reserved word)", "interface (reserved word)", "package (reserved word)", "private (reserved word)", "protected (reserved word)", "public (reserved word)", "static (reserved word)", "void operator", "yield (reserved word)", "enum (reserved word)", "reserved word", [binding, naming]}}
-Words with a special meaning, such as `let`, are _((keyword))s_, and
-they may not be used as binding names. There are also a number of
-words that are "reserved for use" in ((future)) versions of
-JavaScript, which also can't be used as binding names. The full list
-of keywords and reserved words is rather long.
+Words with a special meaning, such as `let`, are _((keyword))s_, and they may not be used as binding names. There are also a number of words that are "reserved for use" in ((future)) versions of JavaScript, which also can't be used as binding names. The full list of keywords and reserved words is rather long.
```{lang: "text/plain"}
break case catch class const continue debugger default
@@ -218,21 +147,13 @@ switch this throw true try typeof var void while with yield
{{index [syntax, error]}}
-Don't worry about memorizing this list. When creating a binding produces
-an unexpected syntax error, see whether you're trying to define a
-reserved word.
+Don't worry about memorizing this list. When creating a binding produces an unexpected syntax error, see whether you're trying to define a reserved word.
## The environment
{{index "standard environment", [browser, environment]}}
-The collection of bindings and their values that exist at a given time
-is called the _((environment))_. When a program starts up, this
-environment is not empty. It always contains bindings that are part of
-the language ((standard)), and most of the time, it also has bindings
-that provide ways to interact with the surrounding system. For
-example, in a browser, there are functions to interact with the
-currently loaded website and to read ((mouse)) and ((keyboard)) input.
+The collection of bindings and their values that exist at a given time is called the _((environment))_. When a program starts up, this environment is not empty. It always contains bindings that are part of the language ((standard)), and most of the time, it also has bindings that provide ways to interact with the surrounding system. For example, in a browser, there are functions to interact with the currently loaded website and to read ((mouse)) and ((keyboard)) input.
## Functions
@@ -241,12 +162,7 @@ currently loaded website and to read ((mouse)) and ((keyboard)) input.
{{indexsee "calling (of functions)", [function, application]}}
{{index output, function, [function, application], [browser, environment]}}
-A lot of the values provided in the default environment have the type
-_((function))_. A function is a piece of program wrapped in a value.
-Such values can be _applied_ in order to run the wrapped program. For
-example, in a browser environment, the binding `prompt` holds a
-function that shows a little ((dialog box)) asking for user input. It
-is used like this:
+A lot of the values provided in the default environment have the type _((function))_. A function is a piece of program wrapped in a value. Such values can be _applied_ in order to run the wrapped program. For example, in a browser environment, the binding `prompt` holds a function that shows a little ((dialog box)) asking for user input. It is used like this:
```
prompt("Enter passcode");
@@ -256,38 +172,19 @@ prompt("Enter passcode");
{{index parameter, [function, application], [parentheses, arguments]}}
-Executing a function is called _invoking_, _calling_, or _applying_
-it. You can call a function by putting parentheses after an
-expression that produces a function value. Usually you'll directly use
-the name of the binding that holds the function. The values between
-the parentheses are given to the program inside the function. In the
-example, the `prompt` function uses the string that we give it as the
-text to show in the dialog box. Values given to functions are called
-_((argument))s_. Different functions might need a different number or
-different types of arguments.
+Executing a function is called _invoking_, _calling_, or _applying_ it. You can call a function by putting parentheses after an expression that produces a function value. Usually you'll directly use the name of the binding that holds the function. The values between the parentheses are given to the program inside the function. In the example, the `prompt` function uses the string that we give it as the text to show in the dialog box. Values given to functions are called _((argument))s_. Different functions might need a different number or different types of arguments.
-The `prompt` function isn't used much in modern web programming,
-mostly because you have no control over the way the resulting dialog
-looks, but can be helpful in toy programs and experiments.
+The `prompt` function isn't used much in modern web programming, mostly because you have no control over the way the resulting dialog looks, but can be helpful in toy programs and experiments.
## The console.log function
{{index "JavaScript console", "developer tools", "Node.js", "console.log", output, [browser, environment]}}
-In the examples, I used `console.log` to output values. Most JavaScript
-systems (including all modern web browsers and Node.js) provide a
-`console.log` function that writes out its arguments to _some_ text
-output device. In browsers, the output lands in the ((JavaScript
-console)). This part of the browser interface is hidden by default,
-but most browsers open it when you press F12 or, on a Mac, [command]{keyname}-[option]{keyname}-I.
-If that does not work, search through the menus for an item named Developer
-Tools or similar.
+In the examples, I used `console.log` to output values. Most JavaScript systems (including all modern web browsers and Node.js) provide a `console.log` function that writes out its arguments to _some_ text output device. In browsers, the output lands in the ((JavaScript console)). This part of the browser interface is hidden by default, but most browsers open it when you press F12 or, on a Mac, [command]{keyname}-[option]{keyname}-I. If that does not work, search through the menus for an item named Developer Tools or similar.
{{if interactive
-When running the examples (or your own code) on the pages of this
-book, `console.log` output will be shown after the example, instead of
-in the browser's JavaScript console.
+When running the examples (or your own code) on the pages of this book, `console.log` output will be shown after the example, instead of in the browser's JavaScript console.
```
let x = 30;
@@ -299,23 +196,14 @@ if}}
{{index [object, property], [property, access]}}
-Though binding names cannot contain ((period character))s,
-`console.log` does have one. This is because `console.log` isn't a
-simple binding. It is actually an expression that retrieves the `log`
-property from the value held by the `console` binding. We'll
-find out exactly what this means in [Chapter ?](data#properties).
+Though binding names cannot contain ((period character))s, `console.log` does have one. This is because `console.log` isn't a simple binding. It is actually an expression that retrieves the `log` property from the value held by the `console` binding. We'll find out exactly what this means in [Chapter ?](data#properties).
{{id return_values}}
## Return values
{{index [comparison, "of numbers"], "return value", "Math.max function", maximum}}
-Showing a dialog box or writing text to the screen is a _((side
-effect))_. A lot of functions are useful because of the side effects
-they produce. Functions may also produce values, in which case they
-don't need to have a side effect to be useful. For example, the
-function `Math.max` takes any amount of number arguments and gives
-back the greatest.
+Showing a dialog box or writing text to the screen is a _((side effect))_. A lot of functions are useful because of the side effects they produce. Functions may also produce values, in which case they don't need to have a side effect to be useful. For example, the function `Math.max` takes any amount of number arguments and gives back the greatest.
```
console.log(Math.max(2, 4));
@@ -324,29 +212,20 @@ console.log(Math.max(2, 4));
{{index [function, application], minimum, "Math.min function"}}
-When a function produces a value, it is said to _return_ that value.
-Anything that produces a value is an ((expression)) in JavaScript,
-which means function calls can be used within larger expressions. Here
-a call to `Math.min`, which is the opposite of `Math.max`, is used as
-part of a plus expression:
+When a function produces a value, it is said to _return_ that value. Anything that produces a value is an ((expression)) in JavaScript, which means function calls can be used within larger expressions. Here a call to `Math.min`, which is the opposite of `Math.max`, is used as part of a plus expression:
```
console.log(Math.min(2, 4) + 100);
// → 102
```
-The [next chapter](functions) explains how to write your own
-functions.
+The [next chapter](functions) explains how to write your own functions.
## Control flow
{{index "execution order", program, "control flow"}}
-When your program contains more than one ((statement)), the statements
-are executed as if they are a story, from top to bottom. This example
-program has two statements. The first one asks the user for a number,
-and the second, which is executed after the first, shows the
-((square)) of that number.
+When your program contains more than one ((statement)), the statements are executed as if they are a story, from top to bottom. This example program has two statements. The first one asks the user for a number, and the second, which is executed after the first, shows the ((square)) of that number.
```
let theNumber = Number(prompt("Pick a number"));
@@ -356,13 +235,9 @@ console.log("Your number is the square root of " +
{{index [number, "conversion to"], "type coercion", "Number function", "String function", "Boolean function", [Boolean, "conversion to"]}}
-The function `Number` converts a value to a number. We need that
-conversion because the result of `prompt` is a string value, and we
-want a number. There are similar functions called `String` and
-`Boolean` that convert values to those types.
+The function `Number` converts a value to a number. We need that conversion because the result of `prompt` is a string value, and we want a number. There are similar functions called `String` and `Boolean` that convert values to those types.
-Here is the rather trivial schematic representation of straight-line
-control flow:
+Here is the rather trivial schematic representation of straight-line control flow:
{{figure {url: "img/controlflow-straight.svg", alt: "Trivial control flow", width: "4cm"}}}
@@ -370,19 +245,13 @@ control flow:
{{index Boolean, ["control flow", conditional]}}
-Not all programs are straight roads. We may, for example, want to
-create a branching road, where the program takes the proper branch
-based on the situation at hand. This is called _((conditional
-execution))_.
+Not all programs are straight roads. We may, for example, want to create a branching road, where the program takes the proper branch based on the situation at hand. This is called _((conditional execution))_.
{{figure {url: "img/controlflow-if.svg", alt: "Conditional control flow",width: "4cm"}}}
{{index [syntax, statement], "Number function", "if keyword"}}
-Conditional execution is created with the `if` keyword in JavaScript.
-In the simple case, we want some code to be executed if, and only if,
-a certain condition holds. We might, for example, want to show the
-square of the input only if the input is actually a number.
+Conditional execution is created with the `if` keyword in JavaScript. In the simple case, we want some code to be executed if, and only if, a certain condition holds. We might, for example, want to show the square of the input only if the input is actually a number.
```{test: wrap}
let theNumber = Number(prompt("Pick a number"));
@@ -396,28 +265,15 @@ With this modification, if you enter "parrot", no output is shown.
{{index [parentheses, statement]}}
-The `if` keyword executes or skips a statement depending on the value
-of a Boolean expression. The deciding expression is written after the
-keyword, between parentheses, followed by the statement to
-execute.
+The `if` keyword executes or skips a statement depending on the value of a Boolean expression. The deciding expression is written after the keyword, between parentheses, followed by the statement to execute.
{{index "Number.isNaN function"}}
-The `Number.isNaN` function is a standard JavaScript function that
-returns `true` only if the argument it is given is `NaN`. The `Number`
-function happens to return `NaN` when you give it a string that
-doesn't represent a valid number. Thus, the condition translates to
-"unless `theNumber` is not-a-number, do this".
+The `Number.isNaN` function is a standard JavaScript function that returns `true` only if the argument it is given is `NaN`. The `Number` function happens to return `NaN` when you give it a string that doesn't represent a valid number. Thus, the condition translates to "unless `theNumber` is not-a-number, do this".
{{index grouping, "{} (block)", [braces, "block"]}}
-The statement after the `if` is wrapped in braces (`{` and
-`}`) in this example. The braces can be used to group any number of
-statements into a single statement, called a _((block))_. You could
-also have omitted them in this case, since they hold only a single
-statement, but to avoid having to think about whether they are needed, most JavaScript programmers use them in every wrapped
-statement like this. We'll mostly follow that convention in this book,
-except for the occasional one-liner.
+The statement after the `if` is wrapped in braces (`{` and `}`) in this example. The braces can be used to group any number of statements into a single statement, called a _((block))_. You could also have omitted them in this case, since they hold only a single statement, but to avoid having to think about whether they are needed, most JavaScript programmers use them in every wrapped statement like this. We'll mostly follow that convention in this book, except for the occasional one-liner.
```
if (1 + 1 == 2) console.log("It's true");
@@ -426,10 +282,7 @@ if (1 + 1 == 2) console.log("It's true");
{{index "else keyword"}}
-You often won't just have code that executes when a condition holds
-true, but also code that handles the other case. This alternate path
-is represented by the second arrow in the diagram. You can use the `else` keyword, together with `if`, to create two separate, alternative
-execution paths.
+You often won't just have code that executes when a condition holds true, but also code that handles the other case. This alternate path is represented by the second arrow in the diagram. You can use the `else` keyword, together with `if`, to create two separate, alternative execution paths.
```{test: wrap}
let theNumber = Number(prompt("Pick a number"));
@@ -443,8 +296,7 @@ if (!Number.isNaN(theNumber)) {
{{index ["if keyword", chaining]}}
-If you have more than two paths to choose from, you can "chain" multiple `if`/`else`
-pairs together. Here's an example:
+If you have more than two paths to choose from, you can "chain" multiple `if`/`else` pairs together. Here's an example:
```
let num = Number(prompt("Pick a number"));
@@ -458,12 +310,7 @@ if (num < 10) {
}
```
-The program will first check whether `num` is less than 10. If it is,
-it chooses that branch, shows `"Small"`, and is done. If it isn't, it
-takes the `else` branch, which itself contains a second `if`. If the
-second condition (`< 100`) holds, that means the number is at least 10
-but below 100, and `"Medium"` is shown. If it doesn't, the second and
-last `else` branch is chosen.
+The program will first check whether `num` is less than 10. If it is, it chooses that branch, shows `"Small"`, and is done. If it isn't, it takes the `else` branch, which itself contains a second `if`. If the second condition (`< 100`) holds, that means the number is at least 10 but below 100, and `"Medium"` is shown. If it doesn't, the second and last `else` branch is chosen.
The schema for this program looks something like this:
@@ -472,8 +319,7 @@ The schema for this program looks something like this:
{{id loops}}
## while and do loops
-Consider a program that outputs all ((even number))s from 0 to 12. One
-way to write this is as follows:
+Consider a program that outputs all ((even number))s from 0 to 12. One way to write this is as follows:
```
console.log(0);
@@ -487,20 +333,13 @@ console.log(12);
{{index ["control flow", loop]}}
-That works, but the idea of writing a program is to make something
-_less_ work, not more. If we needed all even numbers less than 1,000,
-this approach would be unworkable. What we need is a way to run a
-piece of code multiple times. This form of control flow is called a
-_((loop))_.
+That works, but the idea of writing a program is to make something _less_ work, not more. If we needed all even numbers less than 1,000, this approach would be unworkable. What we need is a way to run a piece of code multiple times. This form of control flow is called a _((loop))_.
{{figure {url: "img/controlflow-loop.svg", alt: "Loop control flow",width: "4cm"}}}
{{index [syntax, statement], "counter variable"}}
-Looping control flow allows us to go back to some point in the program
-where we were before and repeat it with our current program state. If
-we combine this with a binding that counts, we can do something like
-this:
+Looping control flow allows us to go back to some point in the program where we were before and repeat it with our current program state. If we combine this with a binding that counts, we can do something like this:
```
let number = 0;
@@ -515,28 +354,15 @@ while (number <= 12) {
{{index "while loop", Boolean, [parentheses, statement]}}
-A ((statement)) starting with the keyword `while` creates a loop. The
-word `while` is followed by an ((expression)) in parentheses and
-then a statement, much like `if`. The loop keeps entering that
-statement as long as the expression produces a value that gives `true`
-when converted to Boolean.
+A ((statement)) starting with the keyword `while` creates a loop. The word `while` is followed by an ((expression)) in parentheses and then a statement, much like `if`. The loop keeps entering that statement as long as the expression produces a value that gives `true` when converted to Boolean.
{{index [state, in binding], [binding, as state]}}
-The `number` binding demonstrates the way a ((binding)) can track the
-progress of a program. Every time the loop repeats, `number` gets a
-value that is 2 more than its previous value. At the beginning of
-every repetition, it is compared with the number 12 to decide whether
-the program's work is finished.
+The `number` binding demonstrates the way a ((binding)) can track the progress of a program. Every time the loop repeats, `number` gets a value that is 2 more than its previous value. At the beginning of every repetition, it is compared with the number 12 to decide whether the program's work is finished.
{{index exponentiation}}
-As an example that actually does something useful, we can now write a
-program that calculates and shows the value of 2^10^ (2 to the 10th
-power). We use two bindings: one to keep track of our result and one
-to count how often we have multiplied this result by 2. The loop tests
-whether the second binding has reached 10 yet and, if not, updates
-both bindings.
+As an example that actually does something useful, we can now write a program that calculates and shows the value of 2^10^ (2 to the 10th power). We use two bindings: one to keep track of our result and one to count how often we have multiplied this result by 2. The loop tests whether the second binding has reached 10 yet and, if not, updates both bindings.
```
let result = 1;
@@ -549,18 +375,11 @@ console.log(result);
// → 1024
```
-The counter could also have started at `1` and checked for `<= 10`,
-but for reasons that will become apparent in [Chapter
-?](data#array_indexing), it is a good idea to get used to
-counting from 0.
+The counter could also have started at `1` and checked for `<= 10`, but for reasons that will become apparent in [Chapter ?](data#array_indexing), it is a good idea to get used to counting from 0.
{{index "loop body", "do loop", ["control flow", loop]}}
-A `do` loop is a control structure similar to a `while` loop. It
-differs only on one point: a `do` loop always executes its body at
-least once, and it starts testing whether it should stop only after
-that first execution. To reflect this, the test appears after the body
-of the loop.
+A `do` loop is a control structure similar to a `while` loop. It differs only on one point: a `do` loop always executes its body at least once, and it starts testing whether it should stop only after that first execution. To reflect this, the test appears after the body of the loop.
```
let yourName;
@@ -572,30 +391,15 @@ console.log(yourName);
{{index [Boolean, "conversion to"], "! operator"}}
-This program will force you to enter a name. It will ask again and
-again until it gets something that is not an empty string. Applying
-the `!` operator will convert a value to Boolean type before negating
-it, and all strings except `""` convert to `true`. This means the loop
-continues going round until you provide a non-empty name.
+This program will force you to enter a name. It will ask again and again until it gets something that is not an empty string. Applying the `!` operator will convert a value to Boolean type before negating it, and all strings except `""` convert to `true`. This means the loop continues going round until you provide a non-empty name.
## Indenting Code
{{index [code, "structure of"], [whitespace, indentation], "programming style"}}
-In the examples, I've been adding spaces in front of statements that
-are part of some larger statement. These spaces are not required—the computer
-will accept the program just fine without them. In fact, even the
-((line)) breaks in programs are optional. You could write a program as
-a single long line if you felt like it.
+In the examples, I've been adding spaces in front of statements that are part of some larger statement. These spaces are not required—the computer will accept the program just fine without them. In fact, even the ((line)) breaks in programs are optional. You could write a program as a single long line if you felt like it.
-The role of this ((indentation)) inside ((block))s is to make the
-structure of the code stand out. In code where new blocks are opened
-inside other blocks, it can become hard to see where one block ends
-and another begins. With proper indentation, the visual shape of a
-program corresponds to the shape of the blocks inside it. I like to
-use two spaces for every open block, but tastes differ—some people use
-four spaces, and some people use ((tab character))s. The important
-thing is that each new block adds the same amount of space.
+The role of this ((indentation)) inside ((block))s is to make the structure of the code stand out. In code where new blocks are opened inside other blocks, it can become hard to see where one block ends and another begins. With proper indentation, the visual shape of a program corresponds to the shape of the blocks inside it. I like to use two spaces for every open block, but tastes differ—some people use four spaces, and some people use ((tab character))s. The important thing is that each new block adds the same amount of space.
```
if (false != true) {
@@ -606,25 +410,17 @@ if (false != true) {
}
```
-Most code ((editor)) programs[ (including the one in this book)]{if
-interactive} will help by automatically indenting new lines the proper
-amount.
+Most code ((editor)) programs[ (including the one in this book)]{if interactive} will help by automatically indenting new lines the proper amount.
## for loops
{{index [syntax, statement], "while loop", "counter variable"}}
-Many loops follow the pattern shown in the `while` examples. First a
-"counter" binding is created to track the progress of the loop. Then
-comes a `while` loop, usually with a test expression that checks whether the
-counter has reached its end value. At the end of the loop body, the
-counter is updated to track progress.
+Many loops follow the pattern shown in the `while` examples. First a "counter" binding is created to track the progress of the loop. Then comes a `while` loop, usually with a test expression that checks whether the counter has reached its end value. At the end of the loop body, the counter is updated to track progress.
{{index "for loop", loop}}
-Because this pattern is so common, JavaScript and similar languages
-provide a slightly shorter and more comprehensive form, the `for`
-loop.
+Because this pattern is so common, JavaScript and similar languages provide a slightly shorter and more comprehensive form, the `for` loop.
```
for (let number = 0; number <= 12; number = number + 2) {
@@ -637,19 +433,11 @@ for (let number = 0; number <= 12; number = number + 2) {
{{index ["control flow", loop], state}}
-This program is exactly equivalent to the
-[earlier](program_structure#loops) even-number-printing example. The
-only change is that all the ((statement))s that are related to the
-"state" of the loop are grouped together after `for`.
+This program is exactly equivalent to the [earlier](program_structure#loops) even-number-printing example. The only change is that all the ((statement))s that are related to the "state" of the loop are grouped together after `for`.
{{index [binding, as state], [parentheses, statement]}}
-The parentheses after a `for` keyword must contain two
-((semicolon))s. The part before the first semicolon _initializes_ the
-loop, usually by defining a binding. The second part is the
-((expression)) that _checks_ whether the loop must continue. The final
-part _updates_ the state of the loop after every iteration. In most
-cases, this is shorter and clearer than a `while` construct.
+The parentheses after a `for` keyword must contain two ((semicolon))s. The part before the first semicolon _initializes_ the loop, usually by defining a binding. The second part is the ((expression)) that _checks_ whether the loop must continue. The final part _updates_ the state of the loop after every iteration. In most cases, this is shorter and clearer than a `while` construct.
{{index exponentiation}}
@@ -668,12 +456,9 @@ console.log(result);
{{index [loop, "termination of"], "break keyword"}}
-Having the looping condition produce `false` is not the only way a
-loop can finish. There is a special statement called `break` that has
-the effect of immediately jumping out of the enclosing loop.
+Having the looping condition produce `false` is not the only way a loop can finish. There is a special statement called `break` that has the effect of immediately jumping out of the enclosing loop.
-This program illustrates the `break` statement. It finds the first number
-that is both greater than or equal to 20 and divisible by 7.
+This program illustrates the `break` statement. It finds the first number that is both greater than or equal to 20 and divisible by 7.
```
for (let current = 20; ; current = current + 1) {
@@ -687,43 +472,29 @@ for (let current = 20; ; current = current + 1) {
{{index "remainder operator", "% operator"}}
-Using the remainder (`%`) operator is an easy way to test whether a
-number is divisible by another number. If it is, the remainder of
-their division is zero.
+Using the remainder (`%`) operator is an easy way to test whether a number is divisible by another number. If it is, the remainder of their division is zero.
{{index "for loop"}}
-The `for` construct in the example does not have a part that checks
-for the end of the loop. This means that the loop will never stop
-unless the `break` statement inside is executed.
+The `for` construct in the example does not have a part that checks for the end of the loop. This means that the loop will never stop unless the `break` statement inside is executed.
-If you were to remove that `break` statement or you accidentally write
-an end condition that always produces `true`, your program would get
-stuck in an _((infinite loop))_. A program stuck in an infinite loop
-will never finish running, which is usually a bad thing.
+If you were to remove that `break` statement or you accidentally write an end condition that always produces `true`, your program would get stuck in an _((infinite loop))_. A program stuck in an infinite loop will never finish running, which is usually a bad thing.
{{if interactive
-If you create an infinite loop in one of the examples on these pages,
-you'll usually be asked whether you want to stop the script after a
-few seconds. If that fails, you will have to close the tab that you're
-working in, or on some browsers close your whole browser, to recover.
+If you create an infinite loop in one of the examples on these pages, you'll usually be asked whether you want to stop the script after a few seconds. If that fails, you will have to close the tab that you're working in, or on some browsers close your whole browser, to recover.
if}}
{{index "continue keyword"}}
-The `continue` keyword is similar to `break`, in that it influences
-the progress of a loop. When `continue` is encountered in a loop body,
-control jumps out of the body and continues with the loop's next
-iteration.
+The `continue` keyword is similar to `break`, in that it influences the progress of a loop. When `continue` is encountered in a loop body, control jumps out of the body and continues with the loop's next iteration.
## Updating bindings succinctly
{{index assignment, "+= operator", "-= operator", "/= operator", "*= operator", [state, in binding], "side effect"}}
-Especially when looping, a program often needs to "update" a binding
-to hold a value based on that binding's previous value.
+Especially when looping, a program often needs to "update" a binding to hold a value based on that binding's previous value.
```{test: no}
counter = counter + 1;
@@ -735,8 +506,7 @@ JavaScript provides a shortcut for this.
counter += 1;
```
-Similar shortcuts work for many other operators, such as `result *= 2`
-to double `result` or `counter -= 1` to count downward.
+Similar shortcuts work for many other operators, such as `result *= 2` to double `result` or `counter -= 1` to count downward.
This allows us to shorten our counting example a little more.
@@ -748,8 +518,7 @@ for (let number = 0; number <= 12; number += 2) {
{{index "++ operator", "-- operator"}}
-For `counter += 1` and `counter -= 1`, there are even shorter
-equivalents: `counter++` and `counter--`.
+For `counter += 1` and `counter -= 1`, there are even shorter equivalents: `counter++` and `counter--`.
## Dispatching on a value with switch
@@ -766,11 +535,7 @@ else defaultAction();
{{index "colon character", "switch keyword"}}
-There is a construct called `switch` that is intended to express such
-a "dispatch" in a more direct way. Unfortunately, the syntax
-JavaScript uses for this (which it inherited from the C/Java line of
-programming languages) is somewhat awkward—a chain of `if` statements
-may look better. Here is an example:
+There is a construct called `switch` that is intended to express such a "dispatch" in a more direct way. Unfortunately, the syntax JavaScript uses for this (which it inherited from the C/Java line of programming languages) is somewhat awkward—a chain of `if` statements may look better. Here is an example:
```
switch (prompt("What is the weather like?")) {
@@ -790,25 +555,13 @@ switch (prompt("What is the weather like?")) {
{{index fallthrough, "break keyword", "case keyword", "default keyword"}}
-You may put any number of `case` labels inside the block opened by
-`switch`. The program will start executing at the label that
-corresponds to the value that `switch` was given, or at `default` if
-no matching value is found. It will continue executing, even across
-other labels, until it reaches a `break` statement. In some cases,
-such as the `"sunny"` case in the example, this can be used to share
-some code between cases (it recommends going outside for both sunny
-and cloudy weather). But be careful—it is easy to forget such a
-`break`, which will cause the program to execute code you do not want
-executed.
+You may put any number of `case` labels inside the block opened by `switch`. The program will start executing at the label that corresponds to the value that `switch` was given, or at `default` if no matching value is found. It will continue executing, even across other labels, until it reaches a `break` statement. In some cases, such as the `"sunny"` case in the example, this can be used to share some code between cases (it recommends going outside for both sunny and cloudy weather). But be careful—it is easy to forget such a `break`, which will cause the program to execute code you do not want executed.
## Capitalization
{{index capitalization, [binding, naming], [whitespace, syntax]}}
-Binding names may not contain spaces, yet it is often helpful to use
-multiple words to clearly describe what the binding represents. These
-are pretty much your choices for writing a binding name with several
-words in it:
+Binding names may not contain spaces, yet it is often helpful to use multiple words to clearly describe what the binding represents. These are pretty much your choices for writing a binding name with several words in it:
```{lang: null}
fuzzylittleturtle
@@ -819,38 +572,21 @@ fuzzyLittleTurtle
{{index "camel case", "programming style", "underscore character"}}
-The first style can be hard to read. I rather like the look of the
-underscores, though that style is a little painful to type. The
-((standard)) JavaScript functions, and most JavaScript programmers,
-follow the bottom style—they capitalize every word except the first.
-It is not hard to get used to little things like that, and code with
-mixed naming styles can be jarring to read, so we follow this
-((convention)).
+The first style can be hard to read. I rather like the look of the underscores, though that style is a little painful to type. The ((standard)) JavaScript functions, and most JavaScript programmers, follow the bottom style—they capitalize every word except the first. It is not hard to get used to little things like that, and code with mixed naming styles can be jarring to read, so we follow this ((convention)).
{{index "Number function", constructor}}
-In a few cases, such as the `Number` function, the first letter of a
-binding is also capitalized. This was done to mark this function as a
-constructor. What a constructor is will become clear in [Chapter
-?](object#constructors). For now, the important thing is not
-to be bothered by this apparent lack of ((consistency)).
+In a few cases, such as the `Number` function, the first letter of a binding is also capitalized. This was done to mark this function as a constructor. What a constructor is will become clear in [Chapter ?](object#constructors). For now, the important thing is not to be bothered by this apparent lack of ((consistency)).
## Comments
{{index readability}}
-Often, raw code does not convey all the information you want a program
-to convey to human readers, or it conveys it in such a cryptic way
-that people might not understand it. At other times, you might just
-want to include some related thoughts as part of your program. This is
-what _((comment))s_ are for.
+Often, raw code does not convey all the information you want a program to convey to human readers, or it conveys it in such a cryptic way that people might not understand it. At other times, you might just want to include some related thoughts as part of your program. This is what _((comment))s_ are for.
{{index "slash character", "line comment"}}
-A comment is a piece of text that is part of a program but is
-completely ignored by the computer. JavaScript has two ways of writing
-comments. To write a single-line comment, you can use two slash
-characters (`//`) and then the comment text after it.
+A comment is a piece of text that is part of a program but is completely ignored by the computer. JavaScript has two ways of writing comments. To write a single-line comment, you can use two slash characters (`//`) and then the comment text after it.
```{test: no}
let accountBalance = calculateBalance(account);
@@ -865,10 +601,7 @@ addToReport(accountBalance, report);
{{index "block comment"}}
-A `//` comment goes only to the end of the line. A section of text
-between `/*` and `*/` will be ignored in its entirety, regardless of
-whether it contains line breaks. This is useful for adding blocks of
-information about a file or a chunk of program.
+A `//` comment goes only to the end of the line. A section of text between `/*` and `*/` will be ignored in its entirety, regardless of whether it contains line breaks. This is useful for adding blocks of information about a file or a chunk of program.
```
/*
@@ -882,49 +615,27 @@ const myNumber = 11213;
## Summary
-You now know that a program is built out of statements, which
-themselves sometimes contain more statements. Statements tend to
-contain expressions, which themselves can be built out of smaller
-expressions.
+You now know that a program is built out of statements, which themselves sometimes contain more statements. Statements tend to contain expressions, which themselves can be built out of smaller expressions.
-Putting statements after one another gives you a program that is
-executed from top to bottom. You can introduce disturbances in the
-flow of control by using conditional (`if`, `else`, and `switch`) and
-looping (`while`, `do`, and `for`) statements.
+Putting statements after one another gives you a program that is executed from top to bottom. You can introduce disturbances in the flow of control by using conditional (`if`, `else`, and `switch`) and looping (`while`, `do`, and `for`) statements.
-Bindings can be used to file pieces of data under a name, and they are
-useful for tracking state in your program. The environment is the set
-of bindings that are defined. JavaScript systems always put a number
-of useful standard bindings into your environment.
+Bindings can be used to file pieces of data under a name, and they are useful for tracking state in your program. The environment is the set of bindings that are defined. JavaScript systems always put a number of useful standard bindings into your environment.
-Functions are special values that encapsulate a piece of program. You
-can invoke them by writing `functionName(argument1, argument2)`. Such
-a function call is an expression and may produce a value.
+Functions are special values that encapsulate a piece of program. You can invoke them by writing `functionName(argument1, argument2)`. Such a function call is an expression and may produce a value.
## Exercises
{{index exercises}}
-If you are unsure how to test your solutions to the exercises, refer to the
-[Introduction](intro).
+If you are unsure how to test your solutions to the exercises, refer to the [Introduction](intro).
-Each exercise starts with a problem description. Read this description and try to
-solve the exercise. If you run into problems, consider reading the
-hints [after the exercise]{if interactive}[at the [end of the
-book](hints)]{if book}. Full solutions to the exercises are
-not included in this book, but you can find them online at
-[_https://eloquentjavascript.net/code_](https://eloquentjavascript.net/code#2).
-If you want to learn something from the exercises, I recommend looking
-at the solutions only after you've solved the exercise, or at least
-after you've attacked it long and hard enough to have a slight
-headache.
+Each exercise starts with a problem description. Read this description and try to solve the exercise. If you run into problems, consider reading the hints [after the exercise]{if interactive}[at the [end of the book](hints)]{if book}. Full solutions to the exercises are not included in this book, but you can find them online at [_https://eloquentjavascript.net/code_](https://eloquentjavascript.net/code#2). If you want to learn something from the exercises, I recommend looking at the solutions only after you've solved the exercise, or at least after you've attacked it long and hard enough to have a slight headache.
### Looping a triangle
{{index "triangle (exercise)"}}
-Write a ((loop)) that makes seven calls to `console.log` to output the
-following triangle:
+Write a ((loop)) that makes seven calls to `console.log` to output the following triangle:
```{lang: null}
#
@@ -938,8 +649,7 @@ following triangle:
{{index [string, length]}}
-It may be useful to know that you can find the length of a string by
-writing `.length` after it.
+It may be useful to know that you can find the length of a string by writing `.length` after it.
```
let abc = "abc";
@@ -949,8 +659,7 @@ console.log(abc.length);
{{if interactive
-Most exercises contain a piece of code that you can modify to solve
-the exercise. Remember that you can click code blocks to edit them.
+Most exercises contain a piece of code that you can modify to solve the exercise. Remember that you can click code blocks to edit them.
```
// Your code here.
@@ -961,15 +670,9 @@ if}}
{{index "triangle (exercise)"}}
-You can start with a program that prints out the numbers 1 to 7, which
-you can derive by making a few modifications to the [even number
-printing example](program_structure#loops) given earlier in the
-chapter, where the `for` loop was introduced.
+You can start with a program that prints out the numbers 1 to 7, which you can derive by making a few modifications to the [even number printing example](program_structure#loops) given earlier in the chapter, where the `for` loop was introduced.
-Now consider the equivalence between numbers and strings of hash
-characters. You can go from 1 to 2 by adding 1 (`+= 1`). You can go
-from `"#"` to `"##"` by adding a character (`+= "#"`). Thus, your
-solution can closely follow the number-printing program.
+Now consider the equivalence between numbers and strings of hash characters. You can go from 1 to 2 by adding 1 (`+= 1`). You can go from `"#"` to `"##"` by adding a character (`+= "#"`). Thus, your solution can closely follow the number-printing program.
hint}}
@@ -977,18 +680,11 @@ hint}}
{{index "FizzBuzz (exercise)", loop, "conditional execution"}}
-Write a program that uses `console.log` to print all the numbers from
-1 to 100, with two exceptions. For numbers divisible by 3, print
-`"Fizz"` instead of the number, and for numbers divisible by 5 (and
-not 3), print `"Buzz"` instead.
+Write a program that uses `console.log` to print all the numbers from 1 to 100, with two exceptions. For numbers divisible by 3, print `"Fizz"` instead of the number, and for numbers divisible by 5 (and not 3), print `"Buzz"` instead.
-When you have that working, modify your program to print `"FizzBuzz"`
-for numbers that are divisible by both 3 and 5 (and still print
-`"Fizz"` or `"Buzz"` for numbers divisible by only one of those).
+When you have that working, modify your program to print `"FizzBuzz"` for numbers that are divisible by both 3 and 5 (and still print `"Fizz"` or `"Buzz"` for numbers divisible by only one of those).
-(This is actually an ((interview question)) that has been claimed to
-weed out a significant percentage of programmer candidates. So if you
-solved it, your labor market value just went up.)
+(This is actually an ((interview question)) that has been claimed to weed out a significant percentage of programmer candidates. So if you solved it, your labor market value just went up.)
{{if interactive
```
@@ -1000,22 +696,13 @@ if}}
{{index "FizzBuzz (exercise)", "remainder operator", "% operator"}}
-Going over the numbers is clearly a looping job, and selecting what to
-print is a matter of conditional execution. Remember the trick of
-using the remainder (`%`) operator for checking whether a number is
-divisible by another number (has a remainder of zero).
+Going over the numbers is clearly a looping job, and selecting what to print is a matter of conditional execution. Remember the trick of using the remainder (`%`) operator for checking whether a number is divisible by another number (has a remainder of zero).
-In the first version, there are three possible outcomes for every
-number, so you'll have to create an `if`/`else if`/`else` chain.
+In the first version, there are three possible outcomes for every number, so you'll have to create an `if`/`else if`/`else` chain.
{{index "|| operator", ["if keyword", chaining]}}
-The second version of the program has a straightforward solution and a
-clever one. The simple solution is to add another conditional "branch" to
-precisely test the given condition. For the clever solution, build up a
-string containing the word or words to output and print either this
-word or the number if there is no word, potentially by making good use
-of the `||` operator.
+The second version of the program has a straightforward solution and a clever one. The simple solution is to add another conditional "branch" to precisely test the given condition. For the clever solution, build up a string containing the word or words to output and print either this word or the number if there is no word, potentially by making good use of the `||` operator.
hint}}
@@ -1023,10 +710,7 @@ hint}}
{{index "chessboard (exercise)", loop, [nesting, "of loops"], "newline character"}}
-Write a program that creates a string that represents an 8×8 grid,
-using newline characters to separate lines. At each position of the
-grid there is either a space or a "#" character. The characters should
-form a chessboard.
+Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a "#" character. The characters should form a chessboard.
Passing this string to `console.log` should show something like this:
@@ -1041,9 +725,7 @@ Passing this string to `console.log` should show something like this:
# # # #
```
-When you have a program that generates this pattern, define a
-binding `size = 8` and change the program so that it works for
-any `size`, outputting a grid of the given width and height.
+When you have a program that generates this pattern, define a binding `size = 8` and change the program so that it works for any `size`, outputting a grid of the given width and height.
{{if interactive
```
@@ -1055,26 +737,16 @@ if}}
{{index "chess board (exercise)"}}
-You can build the string by starting with an empty one (`""`) and
-repeatedly adding characters. A newline character is written `"\n"`.
+You can build the string by starting with an empty one (`""`) and repeatedly adding characters. A newline character is written `"\n"`.
{{index [nesting, "of loops"], [braces, "block"]}}
-To work with two ((dimensions)), you will need a ((loop)) inside of a
-loop. Put braces around the bodies of both loops to make it
-easy to see where they start and end. Try to properly indent these
-bodies. The order of the loops must follow the order in which we build
-up the string (line by line, left to right, top to bottom). So the
-outer loop handles the lines, and the inner loop handles the characters
-on a line.
+To work with two ((dimensions)), you will need a ((loop)) inside of a loop. Put braces around the bodies of both loops to make it easy to see where they start and end. Try to properly indent these bodies. The order of the loops must follow the order in which we build up the string (line by line, left to right, top to bottom). So the outer loop handles the lines, and the inner loop handles the characters on a line.
{{index "counter variable", "remainder operator", "% operator"}}
-You'll need two bindings to track your progress. To know whether to
-put a space or a hash sign at a given position, you could test whether
-the sum of the two counters is even (`% 2`).
+You'll need two bindings to track your progress. To know whether to put a space or a hash sign at a given position, you could test whether the sum of the two counters is even (`% 2`).
-Terminating a line by adding a newline character must happen after the
-line has been built up, so do this after the inner loop but inside the outer loop.
+Terminating a line by adding a newline character must happen after the line has been built up, so do this after the inner loop but inside the outer loop.
hint}}
diff --git a/03_functions.md b/03_functions.md
index 730ec57a3..f4126b189 100644
--- a/03_functions.md
+++ b/03_functions.md
@@ -2,9 +2,7 @@
{{quote {author: "Donald Knuth", chapter: true}
-People think that computer science is the art of geniuses but the
-actual reality is the opposite, just many people doing things that
-build on each other, like a wall of mini stones.
+People think that computer science is the art of geniuses but the actual reality is the opposite, just many people doing things that build on each other, like a wall of mini stones.
quote}}
@@ -14,32 +12,19 @@ quote}}
{{index function, [code, "structure of"]}}
-Functions are the bread and butter of JavaScript programming. The
-concept of wrapping a piece of program in a value has many uses. It
-gives us a way to structure larger programs, to reduce repetition, to
-associate names with subprograms, and to isolate these subprograms
-from each other.
+Functions are the bread and butter of JavaScript programming. The concept of wrapping a piece of program in a value has many uses. It gives us a way to structure larger programs, to reduce repetition, to associate names with subprograms, and to isolate these subprograms from each other.
-The most obvious application of functions is defining new
-((vocabulary)). Creating new words in prose is usually bad style. But
-in programming, it is indispensable.
+The most obvious application of functions is defining new ((vocabulary)). Creating new words in prose is usually bad style. But in programming, it is indispensable.
{{index abstraction, vocabulary}}
-Typical adult English speakers have some 20,000 words in their
-vocabulary. Few programming languages come with 20,000 commands built
-in. And the vocabulary that _is_ available tends to be more precisely
-defined, and thus less flexible, than in human language. Therefore, we
-usually _have_ to introduce new concepts to avoid repeating ourselves
-too much.
+Typical adult English speakers have some 20,000 words in their vocabulary. Few programming languages come with 20,000 commands built in. And the vocabulary that _is_ available tends to be more precisely defined, and thus less flexible, than in human language. Therefore, we usually _have_ to introduce new concepts to avoid repeating ourselves too much.
## Defining a function
{{index "square example", [function, definition], [binding, definition]}}
-A function definition is a regular binding where the value of the
-binding is a function. For example, this code defines `square` to
-refer to a function that produces the square of a given number:
+A function definition is a regular binding where the value of the binding is a function. For example, this code defines `square` to refer to a function that produces the square of a given number:
```
const square = function(x) {
@@ -53,18 +38,11 @@ console.log(square(12));
{{indexsee "curly braces", braces}}
{{index [braces, "function body"], block, [syntax, function], "function keyword", [function, body], [function, "as value"], [parentheses, arguments]}}
-A function is created with an expression that starts with the keyword
-`function`. Functions have a set of _((parameter))s_ (in this case,
-only `x`) and a _body_, which contains the statements that are to be
-executed when the function is called. The function body of a function
-created this way must always be wrapped in braces, even when it
-consists of only a single ((statement)).
+A function is created with an expression that starts with the keyword `function`. Functions have a set of _((parameter))s_ (in this case, only `x`) and a _body_, which contains the statements that are to be executed when the function is called. The function body of a function created this way must always be wrapped in braces, even when it consists of only a single ((statement)).
{{index "power example"}}
-A function can have multiple parameters or no parameters at all. In
-the following example, `makeNoise` does not list any parameter names,
-whereas `power` lists two:
+A function can have multiple parameters or no parameters at all. In the following example, `makeNoise` does not list any parameter names, whereas `power` lists two:
```
const makeNoise = function() {
@@ -88,51 +66,26 @@ console.log(power(2, 10));
{{index "return value", "return keyword", undefined}}
-Some functions produce a value, such as `power` and `square`, and some
-don't, such as `makeNoise`, whose only result is a ((side effect)). A
-`return` statement determines the value the function returns. When
-control comes across such a statement, it immediately jumps out of the
-current function and gives the returned value to the code that called
-the function. A `return` keyword without an expression after it will
-cause the function to return `undefined`. Functions that don't have a
-`return` statement at all, such as `makeNoise`, similarly return
-`undefined`.
+Some functions produce a value, such as `power` and `square`, and some don't, such as `makeNoise`, whose only result is a ((side effect)). A `return` statement determines the value the function returns. When control comes across such a statement, it immediately jumps out of the current function and gives the returned value to the code that called the function. A `return` keyword without an expression after it will cause the function to return `undefined`. Functions that don't have a `return` statement at all, such as `makeNoise`, similarly return `undefined`.
{{index parameter, [function, application], [binding, "from parameter"]}}
-Parameters to a function behave like regular bindings, but their
-initial values are given by the _caller_ of the function, not the code
-in the function itself.
+Parameters to a function behave like regular bindings, but their initial values are given by the _caller_ of the function, not the code in the function itself.
## Bindings and scopes
{{indexsee "top-level scope", "global scope"}}
{{index "var keyword", "global scope", [binding, global], [binding, "scope of"]}}
-Each binding has a _((scope))_, which is the part of the program
-in which the binding is visible. For bindings defined outside of any
-function or block, the scope is the whole program—you can refer to
-such bindings wherever you want. These are called _global_.
+Each binding has a _((scope))_, which is the part of the program in which the binding is visible. For bindings defined outside of any function or block, the scope is the whole program—you can refer to such bindings wherever you want. These are called _global_.
{{index "local scope", [binding, local]}}
-But bindings created for function ((parameter))s or declared inside a
-function can be referenced only in that function, so they are known as
-_local_ bindings. Every time the function is called, new instances of these
-bindings are created. This provides some isolation between
-functions—each function call acts in its own little world (its local
-environment) and can often be understood without knowing a lot about
-what's going on in the global environment.
+But bindings created for function ((parameter))s or declared inside a function can be referenced only in that function, so they are known as _local_ bindings. Every time the function is called, new instances of these bindings are created. This provides some isolation between functions—each function call acts in its own little world (its local environment) and can often be understood without knowing a lot about what's going on in the global environment.
{{index "let keyword", "const keyword", "var keyword"}}
-Bindings declared with `let` and `const` are in fact local to the
-_((block))_ that they are declared in, so if you create one of those
-inside of a loop, the code before and after the loop cannot "see" it.
-In pre-2015 JavaScript, only functions created new scopes, so
-old-style bindings, created with the `var` keyword, are visible
-throughout the whole function that they appear in—or throughout the
-global scope, if they are not in a function.
+Bindings declared with `let` and `const` are in fact local to the _((block))_ that they are declared in, so if you create one of those inside of a loop, the code before and after the loop cannot "see" it. In pre-2015 JavaScript, only functions created new scopes, so old-style bindings, created with the `var` keyword, are visible throughout the whole function that they appear in—or throughout the global scope, if they are not in a function.
```
let x = 10;
@@ -149,12 +102,7 @@ console.log(x + z);
{{index [binding, visibility]}}
-Each ((scope)) can "look out" into the scope around it, so `x` is
-visible inside the block in the example. The exception is when
-multiple bindings have the same name—in that case, code can see only
-the innermost one. For example, when the code inside the `halve`
-function refers to `n`, it is seeing its _own_ `n`, not the global
-`n`.
+Each ((scope)) can "look out" into the scope around it, so `x` is visible inside the block in the example. The exception is when multiple bindings have the same name—in that case, code can see only the innermost one. For example, when the code inside the `halve` function refers to `n`, it is seeing its _own_ `n`, not the global `n`.
```
const halve = function(n) {
@@ -174,14 +122,11 @@ console.log(n);
{{index [nesting, "of functions"], [nesting, "of scope"], scope, "inner function", "lexical scoping"}}
-JavaScript distinguishes not just _global_ and _local_
-bindings. Blocks and functions can be created inside other blocks and
-functions, producing multiple degrees of locality.
+JavaScript distinguishes not just _global_ and _local_ bindings. Blocks and functions can be created inside other blocks and functions, producing multiple degrees of locality.
{{index "landscape example"}}
-For example, this function—which outputs the ingredients needed to
-make a batch of hummus—has another function inside it:
+For example, this function—which outputs the ingredients needed to make a batch of hummus—has another function inside it:
```
const hummus = function(factor) {
@@ -203,31 +148,19 @@ const hummus = function(factor) {
{{index [function, scope], scope}}
-The code inside the `ingredient` function can see the `factor` binding
-from the outer function. But its local bindings, such as `unit` or
-`ingredientAmount`, are not visible in the outer function.
+The code inside the `ingredient` function can see the `factor` binding from the outer function. But its local bindings, such as `unit` or `ingredientAmount`, are not visible in the outer function.
-The set of bindings visible inside a block is determined by the place of
-that block in the program text. Each local scope can also see all the
-local scopes that contain it, and all scopes can see the global scope.
-This approach to binding visibility is called _((lexical scoping))_.
+The set of bindings visible inside a block is determined by the place of that block in the program text. Each local scope can also see all the local scopes that contain it, and all scopes can see the global scope. This approach to binding visibility is called _((lexical scoping))_.
## Functions as values
{{index [function, "as value"], [binding, definition]}}
-A function binding usually simply acts as a name for a specific piece
-of the program. Such a binding is defined once and never changed. This
-makes it easy to confuse the function and its name.
+A function binding usually simply acts as a name for a specific piece of the program. Such a binding is defined once and never changed. This makes it easy to confuse the function and its name.
{{index [binding, assignment]}}
-But the two are different. A function value can do all the things that
-other values can do—you can use it in arbitrary ((expression))s, not
-just call it. It is possible to store a function value in a new
-binding, pass it as an argument to a function, and so on. Similarly, a
-binding that holds a function is still just a regular binding and can,
-if not constant, be assigned a new value, like so:
+But the two are different. A function value can do all the things that other values can do—you can use it in arbitrary ((expression))s, not just call it. It is possible to store a function value in a new binding, pass it as an argument to a function, and so on. Similarly, a binding that holds a function is still just a regular binding and can, if not constant, be assigned a new value, like so:
```{test: no}
let launchMissiles = function() {
@@ -240,16 +173,13 @@ if (safeMode) {
{{index [function, "higher-order"]}}
-In [Chapter ?](higher_order), we will discuss the interesting things
-that can be done by passing around function values to other functions.
+In [Chapter ?](higher_order), we will discuss the interesting things that can be done by passing around function values to other functions.
## Declaration notation
{{index [syntax, function], "function keyword", "square example", [function, definition], [function, declaration]}}
-There is a slightly shorter way to create a function binding. When the
-`function` keyword is used at the start of a statement, it works
-differently.
+There is a slightly shorter way to create a function binding. When the `function` keyword is used at the start of a statement, it works differently.
```{test: wrap}
function square(x) {
@@ -259,9 +189,7 @@ function square(x) {
{{index future, "execution order"}}
-This is a function _declaration_. The statement defines the binding
-`square` and points it at the given function. It is slightly easier
-to write and doesn't require a semicolon after the function.
+This is a function _declaration_. The statement defines the binding `square` and points it at the given function. It is slightly easier to write and doesn't require a semicolon after the function.
There is one subtlety with this form of function definition.
@@ -273,23 +201,13 @@ function future() {
}
```
-The preceding code works, even though the function is defined _below_ the code
-that uses it. Function declarations are not part of the regular
-top-to-bottom flow of control. They are conceptually moved to the top
-of their scope and can be used by all the code in that scope. This is
-sometimes useful because it offers the freedom to order code in a
-way that seems meaningful, without worrying about having to define all
-functions before they are used.
+The preceding code works, even though the function is defined _below_ the code that uses it. Function declarations are not part of the regular top-to-bottom flow of control. They are conceptually moved to the top of their scope and can be used by all the code in that scope. This is sometimes useful because it offers the freedom to order code in a way that seems meaningful, without worrying about having to define all functions before they are used.
## Arrow functions
{{index function, "arrow function"}}
-There's a third notation for functions, which looks very different
-from the others. Instead of the `function` keyword, it uses an arrow
-(`=>`) made up of an equal sign and a greater-than character (not to be
-confused with the greater-than-or-equal operator, which is written
-`>=`).
+There's a third notation for functions, which looks very different from the others. Instead of the `function` keyword, it uses an arrow (`=>`) made up of an equal sign and a greater-than character (not to be confused with the greater-than-or-equal operator, which is written `>=`).
```{test: wrap}
const power = (base, exponent) => {
@@ -303,17 +221,11 @@ const power = (base, exponent) => {
{{index [function, body]}}
-The arrow comes _after_ the list of parameters and is followed by the
-function's body. It expresses something like "this input (the
-((parameter))s) produces this result (the body)".
+The arrow comes _after_ the list of parameters and is followed by the function's body. It expresses something like "this input (the ((parameter))s) produces this result (the body)".
{{index [braces, "function body"], "square example", [parentheses, arguments]}}
-When there is only one parameter name, you can omit the parentheses around the
-parameter list. If the body is a single expression,
-rather than a ((block)) in braces, that expression will be returned
-from the function. So, these two definitions of `square` do the same
-thing:
+When there is only one parameter name, you can omit the parentheses around the parameter list. If the body is a single expression, rather than a ((block)) in braces, that expression will be returned from the function. So, these two definitions of `square` do the same thing:
```
const square1 = (x) => { return x * x; };
@@ -322,8 +234,7 @@ const square2 = x => x * x;
{{index [parentheses, arguments]}}
-When an arrow function has no parameters at all, its parameter list is
-just an empty set of parentheses.
+When an arrow function has no parameters at all, its parameter list is just an empty set of parentheses.
```
const horn = () => {
@@ -333,12 +244,7 @@ const horn = () => {
{{index verbosity}}
-There's no deep reason to have both arrow functions and
-`function` expressions in the language. Apart from a minor detail,
-which we'll discuss in [Chapter ?](object), they do the same thing.
-Arrow functions were added in 2015, mostly to make it possible to
-write small function expressions in a less verbose way. We'll be using
-them a lot in [Chapter ?](higher_order).
+There's no deep reason to have both arrow functions and `function` expressions in the language. Apart from a minor detail, which we'll discuss in [Chapter ?](object), they do the same thing. Arrow functions were added in 2015, mostly to make it possible to write small function expressions in a less verbose way. We'll be using them a lot in [Chapter ?](higher_order).
{{id stack}}
@@ -347,9 +253,7 @@ them a lot in [Chapter ?](higher_order).
{{indexsee stack, "call stack"}}
{{index "call stack", [function, application]}}
-The way control flows through functions is somewhat involved. Let's
-take a closer look at it. Here is a simple program that makes a few
-function calls:
+The way control flows through functions is somewhat involved. Let's take a closer look at it. Here is a simple program that makes a few function calls:
```
function greet(who) {
@@ -361,13 +265,7 @@ console.log("Bye");
{{index ["control flow", functions], "execution order", "console.log"}}
-A run through this program goes roughly like this: the call to `greet`
-causes control to jump to the start of that function (line 2). The
-function calls `console.log`, which takes control, does its job, and
-then returns control to line 2. There it reaches the end of the
-`greet` function, so it returns to the place that called it, which is
-line 4. The line after that calls `console.log` again. After that
-returns, the program reaches its end.
+A run through this program goes roughly like this: the call to `greet` causes control to jump to the start of that function (line 2). The function calls `console.log`, which takes control, does its job, and then returns control to line 2. There it reaches the end of the `greet` function, so it returns to the place that called it, which is line 4. The line after that calls `console.log` again. After that returns, the program reaches its end.
We could show the flow of control schematically like this:
@@ -383,26 +281,13 @@ not in function
{{index "return keyword", [memory, call stack]}}
-Because a function has to jump back to the place that called it when
-it returns, the computer must remember the context from which the call
-happened. In one case, `console.log` has to return to the `greet`
-function when it is done. In the other case, it returns to the end of
-the program.
+Because a function has to jump back to the place that called it when it returns, the computer must remember the context from which the call happened. In one case, `console.log` has to return to the `greet` function when it is done. In the other case, it returns to the end of the program.
-The place where the computer stores this context is the _((call
-stack))_. Every time a function is called, the current context is
-stored on top of this stack. When a function returns, it removes the
-top context from the stack and uses that context to continue execution.
+The place where the computer stores this context is the _((call stack))_. Every time a function is called, the current context is stored on top of this stack. When a function returns, it removes the top context from the stack and uses that context to continue execution.
{{index "infinite loop", "stack overflow", recursion}}
-Storing this stack requires space in the computer's memory. When the
-stack grows too big, the computer will fail with a message like "out
-of stack space" or "too much recursion". The following code
-illustrates this by asking the computer a really hard question that
-causes an infinite back-and-forth between two functions. Rather, it
-_would_ be infinite, if the computer had an infinite stack. As it is,
-we will run out of space, or "blow the stack".
+Storing this stack requires space in the computer's memory. When the stack grows too big, the computer will fail with a message like "out of stack space" or "too much recursion". The following code illustrates this by asking the computer a really hard question that causes an infinite back-and-forth between two functions. Rather, it _would_ be infinite, if the computer had an infinite stack. As it is, we will run out of space, or "blow the stack".
```{test: no}
function chicken() {
@@ -427,25 +312,15 @@ console.log(square(4, true, "hedgehog"));
// → 16
```
-We defined `square` with only one ((parameter)). Yet when we call it
-with three, the language doesn't complain. It ignores the extra
-arguments and computes the square of the first one.
+We defined `square` with only one ((parameter)). Yet when we call it with three, the language doesn't complain. It ignores the extra arguments and computes the square of the first one.
{{index undefined}}
-JavaScript is extremely broad-minded about the number of arguments you
-pass to a function. If you pass too many, the extra ones are ignored.
-If you pass too few, the missing parameters get assigned the value
-`undefined`.
+JavaScript is extremely broad-minded about the number of arguments you pass to a function. If you pass too many, the extra ones are ignored. If you pass too few, the missing parameters get assigned the value `undefined`.
-The downside of this is that it is possible—likely, even—that you'll
-accidentally pass the wrong number of arguments to functions. And no
-one will tell you about it.
+The downside of this is that it is possible—likely, even—that you'll accidentally pass the wrong number of arguments to functions. And no one will tell you about it.
-The upside is that this behavior can be used to allow a function to be
-called with different numbers of arguments. For example, this `minus`
-function tries to imitate the `-` operator by acting on either one or
-two arguments:
+The upside is that this behavior can be used to allow a function to be called with different numbers of arguments. For example, this `minus` function tries to imitate the `-` operator by acting on either one or two arguments:
```
function minus(a, b) {
@@ -462,15 +337,11 @@ console.log(minus(10, 5));
{{id power}}
{{index "optional argument", "default value", parameter, ["= operator", "for default value"]}}
-If you write an `=` operator after
-a parameter, followed by an expression, the value of that expression
-will replace the argument when it is not given.
+If you write an `=` operator after a parameter, followed by an expression, the value of that expression will replace the argument when it is not given.
{{index "power example"}}
-For example, this version of `power` makes its second argument
-optional. If you don't provide it or pass the value `undefined`, it will default to two, and the
-function will behave like `square`.
+For example, this version of `power` makes its second argument optional. If you don't provide it or pass the value `undefined`, it will default to two, and the function will behave like `square`.
```{test: wrap}
function power(base, exponent = 2) {
@@ -489,11 +360,7 @@ console.log(power(2, 6));
{{index "console.log"}}
-In the [next chapter](data#rest_parameters), we will see a way in
-which a function body can get at the whole list of arguments it was
-passed. This is helpful because it makes it possible for a function to
-accept any number of arguments. For example, `console.log` does
-this—it outputs all of the values it is given.
+In the [next chapter](data#rest_parameters), we will see a way in which a function body can get at the whole list of arguments it was passed. This is helpful because it makes it possible for a function to accept any number of arguments. For example, `console.log` does this—it outputs all of the values it is given.
```
console.log("C", "O", 2);
@@ -504,14 +371,9 @@ console.log("C", "O", 2);
{{index "call stack", "local binding", [function, "as value"], scope}}
-The ability to treat functions as values, combined with the fact that
-local bindings are re-created every time a function is called, brings
-up an interesting question. What happens to local bindings when the
-function call that created them is no longer active?
+The ability to treat functions as values, combined with the fact that local bindings are re-created every time a function is called, brings up an interesting question. What happens to local bindings when the function call that created them is no longer active?
-The following code shows an example of this. It defines a function,
-`wrapValue`, that creates a local binding. It then returns a function
-that accesses and returns this local binding.
+The following code shows an example of this. It defines a function, `wrapValue`, that creates a local binding. It then returns a function that accesses and returns this local binding.
```
function wrapValue(n) {
@@ -527,22 +389,13 @@ console.log(wrap2());
// → 2
```
-This is allowed and works as you'd hope—both instances of the binding
-can still be accessed. This situation is a good demonstration of the
-fact that local bindings are created anew for every call, and
-different calls can't trample on one another's local bindings.
+This is allowed and works as you'd hope—both instances of the binding can still be accessed. This situation is a good demonstration of the fact that local bindings are created anew for every call, and different calls can't trample on one another's local bindings.
-This feature—being able to reference a specific instance of a local
-binding in an enclosing scope—is called _((closure))_. A function that
-references bindings from local scopes around it is called _a_ closure. This behavior
-not only frees you from having to worry about lifetimes of bindings
-but also makes it possible to use function values in some creative
-ways.
+This feature—being able to reference a specific instance of a local binding in an enclosing scope—is called _((closure))_. A function that references bindings from local scopes around it is called _a_ closure. This behavior not only frees you from having to worry about lifetimes of bindings but also makes it possible to use function values in some creative ways.
{{index "multiplier function"}}
-With a slight change, we can turn the previous example into a way to
-create functions that multiply by an arbitrary amount.
+With a slight change, we can turn the previous example into a way to create functions that multiply by an arbitrary amount.
```
function multiplier(factor) {
@@ -556,31 +409,19 @@ console.log(twice(5));
{{index [binding, "from parameter"]}}
-The explicit `local` binding from the `wrapValue` example isn't really
-needed since a parameter is itself a local binding.
+The explicit `local` binding from the `wrapValue` example isn't really needed since a parameter is itself a local binding.
{{index [function, "model of"]}}
-Thinking about programs like this takes some practice. A good mental
-model is to think of function values as containing both the code in
-their body and the environment in which they are created. When called,
-the function body sees the environment in which it was created, not the
-environment in which it is called.
+Thinking about programs like this takes some practice. A good mental model is to think of function values as containing both the code in their body and the environment in which they are created. When called, the function body sees the environment in which it was created, not the environment in which it is called.
-In the example, `multiplier` is called and creates an environment in
-which its `factor` parameter is bound to 2. The function value it
-returns, which is stored in `twice`, remembers this environment. So
-when that is called, it multiplies its argument by 2.
+In the example, `multiplier` is called and creates an environment in which its `factor` parameter is bound to 2. The function value it returns, which is stored in `twice`, remembers this environment. So when that is called, it multiplies its argument by 2.
## Recursion
{{index "power example", "stack overflow", recursion, [function, application]}}
-It is perfectly okay for a function to call itself, as long as it
-doesn't do it so often that it overflows the stack. A function that calls
-itself is called _recursive_. Recursion allows some functions to be
-written in a different style. Take, for example, this alternative
-implementation of `power`:
+It is perfectly okay for a function to call itself, as long as it doesn't do it so often that it overflows the stack. A function that calls itself is called _recursive_. Recursion allows some functions to be written in a different style. Take, for example, this alternative implementation of `power`:
```{test: wrap}
function power(base, exponent) {
@@ -597,67 +438,36 @@ console.log(power(2, 3));
{{index loop, readability, mathematics}}
-This is rather close to the way mathematicians define exponentiation
-and arguably describes the concept more clearly than the looping
-variant. The function calls itself multiple times with ever smaller
-exponents to achieve the repeated multiplication.
+This is rather close to the way mathematicians define exponentiation and arguably describes the concept more clearly than the looping variant. The function calls itself multiple times with ever smaller exponents to achieve the repeated multiplication.
{{index [function, application], efficiency}}
-But this implementation has one problem: in typical JavaScript
-implementations, it's about three times slower than the looping version.
-Running through a simple loop is generally cheaper than calling a
-function multiple times.
+But this implementation has one problem: in typical JavaScript implementations, it's about three times slower than the looping version. Running through a simple loop is generally cheaper than calling a function multiple times.
{{index optimization}}
-The dilemma of speed versus ((elegance)) is an interesting one. You
-can see it as a kind of continuum between human-friendliness and
-machine-friendliness. Almost any program can be made faster by making
-it bigger and more convoluted. The programmer has to decide on an
-appropriate balance.
+The dilemma of speed versus ((elegance)) is an interesting one. You can see it as a kind of continuum between human-friendliness and machine-friendliness. Almost any program can be made faster by making it bigger and more convoluted. The programmer has to decide on an appropriate balance.
-In the case of the `power` function, the inelegant (looping) version
-is still fairly simple and easy to read. It doesn't make much sense to
-replace it with the recursive version. Often, though, a program deals
-with such complex concepts that giving up some efficiency in order to
-make the program more straightforward is helpful.
+In the case of the `power` function, the inelegant (looping) version is still fairly simple and easy to read. It doesn't make much sense to replace it with the recursive version. Often, though, a program deals with such complex concepts that giving up some efficiency in order to make the program more straightforward is helpful.
{{index profiling}}
-Worrying about efficiency can be a distraction. It's yet another
-factor that complicates program design, and when you're doing
-something that's already difficult, that extra thing to worry about
-can be paralyzing.
+Worrying about efficiency can be a distraction. It's yet another factor that complicates program design, and when you're doing something that's already difficult, that extra thing to worry about can be paralyzing.
{{index "premature optimization"}}
-Therefore, always start by writing something that's correct and easy
-to understand. If you're worried that it's too slow—which it usually
-isn't since most code simply isn't executed often enough to take any
-significant amount of time—you can measure afterward and improve it
-if necessary.
+Therefore, always start by writing something that's correct and easy to understand. If you're worried that it's too slow—which it usually isn't since most code simply isn't executed often enough to take any significant amount of time—you can measure afterward and improve it if necessary.
{{index "branching recursion"}}
-Recursion is not always just an inefficient alternative to looping.
-Some problems really are easier to solve with recursion than with
-loops. Most often these are problems that require exploring or
-processing several "branches", each of which might branch out again
-into even more branches.
+Recursion is not always just an inefficient alternative to looping. Some problems really are easier to solve with recursion than with loops. Most often these are problems that require exploring or processing several "branches", each of which might branch out again into even more branches.
{{id recursive_puzzle}}
{{index recursion, "number puzzle example"}}
-Consider this puzzle: by starting from the number 1 and repeatedly
-either adding 5 or multiplying by 3, an infinite set of numbers
-can be produced. How would you write a function that, given a number,
-tries to find a sequence of such additions and multiplications that
-produces that number?
+Consider this puzzle: by starting from the number 1 and repeatedly either adding 5 or multiplying by 3, an infinite set of numbers can be produced. How would you write a function that, given a number, tries to find a sequence of such additions and multiplications that produces that number?
-For example, the number 13 could be reached by first multiplying by 3
-and then adding 5 twice, whereas the number 15 cannot be reached at
-all.
+For example, the number 13 could be reached by first multiplying by 3 and then adding 5 twice, whereas the number 15 cannot be reached at all.
Here is a recursive solution:
@@ -680,38 +490,19 @@ console.log(findSolution(24));
// → (((1 * 3) + 5) * 3)
```
-Note that this program doesn't necessarily find the _shortest_
-sequence of operations. It is satisfied when it finds any sequence at
-all.
+Note that this program doesn't necessarily find the _shortest_ sequence of operations. It is satisfied when it finds any sequence at all.
-It is okay if you don't see how it works right away. Let's work
-through it, since it makes for a great exercise in recursive thinking.
+It is okay if you don't see how it works right away. Let's work through it, since it makes for a great exercise in recursive thinking.
-The inner function `find` does the actual recursing. It takes two
-((argument))s: the current number and a string that records how we
-reached this number. If it finds a solution, it returns a string that
-shows how to get to the target. If no solution can be found starting
-from this number, it returns `null`.
+The inner function `find` does the actual recursing. It takes two ((argument))s: the current number and a string that records how we reached this number. If it finds a solution, it returns a string that shows how to get to the target. If no solution can be found starting from this number, it returns `null`.
{{index null, "|| operator", "short-circuit evaluation"}}
-To do this, the function performs one of three actions. If the current
-number is the target number, the current history is a way to reach
-that target, so it is returned. If the current number is greater than
-the target, there's no sense in further exploring this branch because
-both adding and multiplying will only make the number bigger, so it
-returns `null`. Finally, if we're still below the target number,
-the function tries both possible paths that start from the current
-number by calling itself twice, once for addition and once for
-multiplication. If the first call returns something that is not
-`null`, it is returned. Otherwise, the second call is returned,
-regardless of whether it produces a string or `null`.
+To do this, the function performs one of three actions. If the current number is the target number, the current history is a way to reach that target, so it is returned. If the current number is greater than the target, there's no sense in further exploring this branch because both adding and multiplying will only make the number bigger, so it returns `null`. Finally, if we're still below the target number, the function tries both possible paths that start from the current number by calling itself twice, once for addition and once for multiplication. If the first call returns something that is not `null`, it is returned. Otherwise, the second call is returned, regardless of whether it produces a string or `null`.
{{index "call stack"}}
-To better understand how this function produces the effect we're
-looking for, let's look at all the calls to `find` that are made when
-searching for a solution for the number 13.
+To better understand how this function produces the effect we're looking for, let's look at all the calls to `find` that are made when searching for a solution for the number 13.
```{lang: null}
find(1, "1")
@@ -729,59 +520,34 @@ find(1, "1")
found!
```
-The indentation indicates the depth of the call stack. The first time
-`find` is called, it starts by calling itself to explore the solution
-that starts with `(1 + 5)`. That call will further recurse to explore
-_every_ continued solution that yields a number less than or equal to
-the target number. Since it doesn't find one that hits the target, it
-returns `null` back to the first call. There the `||` operator causes
-the call that explores `(1 * 3)` to happen. This search has more
-luck—its first recursive call, through yet _another_ recursive call,
-hits upon the target number. That innermost call returns a string, and
-each of the `||` operators in the intermediate calls passes that string
-along, ultimately returning the solution.
+The indentation indicates the depth of the call stack. The first time `find` is called, it starts by calling itself to explore the solution that starts with `(1 + 5)`. That call will further recurse to explore _every_ continued solution that yields a number less than or equal to the target number. Since it doesn't find one that hits the target, it returns `null` back to the first call. There the `||` operator causes the call that explores `(1 * 3)` to happen. This search has more luck—its first recursive call, through yet _another_ recursive call, hits upon the target number. That innermost call returns a string, and each of the `||` operators in the intermediate calls passes that string along, ultimately returning the solution.
## Growing functions
{{index [function, definition]}}
-There are two more or less natural ways for functions to be introduced
-into programs.
+There are two more or less natural ways for functions to be introduced into programs.
{{index repetition}}
-The first is that you find yourself writing similar code multiple
-times. You'd prefer not to do that. Having more code means more space
-for mistakes to hide and more material to read for people trying to
-understand the program. So you take the repeated functionality, find a
-good name for it, and put it into a function.
+The first is that you find yourself writing similar code multiple times. You'd prefer not to do that. Having more code means more space for mistakes to hide and more material to read for people trying to understand the program. So you take the repeated functionality, find a good name for it, and put it into a function.
-The second way is that you find you need some functionality that you
-haven't written yet and that sounds like it deserves its own function.
-You'll start by naming the function, and then you'll write its body.
-You might even start writing code that uses the function before you
-actually define the function itself.
+The second way is that you find you need some functionality that you haven't written yet and that sounds like it deserves its own function. You'll start by naming the function, and then you'll write its body. You might even start writing code that uses the function before you actually define the function itself.
{{index [function, naming], [binding, naming]}}
-How difficult it is to find a good name for a function is a good
-indication of how clear a concept it is that you're trying to wrap.
-Let's go through an example.
+How difficult it is to find a good name for a function is a good indication of how clear a concept it is that you're trying to wrap. Let's go through an example.
{{index "farm example"}}
-We want to write a program that prints two numbers: the numbers of
-cows and chickens on a farm, with the words `Cows` and `Chickens`
-after them and zeros padded before both numbers so that they are
-always three digits long.
+We want to write a program that prints two numbers: the numbers of cows and chickens on a farm, with the words `Cows` and `Chickens` after them and zeros padded before both numbers so that they are always three digits long.
```{lang: null}
007 Cows
011 Chickens
```
-This asks for a function of two arguments—the number of cows and the
-number of chickens. Let's get coding.
+This asks for a function of two arguments—the number of cows and the number of chickens. Let's get coding.
```
function printFarmInventory(cows, chickens) {
@@ -801,20 +567,13 @@ printFarmInventory(7, 11);
{{index ["length property", "for string"], "while loop"}}
-Writing `.length` after a string expression will give us the length of
-that string. Thus, the `while` loops keep adding zeros in front of the
-number strings until they are at least three characters long.
+Writing `.length` after a string expression will give us the length of that string. Thus, the `while` loops keep adding zeros in front of the number strings until they are at least three characters long.
-Mission accomplished! But just as we are about to send the farmer the
-code (along with a hefty invoice), she calls and tells us she's also
-started keeping pigs, and couldn't we please extend the software to
-also print pigs?
+Mission accomplished! But just as we are about to send the farmer the code (along with a hefty invoice), she calls and tells us she's also started keeping pigs, and couldn't we please extend the software to also print pigs?
{{index "copy-paste programming"}}
-We sure can. But just as we're in the process of copying and pasting
-those four lines one more time, we stop and reconsider. There has to
-be a better way. Here's a first attempt:
+We sure can. But just as we're in the process of copying and pasting those four lines one more time, we stop and reconsider. There has to be a better way. Here's a first attempt:
```
function printZeroPaddedWithLabel(number, label) {
@@ -836,14 +595,11 @@ printFarmInventory(7, 11, 3);
{{index [function, naming]}}
-It works! But that name, `printZeroPaddedWithLabel`, is a little
-awkward. It conflates three things—printing, zero-padding, and adding
-a label—into a single function.
+It works! But that name, `printZeroPaddedWithLabel`, is a little awkward. It conflates three things—printing, zero-padding, and adding a label—into a single function.
{{index "zeroPad function"}}
-Instead of lifting out the repeated part of our program wholesale,
-let's try to pick out a single _concept_.
+Instead of lifting out the repeated part of our program wholesale, let's try to pick out a single _concept_.
```
function zeroPad(number, width) {
@@ -865,76 +621,36 @@ printFarmInventory(7, 16, 3);
{{index readability, "pure function"}}
-A function with a nice, obvious name like `zeroPad` makes it easier
-for someone who reads the code to figure out what it does. And such a
-function is useful in more situations than just this specific program.
-For example, you could use it to help print nicely aligned tables of
-numbers.
+A function with a nice, obvious name like `zeroPad` makes it easier for someone who reads the code to figure out what it does. And such a function is useful in more situations than just this specific program. For example, you could use it to help print nicely aligned tables of numbers.
{{index [interface, design]}}
-How smart and versatile _should_ our function be? We could write
-anything, from a terribly simple function that can only pad a number
-to be three characters wide to a complicated generalized
-number-formatting system that handles fractional numbers, negative
-numbers, alignment of decimal dots, padding with different characters,
-and so on.
+How smart and versatile _should_ our function be? We could write anything, from a terribly simple function that can only pad a number to be three characters wide to a complicated generalized number-formatting system that handles fractional numbers, negative numbers, alignment of decimal dots, padding with different characters, and so on.
-A useful principle is to not add cleverness unless you are absolutely
-sure you're going to need it. It can be tempting to write general
-"((framework))s" for every bit of functionality you come across.
-Resist that urge. You won't get any real work done—you'll just be
-writing code that you never use.
+A useful principle is to not add cleverness unless you are absolutely sure you're going to need it. It can be tempting to write general "((framework))s" for every bit of functionality you come across. Resist that urge. You won't get any real work done—you'll just be writing code that you never use.
{{id pure}}
## Functions and side effects
{{index "side effect", "pure function", [function, purity]}}
-Functions can be roughly divided into those that are called for their
-side effects and those that are called for their return value. (Though
-it is definitely also possible to both have side effects and return a
-value.)
+Functions can be roughly divided into those that are called for their side effects and those that are called for their return value. (Though it is definitely also possible to both have side effects and return a value.)
{{index reuse}}
-The first helper function in the ((farm example)),
-`printZeroPaddedWithLabel`, is called for its side effect: it prints a
-line. The second version, `zeroPad`, is called for its return value.
-It is no coincidence that the second is useful in more situations than
-the first. Functions that create values are easier to combine in new
-ways than functions that directly perform side effects.
+The first helper function in the ((farm example)), `printZeroPaddedWithLabel`, is called for its side effect: it prints a line. The second version, `zeroPad`, is called for its return value. It is no coincidence that the second is useful in more situations than the first. Functions that create values are easier to combine in new ways than functions that directly perform side effects.
{{index substitution}}
-A _pure_ function is a specific kind of value-producing function that
-not only has no side effects but also doesn't rely on side effects
-from other code—for example, it doesn't read global bindings whose
-value might change. A pure function has the pleasant property that,
-when called with the same arguments, it always produces the same value
-(and doesn't do anything else). A call to such a function can be
-substituted by its return value without changing the meaning of the
-code. When you are not sure that a pure function is working correctly,
-you can test it by simply calling it and know that if it works in
-that context, it will work in any context. Nonpure functions tend to
-require more scaffolding to test.
+A _pure_ function is a specific kind of value-producing function that not only has no side effects but also doesn't rely on side effects from other code—for example, it doesn't read global bindings whose value might change. A pure function has the pleasant property that, when called with the same arguments, it always produces the same value (and doesn't do anything else). A call to such a function can be substituted by its return value without changing the meaning of the code. When you are not sure that a pure function is working correctly, you can test it by simply calling it and know that if it works in that context, it will work in any context. Nonpure functions tend to require more scaffolding to test.
{{index optimization, "console.log"}}
-Still, there's no need to feel bad when writing functions that are not
-pure or to wage a holy war to purge them from your code. Side effects
-are often useful. There'd be no way to write a pure version of
-`console.log`, for example, and `console.log` is good to have. Some
-operations are also easier to express in an efficient way when we use
-side effects, so computing speed can be a reason to avoid purity.
+Still, there's no need to feel bad when writing functions that are not pure or to wage a holy war to purge them from your code. Side effects are often useful. There'd be no way to write a pure version of `console.log`, for example, and `console.log` is good to have. Some operations are also easier to express in an efficient way when we use side effects, so computing speed can be a reason to avoid purity.
## Summary
-This chapter taught you how to write your own functions. The
-`function` keyword, when used as an expression, can create a function
-value. When used as a statement, it can be used to declare a binding
-and give it a function as its value. Arrow functions are yet another
-way to create functions.
+This chapter taught you how to write your own functions. The `function` keyword, when used as an expression, can create a function value. When used as a statement, it can be used to declare a binding and give it a function as its value. Arrow functions are yet another way to create functions.
```
// Define f to hold a function value
@@ -951,16 +667,9 @@ function g(a, b) {
let h = a => a % 3;
```
-A key aspect in understanding functions is understanding scopes. Each
-block creates a new scope. Parameters and bindings declared in a given
-scope are local and not visible from the outside. Bindings declared
-with `var` behave differently—they end up in the nearest function
-scope or the global scope.
+A key aspect in understanding functions is understanding scopes. Each block creates a new scope. Parameters and bindings declared in a given scope are local and not visible from the outside. Bindings declared with `var` behave differently—they end up in the nearest function scope or the global scope.
-Separating the tasks your program performs into different functions is
-helpful. You won't have to repeat yourself as much, and functions can
-help organize a program by grouping code into pieces that do specific
-things.
+Separating the tasks your program performs into different functions is helpful. You won't have to repeat yourself as much, and functions can help organize a program by grouping code into pieces that do specific things.
## Exercises
@@ -968,10 +677,7 @@ things.
{{index "Math object", "minimum (exercise)", "Math.min function", minimum}}
-The [previous chapter](program_structure#return_values) introduced the
-standard function `Math.min` that returns its smallest argument. We
-can build something like that now. Write a function `min` that takes
-two arguments and returns their minimum.
+The [previous chapter](program_structure#return_values) introduced the standard function `Math.min` that returns its smallest argument. We can build something like that now. Write a function `min` that takes two arguments and returns their minimum.
{{if interactive
@@ -989,9 +695,7 @@ if}}
{{index "minimum (exercise)"}}
-If you have trouble putting braces and
-parentheses in the right place to get a valid function definition,
-start by copying one of the examples in this chapter and modifying it.
+If you have trouble putting braces and parentheses in the right place to get a valid function definition, start by copying one of the examples in this chapter and modifying it.
{{index "return keyword"}}
@@ -1003,10 +707,7 @@ hint}}
{{index recursion, "isEven (exercise)", "even number"}}
-We've seen that `%` (the remainder operator) can be used to test
-whether a number is even or odd by using `% 2` to see whether it's
-divisible by two. Here's another way to define whether a positive
-whole number is even or odd:
+We've seen that `%` (the remainder operator) can be used to test whether a number is even or odd by using `% 2` to see whether it's divisible by two. Here's another way to define whether a positive whole number is even or odd:
- Zero is even.
@@ -1014,14 +715,11 @@ whole number is even or odd:
- For any other number _N_, its evenness is the same as _N_ - 2.
-Define a recursive function `isEven` corresponding to this
-description. The function should accept a single parameter (a
-positive, whole number) and return a Boolean.
+Define a recursive function `isEven` corresponding to this description. The function should accept a single parameter (a positive, whole number) and return a Boolean.
{{index "stack overflow"}}
-Test it on 50 and 75. See how it behaves on -1. Why? Can you think of
-a way to fix this?
+Test it on 50 and 75. See how it behaves on -1. Why? Can you think of a way to fix this?
{{if interactive
@@ -1042,21 +740,11 @@ if}}
{{index "isEven (exercise)", ["if keyword", chaining], recursion}}
-Your function will likely look somewhat similar to the inner `find`
-function in the recursive `findSolution`
-[example](functions#recursive_puzzle) in this chapter, with an
-`if`/`else if`/`else` chain that tests which of the three cases
-applies. The final `else`, corresponding to the third case, makes the
-recursive call. Each of the branches should contain a `return`
-statement or in some other way arrange for a specific value to be
-returned.
+Your function will likely look somewhat similar to the inner `find` function in the recursive `findSolution` [example](functions#recursive_puzzle) in this chapter, with an `if`/`else if`/`else` chain that tests which of the three cases applies. The final `else`, corresponding to the third case, makes the recursive call. Each of the branches should contain a `return` statement or in some other way arrange for a specific value to be returned.
{{index "stack overflow"}}
-When given a negative number, the function will recurse again and
-again, passing itself an ever more negative number, thus getting
-further and further away from returning a result. It will eventually
-run out of stack space and abort.
+When given a negative number, the function will recurse again and again, passing itself an ever more negative number, thus getting further and further away from returning a result. It will eventually run out of stack space and abort.
hint}}
@@ -1064,21 +752,11 @@ hint}}
{{index "bean counting (exercise)", [string, indexing], "zero-based counting", ["length property", "for string"]}}
-You can get the Nth character, or letter, from a string by writing
-`"string"[N]`. The returned value will be a string containing only one
-character (for example, `"b"`). The first character has position 0,
-which causes the last one to be found at position `string.length - 1`.
-In other words, a two-character string has length 2, and its
-characters have positions 0 and 1.
+You can get the Nth character, or letter, from a string by writing `"string"[N]`. The returned value will be a string containing only one character (for example, `"b"`). The first character has position 0, which causes the last one to be found at position `string.length - 1`. In other words, a two-character string has length 2, and its characters have positions 0 and 1.
-Write a function `countBs` that takes a string as its only argument
-and returns a number that indicates how many uppercase "B" characters
-there are in the string.
+Write a function `countBs` that takes a string as its only argument and returns a number that indicates how many uppercase "B" characters there are in the string.
-Next, write a function called `countChar` that behaves like `countBs`,
-except it takes a second argument that indicates the character that is
-to be counted (rather than counting only uppercase "B" characters).
-Rewrite `countBs` to make use of this new function.
+Next, write a function called `countChar` that behaves like `countBs`, except it takes a second argument that indicates the character that is to be counted (rather than counting only uppercase "B" characters). Rewrite `countBs` to make use of this new function.
{{if interactive
@@ -1097,15 +775,10 @@ if}}
{{index "bean counting (exercise)", ["length property", "for string"], "counter variable"}}
-Your function will need a ((loop)) that looks at every character in
-the string. It can run an index from zero to one below its length (`<
-string.length`). If the character at the current position is the same
-as the one the function is looking for, it adds 1 to a counter
-variable. Once the loop has finished, the counter can be returned.
+Your function will need a ((loop)) that looks at every character in the string. It can run an index from zero to one below its length (`< string.length`). If the character at the current position is the same as the one the function is looking for, it adds 1 to a counter variable. Once the loop has finished, the counter can be returned.
{{index "local binding"}}
-Take care to make all the bindings used in the function _local_ to the
-function by properly declaring them with the `let` or `const` keyword.
+Take care to make all the bindings used in the function _local_ to the function by properly declaring them with the `let` or `const` keyword.
hint}}
diff --git a/04_data.md b/04_data.md
index 52bc92c7e..21e59496f 100644
--- a/04_data.md
+++ b/04_data.md
@@ -4,10 +4,7 @@
{{quote {author: "Charles Babbage", title: "Passages from the Life of a Philosopher (1864)", chapter: true}
-On two occasions I have been asked, 'Pray, Mr. Babbage, if you put
-into the machine wrong figures, will the right answers come out?'
-[...] I am not able rightly to apprehend the kind of confusion of
-ideas that could provoke such a question.
+On two occasions I have been asked, 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?' [...] I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question.
quote}}
@@ -17,29 +14,15 @@ quote}}
{{index object, "data structure"}}
-Numbers, Booleans, and strings are the atoms that ((data)) structures
-are built from. Many types of information require more than one
-atom, though. _Objects_ allow us to group values—including other
-objects—to build more complex structures.
+Numbers, Booleans, and strings are the atoms that ((data)) structures are built from. Many types of information require more than one atom, though. _Objects_ allow us to group values—including other objects—to build more complex structures.
-The programs we have built so far have been limited by the fact that
-they were operating only on simple data types. This chapter will
-introduce basic data structures. By the end of it, you'll know enough
-to start writing useful programs.
+The programs we have built so far have been limited by the fact that they were operating only on simple data types. This chapter will introduce basic data structures. By the end of it, you'll know enough to start writing useful programs.
-The chapter will work through a more or less realistic programming
-example, introducing concepts as they apply to the problem at hand.
-The example code will often build on functions and bindings that were
-introduced earlier in the text.
+The chapter will work through a more or less realistic programming example, introducing concepts as they apply to the problem at hand. The example code will often build on functions and bindings that were introduced earlier in the text.
{{if book
-The online coding ((sandbox)) for the book
-([_https://eloquentjavascript.net/code_](https://eloquentjavascript.net/code))
-provides a way to run code in the context of a specific chapter. If
-you decide to work through the examples in another environment, be
-sure to first download the full code for this chapter from the sandbox
-page.
+The online coding ((sandbox)) for the book ([_https://eloquentjavascript.net/code_](https://eloquentjavascript.net/code)) provides a way to run code in the context of a specific chapter. If you decide to work through the examples in another environment, be sure to first download the full code for this chapter from the sandbox page.
if}}
@@ -47,56 +30,31 @@ if}}
{{index "weresquirrel example", lycanthropy}}
-Every now and then, usually between 8 p.m. and 10 p.m.,
-((Jacques)) finds himself transforming into a small furry rodent with
-a bushy tail.
-
-On one hand, Jacques is quite glad that he doesn't have classic
-lycanthropy. Turning into a squirrel does cause fewer problems than
-turning into a wolf. Instead of having to worry about accidentally
-eating the neighbor (_that_ would be awkward), he worries about being
-eaten by the neighbor's cat. After two occasions where he woke up on a
-precariously thin branch in the crown of an oak, naked and
-disoriented, he has taken to locking the doors and windows of his room
-at night and putting a few walnuts on the floor to keep himself busy.
-
-That takes care of the cat and tree problems. But Jacques would prefer
-to get rid of his condition entirely. The irregular occurrences of the
-transformation make him suspect that they might be triggered by
-something. For a while, he believed that it happened only on days when
-he had been near oak trees. But avoiding oak trees did not stop the
-problem.
+Every now and then, usually between 8 p.m. and 10 p.m., ((Jacques)) finds himself transforming into a small furry rodent with a bushy tail.
+
+On one hand, Jacques is quite glad that he doesn't have classic lycanthropy. Turning into a squirrel does cause fewer problems than turning into a wolf. Instead of having to worry about accidentally eating the neighbor (_that_ would be awkward), he worries about being eaten by the neighbor's cat. After two occasions where he woke up on a precariously thin branch in the crown of an oak, naked and disoriented, he has taken to locking the doors and windows of his room at night and putting a few walnuts on the floor to keep himself busy.
+
+That takes care of the cat and tree problems. But Jacques would prefer to get rid of his condition entirely. The irregular occurrences of the transformation make him suspect that they might be triggered by something. For a while, he believed that it happened only on days when he had been near oak trees. But avoiding oak trees did not stop the problem.
{{index journal}}
-Switching to a more scientific approach, Jacques has started keeping a
-daily log of everything he does on a given day and whether he changed
-form. With this data he hopes to narrow down the conditions that
-trigger the transformations.
+Switching to a more scientific approach, Jacques has started keeping a daily log of everything he does on a given day and whether he changed form. With this data he hopes to narrow down the conditions that trigger the transformations.
-The first thing he needs is a data structure to store this
-information.
+The first thing he needs is a data structure to store this information.
## Data sets
{{index ["data structure", collection], [memory, organization]}}
-To work with a chunk of digital data, we'll first have to find a way
-to represent it in our machine's memory. Say, for example, that we
-want to represent a ((collection)) of the numbers 2, 3, 5, 7, and 11.
+To work with a chunk of digital data, we'll first have to find a way to represent it in our machine's memory. Say, for example, that we want to represent a ((collection)) of the numbers 2, 3, 5, 7, and 11.
{{index string}}
-We could get creative with strings—after all, strings can have any
-length, so we can put a lot of data into them—and use `"2 3 5 7 11"`
-as our representation. But this is awkward. You'd have to somehow
-extract the digits and convert them back to numbers to access them.
+We could get creative with strings—after all, strings can have any length, so we can put a lot of data into them—and use `"2 3 5 7 11"` as our representation. But this is awkward. You'd have to somehow extract the digits and convert them back to numbers to access them.
{{index [array, creation], "[] (array)"}}
-Fortunately, JavaScript provides a data type specifically for storing
-sequences of values. It is called an _array_ and is written as a list
-of values between ((square brackets)), separated by commas.
+Fortunately, JavaScript provides a data type specifically for storing sequences of values. It is called an _array_ and is written as a list of values between ((square brackets)), separated by commas.
```
let listOfNumbers = [2, 3, 5, 7, 11];
@@ -110,20 +68,12 @@ console.log(listOfNumbers[2 - 1]);
{{index "[] (subscript)", [array, indexing]}}
-The notation for getting at the elements inside an array also uses
-((square brackets)). A pair of square brackets immediately after an
-expression, with another expression inside of them, will look up the
-element in the left-hand expression that corresponds to the
-_((index))_ given by the expression in the brackets.
+The notation for getting at the elements inside an array also uses ((square brackets)). A pair of square brackets immediately after an expression, with another expression inside of them, will look up the element in the left-hand expression that corresponds to the _((index))_ given by the expression in the brackets.
{{id array_indexing}}
{{index "zero-based counting"}}
-The first index of an array is zero, not one. So the first element is
-retrieved with `listOfNumbers[0]`. Zero-based counting has a long
-tradition in technology and in certain ways makes a lot of sense, but
-it takes some getting used to. Think of the index as the amount of
-items to skip, counting from the start of the array.
+The first index of an array is zero, not one. So the first element is retrieved with `listOfNumbers[0]`. Zero-based counting has a long tradition in technology and in certain ways makes a lot of sense, but it takes some getting used to. Think of the index as the amount of items to skip, counting from the start of the array.
{{id properties}}
@@ -131,19 +81,11 @@ items to skip, counting from the start of the array.
{{index "Math object", "Math.max function", ["length property", "for string"], [object, property], "period character", [property, access]}}
-We've seen a few suspicious-looking expressions like `myString.length`
-(to get the length of a string) and `Math.max` (the maximum function)
-in past chapters. These are expressions that access a _property_
-of some value. In the first case, we access the `length` property of
-the value in `myString`. In the second, we access the property named
-`max` in the `Math` object (which is a collection of
-mathematics-related constants and functions).
+We've seen a few suspicious-looking expressions like `myString.length` (to get the length of a string) and `Math.max` (the maximum function) in past chapters. These are expressions that access a _property_ of some value. In the first case, we access the `length` property of the value in `myString`. In the second, we access the property named `max` in the `Math` object (which is a collection of mathematics-related constants and functions).
{{index [property, access], null, undefined}}
-Almost all JavaScript values have properties. The exceptions are
-`null` and `undefined`. If you try to access a property on one of
-these nonvalues, you get an error.
+Almost all JavaScript values have properties. The exceptions are `null` and `undefined`. If you try to access a property on one of these nonvalues, you get an error.
```{test: no}
null.length;
@@ -153,35 +95,15 @@ null.length;
{{indexsee "dot character", "period character"}}
{{index "[] (subscript)", "period character", "square brackets", "computed property", [property, access]}}
-The two main ways to access properties in JavaScript are with a dot
-and with square brackets. Both `value.x` and `value[x]` access a
-property on `value`—but not necessarily the same property. The
-difference is in how `x` is interpreted. When using a dot, the word
-after the dot is the literal name of the property. When using square
-brackets, the expression between the brackets is _evaluated_ to get
-the property name. Whereas `value.x` fetches the property of `value`
-named "x", `value[x]` tries to evaluate the expression `x` and uses
-the result, converted to a string, as the property name.
-
-So if you know that the property you are interested in is called
-_color_, you say `value.color`. If you want to extract the property
-named by the value held in the binding `i`, you say `value[i]`.
-Property names are strings. They can be any string, but the dot notation works only with
-names that look like valid binding names. So if you want to access a
-property named _2_ or _John Doe_, you must use square brackets:
-`value[2]` or `value["John Doe"]`.
-
-The elements in an ((array)) are stored as the array's properties, using
-numbers as property names. Because you can't use the dot notation with
-numbers and usually want to use a binding that holds the index
-anyway, you have to use the bracket notation to get at them.
+The two main ways to access properties in JavaScript are with a dot and with square brackets. Both `value.x` and `value[x]` access a property on `value`—but not necessarily the same property. The difference is in how `x` is interpreted. When using a dot, the word after the dot is the literal name of the property. When using square brackets, the expression between the brackets is _evaluated_ to get the property name. Whereas `value.x` fetches the property of `value` named "x", `value[x]` tries to evaluate the expression `x` and uses the result, converted to a string, as the property name.
+
+So if you know that the property you are interested in is called _color_, you say `value.color`. If you want to extract the property named by the value held in the binding `i`, you say `value[i]`. Property names are strings. They can be any string, but the dot notation works only with names that look like valid binding names. So if you want to access a property named _2_ or _John Doe_, you must use square brackets: `value[2]` or `value["John Doe"]`.
+
+The elements in an ((array)) are stored as the array's properties, using numbers as property names. Because you can't use the dot notation with numbers and usually want to use a binding that holds the index anyway, you have to use the bracket notation to get at them.
{{index ["length property", "for array"], [array, "length of"]}}
-The `length` property of an array tells us how many elements it has.
-This property name is a valid binding name, and we know its name in
-advance, so to find the length of an array, you typically write
-`array.length` because that's easier to write than `array["length"]`.
+The `length` property of an array tells us how many elements it has. This property name is a valid binding name, and we know its name in advance, so to find the length of an array, you typically write `array.length` because that's easier to write than `array["length"]`.
{{id methods}}
@@ -189,8 +111,7 @@ advance, so to find the length of an array, you typically write
{{index [function, "as property"], method, string}}
-Both string and array values contain, in addition to the `length`
-property, a number of properties that hold function values.
+Both string and array values contain, in addition to the `length` property, a number of properties that hold function values.
```
let doh = "Doh";
@@ -202,25 +123,17 @@ console.log(doh.toUpperCase());
{{index "case conversion", "toUpperCase method", "toLowerCase method"}}
-Every string has a `toUpperCase` property. When called, it will return
-a copy of the string in which all letters have been converted to
-uppercase. There is also `toLowerCase`, going the other way.
+Every string has a `toUpperCase` property. When called, it will return a copy of the string in which all letters have been converted to uppercase. There is also `toLowerCase`, going the other way.
{{index "this binding"}}
-Interestingly, even though the call to `toUpperCase` does not pass any
-arguments, the function somehow has access to the string `"Doh"`, the
-value whose property we called. How this works is described in
-[Chapter ?](object#obj_methods).
+Interestingly, even though the call to `toUpperCase` does not pass any arguments, the function somehow has access to the string `"Doh"`, the value whose property we called. How this works is described in [Chapter ?](object#obj_methods).
-Properties that contain functions are generally called _methods_ of
-the value they belong to, as in "`toUpperCase` is a method of a
-string".
+Properties that contain functions are generally called _methods_ of the value they belong to, as in "`toUpperCase` is a method of a string".
{{id array_methods}}
-This example demonstrates two methods you can use to manipulate
-arrays:
+This example demonstrates two methods you can use to manipulate arrays:
```
let sequence = [1, 2, 3];
@@ -236,36 +149,21 @@ console.log(sequence);
{{index collection, array, "push method", "pop method"}}
-The `push` method adds values to the end of an array, and the
-`pop` method does the opposite, removing the last value in the array
-and returning it.
+The `push` method adds values to the end of an array, and the `pop` method does the opposite, removing the last value in the array and returning it.
{{index ["data structure", stack]}}
-These somewhat silly names are the traditional terms for operations on
-a _((stack))_. A stack, in programming, is a data structure that
-allows you to push values into it and pop them out again in the
-opposite order so that the thing that was added last is removed first.
-These are common in programming—you might remember the function ((call
-stack)) from [the previous chapter](functions#stack), which is an
-instance of the same idea.
+These somewhat silly names are the traditional terms for operations on a _((stack))_. A stack, in programming, is a data structure that allows you to push values into it and pop them out again in the opposite order so that the thing that was added last is removed first. These are common in programming—you might remember the function ((call stack)) from [the previous chapter](functions#stack), which is an instance of the same idea.
## Objects
{{index journal, "weresquirrel example", array, record}}
-Back to the weresquirrel. A set of daily log entries can be
-represented as an array. But the entries do not consist of just a
-number or a string—each entry needs to store a list of activities and
-a Boolean value that indicates whether Jacques turned into a squirrel
-or not. Ideally, we would like to group these together into a single
-value and then put those grouped values into an array of log entries.
+Back to the weresquirrel. A set of daily log entries can be represented as an array. But the entries do not consist of just a number or a string—each entry needs to store a list of activities and a Boolean value that indicates whether Jacques turned into a squirrel or not. Ideally, we would like to group these together into a single value and then put those grouped values into an array of log entries.
{{index [syntax, object], [property, definition], [braces, object], "{} (object)"}}
-Values of the type _((object))_ are arbitrary collections of
-properties. One way to create an object is by using braces as an
-expression.
+Values of the type _((object))_ are arbitrary collections of properties. One way to create an object is by using braces as an expression.
```
let day1 = {
@@ -283,11 +181,7 @@ console.log(day1.wolf);
{{index [quoting, "of object properties"], "colon character"}}
-Inside the braces, there is a list of properties separated by commas.
-Each property has a name followed by a colon and a value. When an
-object is written over multiple lines, indenting it like in the
-example helps with readability. Properties whose names aren't valid
-binding names or valid numbers have to be quoted.
+Inside the braces, there is a list of properties separated by commas. Each property has a name followed by a colon and a value. When an object is written over multiple lines, indenting it like in the example helps with readability. Properties whose names aren't valid binding names or valid numbers have to be quoted.
```
let descriptions = {
@@ -298,37 +192,23 @@ let descriptions = {
{{index [braces, object]}}
-This means that braces have _two_ meanings in JavaScript. At
-the start of a ((statement)), they start a ((block)) of statements. In
-any other position, they describe an object. Fortunately, it is rarely
-useful to start a statement with an object in braces, so the
-ambiguity between these two is not much of a problem.
+This means that braces have _two_ meanings in JavaScript. At the start of a ((statement)), they start a ((block)) of statements. In any other position, they describe an object. Fortunately, it is rarely useful to start a statement with an object in braces, so the ambiguity between these two is not much of a problem.
{{index undefined}}
-Reading a property that doesn't exist will give you the value
-`undefined`.
+Reading a property that doesn't exist will give you the value `undefined`.
{{index [property, assignment], mutability, "= operator"}}
-It is possible to assign a value to a property expression with the `=`
-operator. This will replace the property's value if it already existed
-or create a new property on the object if it didn't.
+It is possible to assign a value to a property expression with the `=` operator. This will replace the property's value if it already existed or create a new property on the object if it didn't.
{{index "tentacle (analogy)", [property, "model of"], [binding, "model of"]}}
-To briefly return to our tentacle model of ((binding))s—property
-bindings are similar. They _grasp_ values, but other bindings and
-properties might be holding onto those same values. You may think of
-objects as octopuses with any number of tentacles, each of which has a
-name tattooed on it.
+To briefly return to our tentacle model of ((binding))s—property bindings are similar. They _grasp_ values, but other bindings and properties might be holding onto those same values. You may think of objects as octopuses with any number of tentacles, each of which has a name tattooed on it.
{{index "delete operator", [property, deletion]}}
-The `delete` operator cuts off a tentacle from such an octopus. It is
-a unary operator that, when applied to an object property,
-will remove the named property from the object. This is not a common
-thing to do, but it is possible.
+The `delete` operator cuts off a tentacle from such an octopus. It is a unary operator that, when applied to an object property, will remove the named property from the object. This is not a common thing to do, but it is possible.
```
let anObject = {left: 1, right: 2};
@@ -345,26 +225,18 @@ console.log("right" in anObject);
{{index "in operator", [property, "testing for"], object}}
-The binary `in` operator, when applied to a string and an object,
-tells you whether that object has a property with that name. The difference
-between setting a property to `undefined` and actually deleting it is
-that, in the first case, the object still _has_ the property (it just
-doesn't have a very interesting value), whereas in the second case the
-property is no longer present and `in` will return `false`.
+The binary `in` operator, when applied to a string and an object, tells you whether that object has a property with that name. The difference between setting a property to `undefined` and actually deleting it is that, in the first case, the object still _has_ the property (it just doesn't have a very interesting value), whereas in the second case the property is no longer present and `in` will return `false`.
{{index "Object.keys function"}}
-To find out what properties an object has, you can use the
-`Object.keys` function. You give it an object, and it returns an array
-of strings—the object's property names.
+To find out what properties an object has, you can use the `Object.keys` function. You give it an object, and it returns an array of strings—the object's property names.
```
console.log(Object.keys({x: 0, y: 0, z: 2}));
// → ["x", "y", "z"]
```
-There's an `Object.assign` function that copies all properties from
-one object into another.
+There's an `Object.assign` function that copies all properties from one object into another.
```
let objectA = {a: 1, b: 2};
@@ -375,10 +247,7 @@ console.log(objectA);
{{index array, collection}}
-Arrays, then, are just a kind of object specialized for storing
-sequences of things. If you evaluate `typeof []`, it produces
-`"object"`. You can see them as long, flat octopuses with all their
-tentacles in a neat row, labeled with numbers.
+Arrays, then, are just a kind of object specialized for storing sequences of things. If you evaluate `typeof []`, it produces `"object"`. You can see them as long, flat octopuses with all their tentacles in a neat row, labeled with numbers.
{{index journal, "weresquirrel example"}}
@@ -401,30 +270,17 @@ let journal = [
## Mutability
-We will get to actual programming _real_ soon now. First there's one
-more piece of theory to understand.
+We will get to actual programming _real_ soon now. First there's one more piece of theory to understand.
{{index mutability, "side effect", number, string, Boolean, [object, mutability]}}
-We saw that object values can be modified. The types of values
-discussed in earlier chapters, such as numbers, strings, and Booleans,
-are all _((immutable))_—it is impossible to change values of those
-types. You can combine them and derive new values from them, but when
-you take a specific string value, that value will always remain the
-same. The text inside it cannot be changed. If you have a string that
-contains `"cat"`, it is not possible for other code to change a
-character in your string to make it spell `"rat"`.
+We saw that object values can be modified. The types of values discussed in earlier chapters, such as numbers, strings, and Booleans, are all _((immutable))_—it is impossible to change values of those types. You can combine them and derive new values from them, but when you take a specific string value, that value will always remain the same. The text inside it cannot be changed. If you have a string that contains `"cat"`, it is not possible for other code to change a character in your string to make it spell `"rat"`.
-Objects work differently. You _can_ change their properties,
-causing a single object value to have different content at different times.
+Objects work differently. You _can_ change their properties, causing a single object value to have different content at different times.
{{index [object, identity], identity, [memory, organization], mutability}}
-When we have two numbers, 120 and 120, we can consider them precisely
-the same number, whether or not they refer to the same physical bits.
-With objects, there is a difference between having two references to
-the same object and having two different objects that contain the same
-properties. Consider the following code:
+When we have two numbers, 120 and 120, we can consider them precisely the same number, whether or not they refer to the same physical bits. With objects, there is a difference between having two references to the same object and having two different objects that contain the same properties. Consider the following code:
```
let object1 = {value: 10};
@@ -445,20 +301,11 @@ console.log(object3.value);
{{index "tentacle (analogy)", [binding, "model of"]}}
-The `object1` and `object2` bindings grasp the _same_ object, which is
-why changing `object1` also changes the value of `object2`. They are
-said to have the same _identity_. The binding `object3` points to a
-different object, which initially contains the same properties as
-`object1` but lives a separate life.
+The `object1` and `object2` bindings grasp the _same_ object, which is why changing `object1` also changes the value of `object2`. They are said to have the same _identity_. The binding `object3` points to a different object, which initially contains the same properties as `object1` but lives a separate life.
{{index "const keyword", "let keyword", [binding, "as state"]}}
-Bindings can also be changeable or constant, but this is separate from
-the way their values behave. Even though number values don't change,
-you can use a `let` binding to keep track of a changing number by
-changing the value the binding points at. Similarly, though a `const`
-binding to an object can itself not be changed and will continue to
-point at the same object, the _contents_ of that object might change.
+Bindings can also be changeable or constant, but this is separate from the way their values behave. Even though number values don't change, you can use a `let` binding to keep track of a changing number by changing the value the binding points at. Similarly, though a `const` binding to an object can itself not be changed and will continue to point at the same object, the _contents_ of that object might change.
```{test: no}
const score = {visitors: 0, home: 0};
@@ -470,20 +317,13 @@ score = {visitors: 1, home: 1};
{{index "== operator", [comparison, "of objects"], "deep comparison"}}
-When you compare objects with JavaScript's `==` operator, it compares
-by identity: it will produce `true` only if both objects are precisely
-the same value. Comparing different objects will return `false`, even
-if they have identical properties. There is no "deep" comparison
-operation built into JavaScript, which compares objects by contents,
-but it is possible to write it yourself (which is one of the
-[exercises](data#exercise_deep_compare) at the end of this chapter).
+When you compare objects with JavaScript's `==` operator, it compares by identity: it will produce `true` only if both objects are precisely the same value. Comparing different objects will return `false`, even if they have identical properties. There is no "deep" comparison operation built into JavaScript, which compares objects by contents, but it is possible to write it yourself (which is one of the [exercises](data#exercise_deep_compare) at the end of this chapter).
## The lycanthrope's log
{{index "weresquirrel example", lycanthropy, "addEntry function"}}
-So, Jacques starts up his JavaScript interpreter and sets up the
-environment he needs to keep his ((journal)).
+So, Jacques starts up his JavaScript interpreter and sets up the environment he needs to keep his ((journal)).
```{includeCode: true}
let journal = [];
@@ -495,15 +335,9 @@ function addEntry(events, squirrel) {
{{index [braces, object], "{} (object)", [property, definition]}}
-Note that the object added to the journal looks a little odd. Instead
-of declaring properties like `events: events`, it just gives a
-property name. This is shorthand that means the same thing—if a
-property name in brace notation isn't followed by a value, its
-value is taken from the binding with the same name.
+Note that the object added to the journal looks a little odd. Instead of declaring properties like `events: events`, it just gives a property name. This is shorthand that means the same thing—if a property name in brace notation isn't followed by a value, its value is taken from the binding with the same name.
-So then, every evening at 10 p.m.—or sometimes the next morning, after
-climbing down from the top shelf of his bookcase—Jacques records the
-day.
+So then, every evening at 10 p.m.—or sometimes the next morning, after climbing down from the top shelf of his bookcase—Jacques records the day.
```
addEntry(["work", "touched tree", "pizza", "running",
@@ -514,33 +348,17 @@ addEntry(["weekend", "cycling", "break", "peanuts",
"beer"], true);
```
-Once he has enough data points, he intends to use statistics to find
-out which of these events may be related to the squirrelifications.
+Once he has enough data points, he intends to use statistics to find out which of these events may be related to the squirrelifications.
{{index correlation}}
-_Correlation_ is a measure of ((dependence)) between statistical
-variables. A statistical variable is not quite the same as a
-programming variable. In statistics you typically have a set of
-_measurements_, and each variable is measured for every measurement.
-Correlation between variables is usually expressed as a value that
-ranges from -1 to 1. Zero correlation means the variables are not
-related. A correlation of one indicates that the two are perfectly
-related—if you know one, you also know the other. Negative one also
-means that the variables are perfectly related but that they are
-opposites—when one is true, the other is false.
+_Correlation_ is a measure of ((dependence)) between statistical variables. A statistical variable is not quite the same as a programming variable. In statistics you typically have a set of _measurements_, and each variable is measured for every measurement. Correlation between variables is usually expressed as a value that ranges from -1 to 1. Zero correlation means the variables are not related. A correlation of one indicates that the two are perfectly related—if you know one, you also know the other. Negative one also means that the variables are perfectly related but that they are opposites—when one is true, the other is false.
{{index "phi coefficient"}}
-To compute the measure of correlation between two Boolean variables,
-we can use the _phi coefficient_ (_ϕ_). This is a formula whose input
-is a ((frequency table)) containing the number of times the different
-combinations of the variables were observed. The output of the formula
-is a number between -1 and 1 that describes the correlation.
+To compute the measure of correlation between two Boolean variables, we can use the _phi coefficient_ (_ϕ_). This is a formula whose input is a ((frequency table)) containing the number of times the different combinations of the variables were observed. The output of the formula is a number between -1 and 1 that describes the correlation.
-We could take the event of eating ((pizza)) and put that in a
-frequency table like this, where each number indicates the amount of
-times that combination occurred in our measurements:
+We could take the event of eating ((pizza)) and put that in a frequency table like this, where each number indicates the amount of times that combination occurred in our measurements:
{{figure {url: "img/pizza-squirrel.svg", alt: "Eating pizza versus turning into a squirrel", width: "7cm"}}}
@@ -548,18 +366,7 @@ If we call that table _n_, we can compute _ϕ_ using the following formula:
{{if html
-
-
-
ϕ =
-
-
n11n00 −
- n10n01
-
√
- n1•n0•n•1n•0
-
-
-
-
+
ϕ =
n11n00 − n10n01
√n1•n0•n•1n•0
if}}
@@ -569,55 +376,27 @@ if}}
if}}
-(If at this point you're putting the book down to focus on a terrible
-flashback to 10th grade math class—hold on! I do not intend to torture
-you with endless pages of cryptic notation—it's just this one formula for
-now. And even with this one, all we do is turn it into JavaScript.)
+(If at this point you're putting the book down to focus on a terrible flashback to 10th grade math class—hold on! I do not intend to torture you with endless pages of cryptic notation—it's just this one formula for now. And even with this one, all we do is turn it into JavaScript.)
-The notation [_n_~01~]{if html}[[$n_{01}$]{latex}]{if tex} indicates
-the number of measurements where the first variable (squirrelness) is
-false (0) and the second variable (pizza) is true (1). In the pizza
-table, [_n_~01~]{if html}[[$n_{01}$]{latex}]{if tex} is 9.
+The notation [_n_~01~]{if html}[[$n_{01}$]{latex}]{if tex} indicates the number of measurements where the first variable (squirrelness) is false (0) and the second variable (pizza) is true (1). In the pizza table, [_n_~01~]{if html}[[$n_{01}$]{latex}]{if tex} is 9.
-The value [_n_~1•~]{if html}[[$n_{1\bullet}$]{latex}]{if tex} refers
-to the sum of all measurements where the first variable is true, which
-is 5 in the example table. Likewise, [_n_~•0~]{if
-html}[[$n_{\bullet0}$]{latex}]{if tex} refers to the sum of the
-measurements where the second variable is false.
+The value [_n_~1•~]{if html}[[$n_{1\bullet}$]{latex}]{if tex} refers to the sum of all measurements where the first variable is true, which is 5 in the example table. Likewise, [_n_~•0~]{if html}[[$n_{\bullet0}$]{latex}]{if tex} refers to the sum of the measurements where the second variable is false.
{{index correlation, "phi coefficient"}}
-So for the pizza table, the part above the division line (the
-dividend) would be 1×76−4×9 = 40, and the part below it (the
-divisor) would be the square root of 5×85×10×80, or [√340000]{if
-html}[[$\sqrt{340000}$]{latex}]{if tex}. This comes out to _ϕ_ ≈
-0.069, which is tiny. Eating ((pizza)) does not appear to have
-influence on the transformations.
+So for the pizza table, the part above the division line (the dividend) would be 1×76−4×9 = 40, and the part below it (the divisor) would be the square root of 5×85×10×80, or [√340000]{if html}[[$\sqrt{340000}$]{latex}]{if tex}. This comes out to _ϕ_ ≈ 0.069, which is tiny. Eating ((pizza)) does not appear to have influence on the transformations.
## Computing correlation
{{index [array, "as table"], [nesting, "of arrays"]}}
-We can represent a two-by-two ((table)) in JavaScript with a
-four-element array (`[76, 9, 4, 1]`). We could also use other
-representations, such as an array containing two two-element arrays
-(`[[76, 9], [4, 1]]`) or an object with property names like `"11"` and
-`"01"`, but the flat array is simple and makes the expressions that
-access the table pleasantly short. We'll interpret the indices to the
-array as two-((bit)) ((binary number))s, where the leftmost (most
-significant) digit refers to the squirrel variable and the rightmost
-(least significant) digit refers to the event variable. For example,
-the binary number `10` refers to the case where Jacques did turn into
-a squirrel, but the event (say, "pizza") didn't occur. This happened
-four times. And since binary `10` is 2 in decimal notation, we will
-store this number at index 2 of the array.
+We can represent a two-by-two ((table)) in JavaScript with a four-element array (`[76, 9, 4, 1]`). We could also use other representations, such as an array containing two two-element arrays (`[[76, 9], [4, 1]]`) or an object with property names like `"11"` and `"01"`, but the flat array is simple and makes the expressions that access the table pleasantly short. We'll interpret the indices to the array as two-((bit)) ((binary number))s, where the leftmost (most significant) digit refers to the squirrel variable and the rightmost (least significant) digit refers to the event variable. For example, the binary number `10` refers to the case where Jacques did turn into a squirrel, but the event (say, "pizza") didn't occur. This happened four times. And since binary `10` is 2 in decimal notation, we will store this number at index 2 of the array.
{{index "phi coefficient", "phi function"}}
{{id phi_function}}
-This is the function that computes the _ϕ_ coefficient from such an
-array:
+This is the function that computes the _ϕ_ coefficient from such an array:
```{includeCode: strip_log, test: clip}
function phi(table) {
@@ -634,28 +413,15 @@ console.log(phi([76, 9, 4, 1]));
{{index "square root", "Math.sqrt function"}}
-This is a direct translation of the _ϕ_ formula into JavaScript.
-`Math.sqrt` is the square root function, as provided by the `Math`
-object in a standard JavaScript environment. We have to add two fields
-from the table to get fields like [n~1•~]{if
-html}[[$n_{1\bullet}$]{latex}]{if tex} because the sums of rows or
-columns are not stored directly in our data structure.
+This is a direct translation of the _ϕ_ formula into JavaScript. `Math.sqrt` is the square root function, as provided by the `Math` object in a standard JavaScript environment. We have to add two fields from the table to get fields like [n~1•~]{if html}[[$n_{1\bullet}$]{latex}]{if tex} because the sums of rows or columns are not stored directly in our data structure.
{{index "JOURNAL data set"}}
-Jacques kept his journal for three months. The resulting ((data set))
-is available in the [coding
-sandbox](https://eloquentjavascript.net/code#4) for this chapter[
-([_https://eloquentjavascript.net/code#4_](https://eloquentjavascript.net/code#4))]{if
-book}, where it is stored in the `JOURNAL` binding and in a
-downloadable
-[file](https://eloquentjavascript.net/code/journal.js).
+Jacques kept his journal for three months. The resulting ((data set)) is available in the [coding sandbox](https://eloquentjavascript.net/code#4) for this chapter[ ([_https://eloquentjavascript.net/code#4_](https://eloquentjavascript.net/code#4))]{if book}, where it is stored in the `JOURNAL` binding and in a downloadable [file](https://eloquentjavascript.net/code/journal.js).
{{index "tableFor function"}}
-To extract a two-by-two ((table)) for a specific event from the
-journal, we must loop over all the entries and tally how many times
-the event occurs in relation to squirrel transformations.
+To extract a two-by-two ((table)) for a specific event from the journal, we must loop over all the entries and tally how many times the event occurs in relation to squirrel transformations.
```{includeCode: strip_log}
function tableFor(event, journal) {
@@ -675,22 +441,13 @@ console.log(tableFor("pizza", JOURNAL));
{{index [array, searching], "includes method"}}
-Arrays have an `includes` method that checks whether a given value
-exists in the array. The function uses that to determine whether the
-event name it is interested in is part of the event list for a given
-day.
+Arrays have an `includes` method that checks whether a given value exists in the array. The function uses that to determine whether the event name it is interested in is part of the event list for a given day.
{{index [array, indexing]}}
-The body of the loop in `tableFor` figures out which box in the table
-each journal entry falls into by checking whether the entry contains
-the specific event it's interested in and whether the event happens
-alongside a squirrel incident. The loop then adds one to the correct
-box in the table.
+The body of the loop in `tableFor` figures out which box in the table each journal entry falls into by checking whether the entry contains the specific event it's interested in and whether the event happens alongside a squirrel incident. The loop then adds one to the correct box in the table.
-We now have the tools we need to compute individual ((correlation))s.
-The only step remaining is to find a correlation for every type of
-event that was recorded and see whether anything stands out.
+We now have the tools we need to compute individual ((correlation))s. The only step remaining is to find a correlation for every type of event that was recorded and see whether anything stands out.
{{id for_of_loop}}
@@ -707,10 +464,7 @@ for (let i = 0; i < JOURNAL.length; i++) {
}
```
-This kind of loop is common in classical JavaScript—going over arrays
-one element at a time is something that comes up a lot, and to do that
-you'd run a counter over the length of the array and pick out each
-element in turn.
+This kind of loop is common in classical JavaScript—going over arrays one element at a time is something that comes up a lot, and to do that you'd run a counter over the length of the array and pick out each element in turn.
There is a simpler way to write such loops in modern JavaScript.
@@ -722,11 +476,7 @@ for (let entry of JOURNAL) {
{{index "for/of loop"}}
-When a `for` loop looks like this, with the word `of` after a variable
-definition, it will loop over the elements of the value given after
-`of`. This works not only for arrays but also for strings and some
-other data structures. We'll discuss _how_ it works in [Chapter
-?](object).
+When a `for` loop looks like this, with the word `of` after a variable definition, it will loop over the elements of the value given after `of`. This works not only for arrays but also for strings and some other data structures. We'll discuss _how_ it works in [Chapter ?](object).
{{id analysis}}
@@ -734,9 +484,7 @@ other data structures. We'll discuss _how_ it works in [Chapter
{{index journal, "weresquirrel example", "journalEvents function"}}
-We need to compute a correlation for every type of event that occurs
-in the data set. To do that, we first need to _find_ every type of
-event.
+We need to compute a correlation for every type of event that occurs in the data set. To do that, we first need to _find_ every type of event.
{{index "includes method", "push method"}}
@@ -757,9 +505,7 @@ console.log(journalEvents(JOURNAL));
// → ["carrot", "exercise", "weekend", "bread", …]
```
-By going over all the events and adding those that aren't already in
-there to the `events` array, the function collects every type of
-event.
+By going over all the events and adding those that aren't already in there to the `events` array, the function collects every type of event.
Using that, we can see all the ((correlation))s.
@@ -775,10 +521,7 @@ for (let event of journalEvents(JOURNAL)) {
// and so on...
```
-Most correlations seem to lie close to zero. Eating carrots, bread, or
-pudding apparently does not trigger squirrel-lycanthropy. It _does_
-seem to occur somewhat more often on weekends. Let's filter the
-results to show only correlations greater than 0.1 or less than -0.1.
+Most correlations seem to lie close to zero. Eating carrots, bread, or pudding apparently does not trigger squirrel-lycanthropy. It _does_ seem to occur somewhat more often on weekends. Let's filter the results to show only correlations greater than 0.1 or less than -0.1.
```{test: no, startCode: true}
for (let event of journalEvents(JOURNAL)) {
@@ -796,10 +539,7 @@ for (let event of journalEvents(JOURNAL)) {
// → peanuts: 0.5902679812
```
-Aha! There are two factors with a ((correlation)) that's clearly stronger
-than the others. Eating ((peanuts)) has a strong positive effect on
-the chance of turning into a squirrel, whereas brushing his teeth has
-a significant negative effect.
+Aha! There are two factors with a ((correlation)) that's clearly stronger than the others. Eating ((peanuts)) has a strong positive effect on the chance of turning into a squirrel, whereas brushing his teeth has a significant negative effect.
Interesting. Let's try something.
@@ -814,40 +554,25 @@ console.log(phi(tableFor("peanut teeth", JOURNAL)));
// → 1
```
-That's a strong result. The phenomenon occurs precisely when Jacques
-eats ((peanuts)) and fails to brush his teeth. If only he weren't such
-a slob about dental hygiene, he'd have never even noticed his
-affliction.
+That's a strong result. The phenomenon occurs precisely when Jacques eats ((peanuts)) and fails to brush his teeth. If only he weren't such a slob about dental hygiene, he'd have never even noticed his affliction.
-Knowing this, Jacques stops eating peanuts altogether and finds that
-his transformations don't come back.
+Knowing this, Jacques stops eating peanuts altogether and finds that his transformations don't come back.
{{index "weresquirrel example"}}
-For a few years, things go great for Jacques. But at some point he
-loses his job. Because he lives in a nasty country where having no job
-means having no medical services, he is forced to take employment with
-a ((circus)) where he performs as _The Incredible Squirrelman_,
-stuffing his mouth with peanut butter before every show.
+For a few years, things go great for Jacques. But at some point he loses his job. Because he lives in a nasty country where having no job means having no medical services, he is forced to take employment with a ((circus)) where he performs as _The Incredible Squirrelman_, stuffing his mouth with peanut butter before every show.
-One day, fed up with this pitiful existence, Jacques fails to change
-back into his human form, hops through a crack in the circus tent, and
-vanishes into the forest. He is never seen again.
+One day, fed up with this pitiful existence, Jacques fails to change back into his human form, hops through a crack in the circus tent, and vanishes into the forest. He is never seen again.
## Further arrayology
{{index [array, methods], [method, array]}}
-Before finishing the chapter, I want to introduce you to a few more
-object-related concepts. I'll start by introducing some generally
-useful array methods.
+Before finishing the chapter, I want to introduce you to a few more object-related concepts. I'll start by introducing some generally useful array methods.
{{index "push method", "pop method", "shift method", "unshift method"}}
-We saw `push` and `pop`, which add and remove elements at the
-end of an array, [earlier](data#array_methods) in this
-chapter. The corresponding methods for adding and removing things at
-the start of an array are called `unshift` and `shift`.
+We saw `push` and `pop`, which add and remove elements at the end of an array, [earlier](data#array_methods) in this chapter. The corresponding methods for adding and removing things at the start of an array are called `unshift` and `shift`.
```
let todoList = [];
@@ -864,19 +589,11 @@ function rememberUrgently(task) {
{{index "task management example"}}
-That program manages a queue of tasks. You add tasks to the end of the
-queue by calling `remember("groceries")`, and when you're ready to do
-something, you call `getTask()` to get (and remove) the front item
-from the queue. The `rememberUrgently` function also adds a task but
-adds it to the front instead of the back of the queue.
+That program manages a queue of tasks. You add tasks to the end of the queue by calling `remember("groceries")`, and when you're ready to do something, you call `getTask()` to get (and remove) the front item from the queue. The `rememberUrgently` function also adds a task but adds it to the front instead of the back of the queue.
{{index [array, searching], "indexOf method", "lastIndexOf method"}}
-To search for a specific value, arrays provide an `indexOf` method. The method
-searches through the array from the start to the end and returns the
-index at which the requested value was found—or -1 if it wasn't found.
-To search from the end instead of the start, there's a similar method
-called `lastIndexOf`.
+To search for a specific value, arrays provide an `indexOf` method. The method searches through the array from the start to the end and returns the index at which the requested value was found—or -1 if it wasn't found. To search from the end instead of the start, there's a similar method called `lastIndexOf`.
```
console.log([1, 2, 3, 2, 1].indexOf(2));
@@ -885,14 +602,11 @@ console.log([1, 2, 3, 2, 1].lastIndexOf(2));
// → 3
```
-Both `indexOf` and `lastIndexOf` take an optional second argument that
-indicates where to start searching.
+Both `indexOf` and `lastIndexOf` take an optional second argument that indicates where to start searching.
{{index "slice method", [array, indexing]}}
-Another fundamental array method is `slice`, which takes start and end
-indices and returns an array that has only the elements between them.
-The start index is inclusive, the end index exclusive.
+Another fundamental array method is `slice`, which takes start and end indices and returns an array that has only the elements between them. The start index is inclusive, the end index exclusive.
```
console.log([0, 1, 2, 3, 4].slice(2, 4));
@@ -903,18 +617,13 @@ console.log([0, 1, 2, 3, 4].slice(2));
{{index [string, indexing]}}
-When the end index is not given, `slice` will take all of the elements
-after the start index. You can also omit the start index to copy the
-entire array.
+When the end index is not given, `slice` will take all of the elements after the start index. You can also omit the start index to copy the entire array.
{{index concatenation, "concat method"}}
-The `concat` method can be used to glue arrays together to create a
-new array, similar to what the `+` operator does for strings.
+The `concat` method can be used to glue arrays together to create a new array, similar to what the `+` operator does for strings.
-The following example shows both `concat` and `slice` in action. It takes
-an array and an index, and it returns a new array that is a copy of
-the original array with the element at the given index removed.
+The following example shows both `concat` and `slice` in action. It takes an array and an index, and it returns a new array that is a copy of the original array with the element at the given index removed.
```
function remove(array, index) {
@@ -925,15 +634,13 @@ console.log(remove(["a", "b", "c", "d", "e"], 2));
// → ["a", "b", "d", "e"]
```
-If you pass `concat` an argument that is not an array, that value will
-be added to the new array as if it were a one-element array.
+If you pass `concat` an argument that is not an array, that value will be added to the new array as if it were a one-element array.
## Strings and their properties
{{index [string, properties]}}
-We can read properties like `length` and `toUpperCase` from string
-values. But if you try to add a new property, it doesn't stick.
+We can read properties like `length` and `toUpperCase` from string values. But if you try to add a new property, it doesn't stick.
```
let kim = "Kim";
@@ -942,16 +649,11 @@ console.log(kim.age);
// → undefined
```
-Values of type string, number, and Boolean are not objects, and though
-the language doesn't complain if you try to set new properties on
-them, it doesn't actually store those properties. As mentioned earlier,
-such values are immutable and cannot be changed.
+Values of type string, number, and Boolean are not objects, and though the language doesn't complain if you try to set new properties on them, it doesn't actually store those properties. As mentioned earlier, such values are immutable and cannot be changed.
{{index [string, methods], "slice method", "indexOf method", [string, searching]}}
-But these types do have built-in properties. Every string value has a
-number of methods. Some very useful ones are `slice` and `indexOf`,
-which resemble the array methods of the same name.
+But these types do have built-in properties. Every string value has a number of methods. Some very useful ones are `slice` and `indexOf`, which resemble the array methods of the same name.
```
console.log("coconuts".slice(4, 7));
@@ -960,9 +662,7 @@ console.log("coconut".indexOf("u"));
// → 5
```
-One difference is that a string's `indexOf` can search for a string
-containing more than one character, whereas the corresponding array
-method looks only for a single element.
+One difference is that a string's `indexOf` can search for a string containing more than one character, whereas the corresponding array method looks only for a single element.
```
console.log("one two three".indexOf("ee"));
@@ -971,17 +671,14 @@ console.log("one two three".indexOf("ee"));
{{index [whitespace, trimming], "trim method"}}
-The `trim` method removes whitespace (spaces, newlines, tabs, and
-similar characters) from the start and end of a string.
+The `trim` method removes whitespace (spaces, newlines, tabs, and similar characters) from the start and end of a string.
```
console.log(" okay \n ".trim());
// → okay
```
-The `zeroPad` function from the [previous chapter](functions) also
-exists as a method. It is called `padStart` and takes the desired
-length and padding character as arguments.
+The `zeroPad` function from the [previous chapter](functions) also exists as a method. It is called `padStart` and takes the desired length and padding character as arguments.
```
console.log(String(6).padStart(3, "0"));
@@ -990,8 +687,7 @@ console.log(String(6).padStart(3, "0"));
{{id split}}
-You can split a string on every occurrence of another string with
-`split` and join it again with `join`.
+You can split a string on every occurrence of another string with `split` and join it again with `join`.
```
let sentence = "Secretarybirds specialize in stomping";
@@ -1004,9 +700,7 @@ console.log(words.join(". "));
{{index "repeat method"}}
-A string can be repeated with the `repeat` method, which creates a new
-string containing multiple copies of the original string, glued
-together.
+A string can be repeated with the `repeat` method, which creates a new string containing multiple copies of the original string, glued together.
```
console.log("LA".repeat(3));
@@ -1015,10 +709,7 @@ console.log("LA".repeat(3));
{{index ["length property", "for string"], [string, indexing]}}
-We have already seen the string type's `length` property. Accessing
-the individual characters in a string looks like accessing array
-elements (with a caveat that we'll discuss in [Chapter
-?](higher_order#code_units)).
+We have already seen the string type's `length` property. Accessing the individual characters in a string looks like accessing array elements (with a caveat that we'll discuss in [Chapter ?](higher_order#code_units)).
```
let string = "abc";
@@ -1034,14 +725,11 @@ console.log(string[1]);
{{index "Math.max function"}}
-It can be useful for a function to accept any number of ((argument))s.
-For example, `Math.max` computes the maximum of _all_ the arguments it
-is given.
+It can be useful for a function to accept any number of ((argument))s. For example, `Math.max` computes the maximum of _all_ the arguments it is given.
{{index "period character", "max example", spread}}
-To write such a function, you put three dots before the function's
-last ((parameter)), like this:
+To write such a function, you put three dots before the function's last ((parameter)), like this:
```{includeCode: strip_log}
function max(...numbers) {
@@ -1055,15 +743,11 @@ console.log(max(4, 1, 9, -2));
// → 9
```
-When such a function is called, the _((rest parameter))_ is bound to
-an array containing all further arguments. If there are other
-parameters before it, their values aren't part of that array. When, as
-in `max`, it is the only parameter, it will hold all arguments.
+When such a function is called, the _((rest parameter))_ is bound to an array containing all further arguments. If there are other parameters before it, their values aren't part of that array. When, as in `max`, it is the only parameter, it will hold all arguments.
{{index [function, application]}}
-You can use a similar three-dot notation to _call_ a function with an
-array of arguments.
+You can use a similar three-dot notation to _call_ a function with an array of arguments.
```
let numbers = [5, 1, 7];
@@ -1071,14 +755,11 @@ console.log(max(...numbers));
// → 7
```
-This "((spread))s" out the array into the function call, passing its
-elements as separate arguments. It is possible to include an array
-like that along with other arguments, as in `max(9, ...numbers, 2)`.
+This "((spread))s" out the array into the function call, passing its elements as separate arguments. It is possible to include an array like that along with other arguments, as in `max(9, ...numbers, 2)`.
{{index [array, "of rest arguments"], "square brackets"}}
-Square bracket array notation similarly allows the triple-dot operator
-to spread another array into the new array.
+Square bracket array notation similarly allows the triple-dot operator to spread another array into the new array.
```
let words = ["never", "fully"];
@@ -1090,45 +771,25 @@ console.log(["will", ...words, "understand"]);
{{index "Math object", "Math.min function", "Math.max function", "Math.sqrt function", minimum, maximum, "square root"}}
-As we've seen, `Math` is a grab bag of number-related utility
-functions, such as `Math.max` (maximum), `Math.min` (minimum), and
-`Math.sqrt` (square root).
+As we've seen, `Math` is a grab bag of number-related utility functions, such as `Math.max` (maximum), `Math.min` (minimum), and `Math.sqrt` (square root).
{{index namespace, [object, property]}}
{{id namespace_pollution}}
-The `Math` object is used as a container to group a bunch of related
-functionality. There is only one `Math` object, and it is almost never
-useful as a value. Rather, it provides a _namespace_ so that all these
-functions and values do not have to be global bindings.
+The `Math` object is used as a container to group a bunch of related functionality. There is only one `Math` object, and it is almost never useful as a value. Rather, it provides a _namespace_ so that all these functions and values do not have to be global bindings.
{{index [binding, naming]}}
-Having too many global bindings "pollutes" the namespace. The more
-names have been taken, the more likely you are to accidentally
-overwrite the value of some existing binding. For example, it's not
-unlikely to want to name something `max` in one of your programs.
-Since JavaScript's built-in `max` function is tucked safely inside the
-`Math` object, we don't have to worry about overwriting it.
+Having too many global bindings "pollutes" the namespace. The more names have been taken, the more likely you are to accidentally overwrite the value of some existing binding. For example, it's not unlikely to want to name something `max` in one of your programs. Since JavaScript's built-in `max` function is tucked safely inside the `Math` object, we don't have to worry about overwriting it.
{{index "let keyword", "const keyword"}}
-Many languages will stop you, or at least warn you, when you are
-defining a binding with a name that is already taken. JavaScript does
-this for bindings you declared with `let` or `const`
-but—perversely—not for standard bindings nor for bindings declared
-with `var` or `function`.
+Many languages will stop you, or at least warn you, when you are defining a binding with a name that is already taken. JavaScript does this for bindings you declared with `let` or `const` but—perversely—not for standard bindings nor for bindings declared with `var` or `function`.
{{index "Math.cos function", "Math.sin function", "Math.tan function", "Math.acos function", "Math.asin function", "Math.atan function", "Math.PI constant", cosine, sine, tangent, "PI constant", pi}}
-Back to the `Math` object. If you need to do ((trigonometry)), `Math`
-can help. It contains `cos` (cosine), `sin` (sine), and `tan`
-(tangent), as well as their inverse functions, `acos`, `asin`, and
-`atan`, respectively. The number π (pi)—or at least the closest
-approximation that fits in a JavaScript number—is available as
-`Math.PI`. There is an old programming tradition of writing the names
-of ((constant)) values in all caps.
+Back to the `Math` object. If you need to do ((trigonometry)), `Math` can help. It contains `cos` (cosine), `sin` (sine), and `tan` (tangent), as well as their inverse functions, `acos`, `asin`, and `atan`, respectively. The number π (pi)—or at least the closest approximation that fits in a JavaScript number—is available as `Math.PI`. There is an old programming tradition of writing the names of ((constant)) values in all caps.
```{test: no}
function randomPointOnCircle(radius) {
@@ -1140,15 +801,11 @@ console.log(randomPointOnCircle(2));
// → {x: 0.3667, y: 1.966}
```
-If sines and cosines are not something you are familiar with, don't
-worry. When they are used in this book, in [Chapter ?](dom#sin_cos),
-I'll explain them.
+If sines and cosines are not something you are familiar with, don't worry. When they are used in this book, in [Chapter ?](dom#sin_cos), I'll explain them.
{{index "Math.random function", "random number"}}
-The previous example used `Math.random`. This is a function that
-returns a new pseudorandom number between zero (inclusive) and one
-(exclusive) every time you call it.
+The previous example used `Math.random`. This is a function that returns a new pseudorandom number between zero (inclusive) and one (exclusive) every time you call it.
```{test: no}
console.log(Math.random());
@@ -1161,37 +818,22 @@ console.log(Math.random());
{{index "pseudorandom number", "random number"}}
-Though computers are deterministic machines—they always react the same
-way if given the same input—it is possible to have them produce
-numbers that appear random. To do that, the machine keeps some hidden
-value, and whenever you ask for a new random number, it performs
-complicated computations on this hidden value to create a new value.
-It stores a new value and returns some number derived from it. That
-way, it can produce ever new, hard-to-predict numbers in a way that
-_seems_ random.
+Though computers are deterministic machines—they always react the same way if given the same input—it is possible to have them produce numbers that appear random. To do that, the machine keeps some hidden value, and whenever you ask for a new random number, it performs complicated computations on this hidden value to create a new value. It stores a new value and returns some number derived from it. That way, it can produce ever new, hard-to-predict numbers in a way that _seems_ random.
{{index rounding, "Math.floor function"}}
-If we want a whole random number instead of a fractional one, we can
-use `Math.floor` (which rounds down to the nearest whole number) on
-the result of `Math.random`.
+If we want a whole random number instead of a fractional one, we can use `Math.floor` (which rounds down to the nearest whole number) on the result of `Math.random`.
```{test: no}
console.log(Math.floor(Math.random() * 10));
// → 2
```
-Multiplying the random number by 10 gives us a number greater than or
-equal to 0 and below 10. Since `Math.floor` rounds down, this
-expression will produce, with equal chance, any number from 0 through
-9.
+Multiplying the random number by 10 gives us a number greater than or equal to 0 and below 10. Since `Math.floor` rounds down, this expression will produce, with equal chance, any number from 0 through 9.
{{index "Math.ceil function", "Math.round function", "Math.abs function", "absolute value"}}
-There are also the functions `Math.ceil` (for "ceiling", which rounds
-up to a whole number), `Math.round` (to the nearest whole number), and
-`Math.abs`, which takes the absolute value of a number, meaning it
-negates negative values but leaves positive ones as they are.
+There are also the functions `Math.ceil` (for "ceiling", which rounds up to a whole number), `Math.round` (to the nearest whole number), and `Math.abs`, which takes the absolute value of a number, meaning it negates negative values but leaves positive ones as they are.
## Destructuring
@@ -1211,10 +853,7 @@ function phi(table) {
{{index "destructuring binding", parameter}}
-One of the reasons this function is awkward to read is that we have a
-binding pointing at our array, but we'd much prefer to have bindings
-for the _elements_ of the array, that is, `let n00 = table[0]` and so on.
-Fortunately, there is a succinct way to do this in JavaScript.
+One of the reasons this function is awkward to read is that we have a binding pointing at our array, but we'd much prefer to have bindings for the _elements_ of the array, that is, `let n00 = table[0]` and so on. Fortunately, there is a succinct way to do this in JavaScript.
```
function phi([n00, n01, n10, n11]) {
@@ -1226,15 +865,11 @@ function phi([n00, n01, n10, n11]) {
{{index "let keyword", "var keyword", "const keyword", [binding, destructuring]}}
-This also works for bindings created with `let`, `var`, or
-`const`. If you know the value you are binding is an array, you can
-use ((square brackets)) to "look inside" of the value, binding its
-contents.
+This also works for bindings created with `let`, `var`, or `const`. If you know the value you are binding is an array, you can use ((square brackets)) to "look inside" of the value, binding its contents.
{{index [object, property], [braces, object]}}
-A similar trick works for objects, using braces instead of square
-brackets.
+A similar trick works for objects, using braces instead of square brackets.
```
let {name} = {name: "Faraji", age: 23};
@@ -1244,46 +879,25 @@ console.log(name);
{{index null, undefined}}
-Note that if you try to destructure `null` or `undefined`, you get an
-error, much as you would if you directly try to access a property
-of those values.
+Note that if you try to destructure `null` or `undefined`, you get an error, much as you would if you directly try to access a property of those values.
## JSON
{{index [array, representation], [object, representation], "data format", [memory, organization]}}
-Because properties only grasp their value, rather than contain it,
-objects and arrays are stored in the computer's memory as
-sequences of bits holding the _((address))es_—the place in memory—of
-their contents. So an array with another array inside of it consists
-of (at least) one memory region for the inner array, and another for
-the outer array, containing (among other things) a binary number that
-represents the position of the inner array.
-
-If you want to save data in a file for later or send it to another
-computer over the network, you have to somehow convert these tangles
-of memory addresses to a description that can be stored or sent. You
-_could_ send over your entire computer memory along with the address
-of the value you're interested in, I suppose, but that doesn't seem
-like the best approach.
+Because properties only grasp their value, rather than contain it, objects and arrays are stored in the computer's memory as sequences of bits holding the _((address))es_—the place in memory—of their contents. So an array with another array inside of it consists of (at least) one memory region for the inner array, and another for the outer array, containing (among other things) a binary number that represents the position of the inner array.
+
+If you want to save data in a file for later or send it to another computer over the network, you have to somehow convert these tangles of memory addresses to a description that can be stored or sent. You _could_ send over your entire computer memory along with the address of the value you're interested in, I suppose, but that doesn't seem like the best approach.
{{indexsee "JavaScript Object Notation", JSON}}
{{index serialization, "World Wide Web"}}
-What we can do is _serialize_ the data. That means it is converted
-into a flat description. A popular serialization format is called
-_((JSON))_ (pronounced "Jason"), which stands for JavaScript Object
-Notation. It is widely used as a data storage and communication format
-on the Web, even in languages other than JavaScript.
+What we can do is _serialize_ the data. That means it is converted into a flat description. A popular serialization format is called _((JSON))_ (pronounced "Jason"), which stands for JavaScript Object Notation. It is widely used as a data storage and communication format on the Web, even in languages other than JavaScript.
{{index [array, notation], [object, creation], [quoting, "in JSON"], comment}}
-JSON looks similar to JavaScript's way of writing arrays and objects,
-with a few restrictions. All property names have to be surrounded by
-double quotes, and only simple data expressions are allowed—no
-function calls, bindings, or anything that involves actual
-computation. Comments are not allowed in JSON.
+JSON looks similar to JavaScript's way of writing arrays and objects, with a few restrictions. All property names have to be surrounded by double quotes, and only simple data expressions are allowed—no function calls, bindings, or anything that involves actual computation. Comments are not allowed in JSON.
A journal entry might look like this when represented as JSON data:
@@ -1296,10 +910,7 @@ A journal entry might look like this when represented as JSON data:
{{index "JSON.stringify function", "JSON.parse function", serialization, deserialization, parsing}}
-JavaScript gives us the functions `JSON.stringify` and `JSON.parse` to
-convert data to and from this format. The first takes a JavaScript
-value and returns a JSON-encoded string. The second takes such a
-string and converts it to the value it encodes.
+JavaScript gives us the functions `JSON.stringify` and `JSON.parse` to convert data to and from this format. The first takes a JavaScript value and returns a JSON-encoded string. The second takes such a string and converts it to the value it encodes.
```
let string = JSON.stringify({squirrel: false,
@@ -1312,25 +923,13 @@ console.log(JSON.parse(string).events);
## Summary
-Objects and arrays (which are a specific kind of object) provide ways
-to group several values into a single value. Conceptually, this allows
-us to put a bunch of related things in a bag and run around with the
-bag, instead of wrapping our arms around all of the individual things
-and trying to hold on to them separately.
+Objects and arrays (which are a specific kind of object) provide ways to group several values into a single value. Conceptually, this allows us to put a bunch of related things in a bag and run around with the bag, instead of wrapping our arms around all of the individual things and trying to hold on to them separately.
-Most values in JavaScript have properties, the exceptions being `null`
-and `undefined`. Properties are accessed using `value.prop` or
-`value["prop"]`. Objects tend to use names for their properties
-and store more or less a fixed set of them. Arrays, on the other hand,
-usually contain varying amounts of conceptually identical values and
-use numbers (starting from 0) as the names of their properties.
+Most values in JavaScript have properties, the exceptions being `null` and `undefined`. Properties are accessed using `value.prop` or `value["prop"]`. Objects tend to use names for their properties and store more or less a fixed set of them. Arrays, on the other hand, usually contain varying amounts of conceptually identical values and use numbers (starting from 0) as the names of their properties.
-There _are_ some named properties in arrays, such as `length` and a
-number of methods. Methods are functions that live in properties and
-(usually) act on the value they are a property of.
+There _are_ some named properties in arrays, such as `length` and a number of methods. Methods are functions that live in properties and (usually) act on the value they are a property of.
-You can iterate over arrays using a special kind of `for` loop—`for
-(let element of array)`.
+You can iterate over arrays using a special kind of `for` loop—`for (let element of array)`.
## Exercises
@@ -1338,8 +937,7 @@ You can iterate over arrays using a special kind of `for` loop—`for
{{index "summing (exercise)"}}
-The [introduction](intro) of this book alluded to the following as a
-nice way to compute the sum of a range of numbers:
+The [introduction](intro) of this book alluded to the following as a nice way to compute the sum of a range of numbers:
```{test: no}
console.log(sum(range(1, 10)));
@@ -1347,23 +945,13 @@ console.log(sum(range(1, 10)));
{{index "range function", "sum function"}}
-Write a `range` function that takes two arguments, `start` and `end`,
-and returns an array containing all the numbers from `start` up to
-(and including) `end`.
+Write a `range` function that takes two arguments, `start` and `end`, and returns an array containing all the numbers from `start` up to (and including) `end`.
-Next, write a `sum` function that takes an array of numbers and
-returns the sum of these numbers. Run the example program and see
-whether it does indeed return 55.
+Next, write a `sum` function that takes an array of numbers and returns the sum of these numbers. Run the example program and see whether it does indeed return 55.
{{index "optional argument"}}
-As a bonus assignment, modify your `range` function to take an
-optional third argument that indicates the "step" value used when
-building the array. If no step is given, the elements go up by
-increments of one, corresponding to the old behavior. The function
-call `range(1, 10, 2)` should return `[1, 3, 5, 7, 9]`. Make sure it
-also works with negative step values so that `range(5, 2, -1)`
-produces `[5, 4, 3, 2]`.
+As a bonus assignment, modify your `range` function to take an optional third argument that indicates the "step" value used when building the array. If no step is given, the elements go up by increments of one, corresponding to the old behavior. The function call `range(1, 10, 2)` should return `[1, 3, 5, 7, 9]`. Make sure it also works with negative step values so that `range(5, 2, -1)` produces `[5, 4, 3, 2]`.
{{if interactive
@@ -1384,33 +972,21 @@ if}}
{{index "summing (exercise)", [array, creation], "square brackets"}}
-Building up an array is most easily done by first initializing a
-binding to `[]` (a fresh, empty array) and repeatedly calling its
-`push` method to add a value. Don't forget to return the array at the
-end of the function.
+Building up an array is most easily done by first initializing a binding to `[]` (a fresh, empty array) and repeatedly calling its `push` method to add a value. Don't forget to return the array at the end of the function.
{{index [array, indexing], comparison}}
-Since the end boundary is inclusive, you'll need to use the `<=`
-operator rather than `<` to check for the end of your loop.
+Since the end boundary is inclusive, you'll need to use the `<=` operator rather than `<` to check for the end of your loop.
{{index "arguments object"}}
-The step parameter can be an optional parameter that defaults (using
-the `=` operator) to 1.
+The step parameter can be an optional parameter that defaults (using the `=` operator) to 1.
{{index "range function", "for loop"}}
-Having `range` understand negative step values is probably best done
-by writing two separate loops—one for counting up and one for counting
-down—because the comparison that checks whether the loop is finished
-needs to be `>=` rather than `<=` when counting downward.
+Having `range` understand negative step values is probably best done by writing two separate loops—one for counting up and one for counting down—because the comparison that checks whether the loop is finished needs to be `>=` rather than `<=` when counting downward.
-It might also be worthwhile to use a different default step, namely,
--1, when the end of the range is smaller than the start. That way,
-`range(5, 2)` returns something meaningful, rather than getting stuck
-in an ((infinite loop)). It is possible to refer to previous
-parameters in the default value of a parameter.
+It might also be worthwhile to use a different default step, namely, -1, when the end of the range is smaller than the start. That way, `range(5, 2)` returns something meaningful, rather than getting stuck in an ((infinite loop)). It is possible to refer to previous parameters in the default value of a parameter.
hint}}
@@ -1418,20 +994,11 @@ hint}}
{{index "reversing (exercise)", "reverse method", [array, methods]}}
-Arrays have a `reverse` method that changes the array by inverting
-the order in which its elements appear. For this exercise, write two
-functions, `reverseArray` and `reverseArrayInPlace`. The first,
-`reverseArray`, takes an array as argument and produces a _new_ array
-that has the same elements in the inverse order. The second,
-`reverseArrayInPlace`, does what the `reverse` method does: it
-_modifies_ the array given as argument by reversing its elements.
-Neither may use the standard `reverse` method.
+Arrays have a `reverse` method that changes the array by inverting the order in which its elements appear. For this exercise, write two functions, `reverseArray` and `reverseArrayInPlace`. The first, `reverseArray`, takes an array as argument and produces a _new_ array that has the same elements in the inverse order. The second, `reverseArrayInPlace`, does what the `reverse` method does: it _modifies_ the array given as argument by reversing its elements. Neither may use the standard `reverse` method.
{{index efficiency, "pure function", "side effect"}}
-Thinking back to the notes about side effects and pure functions in
-the [previous chapter](functions#pure), which variant do you expect to
-be useful in more situations? Which one runs faster?
+Thinking back to the notes about side effects and pure functions in the [previous chapter](functions#pure), which variant do you expect to be useful in more situations? Which one runs faster?
{{if interactive
@@ -1452,29 +1019,13 @@ if}}
{{index "reversing (exercise)"}}
-There are two obvious ways to implement `reverseArray`. The first is
-to simply go over the input array from front to back and use the
-`unshift` method on the new array to insert each element at its start.
-The second is to loop over the input array backwards and use the `push`
-method. Iterating over an array backwards requires a (somewhat awkward)
-`for` specification, like `(let i = array.length - 1; i >= 0; i--)`.
+There are two obvious ways to implement `reverseArray`. The first is to simply go over the input array from front to back and use the `unshift` method on the new array to insert each element at its start. The second is to loop over the input array backwards and use the `push` method. Iterating over an array backwards requires a (somewhat awkward) `for` specification, like `(let i = array.length - 1; i >= 0; i--)`.
{{index "slice method"}}
-Reversing the array in place is harder. You have to be careful not to
-overwrite elements that you will later need. Using `reverseArray` or
-otherwise copying the whole array (`array.slice(0)` is a good way to
-copy an array) works but is cheating.
-
-The trick is to _swap_ the first and last elements, then the second
-and second-to-last, and so on. You can do this by looping over half
-the length of the array (use `Math.floor` to round down—you don't need
-to touch the middle element in an array with an odd number of
-elements) and swapping the element at position `i` with the one at
-position `array.length - 1 - i`. You can use a local binding to
-briefly hold on to one of the elements, overwrite that one with its
-mirror image, and then put the value from the local binding in the
-place where the mirror image used to be.
+Reversing the array in place is harder. You have to be careful not to overwrite elements that you will later need. Using `reverseArray` or otherwise copying the whole array (`array.slice(0)` is a good way to copy an array) works but is cheating.
+
+The trick is to _swap_ the first and last elements, then the second and second-to-last, and so on. You can do this by looping over half the length of the array (use `Math.floor` to round down—you don't need to touch the middle element in an array with an odd number of elements) and swapping the element at position `i` with the one at position `array.length - 1 - i`. You can use a local binding to briefly hold on to one of the elements, overwrite that one with its mirror image, and then put the value from the local binding in the place where the mirror image used to be.
hint}}
@@ -1484,11 +1035,7 @@ hint}}
{{index ["data structure", list], "list (exercise)", "linked list", array, collection}}
-Objects, as generic blobs of values, can be used to build all sorts of
-data structures. A common data structure is the _list_ (not to be
-confused with array). A list is a nested set of objects, with the
-first object holding a reference to the second, the second to the
-third, and so on.
+Objects, as generic blobs of values, can be used to build all sorts of data structures. A common data structure is the _list_ (not to be confused with array). A list is a nested set of objects, with the first object holding a reference to the second, the second to the third, and so on.
```{includeCode: true}
let list = {
@@ -1509,21 +1056,9 @@ The resulting objects form a chain, like this:
{{index "structure sharing", [memory, structure sharing]}}
-A nice thing about lists is that they can share parts of their
-structure. For example, if I create two new values `{value: 0, rest:
-list}` and `{value: -1, rest: list}` (with `list` referring to the
-binding defined earlier), they are both independent lists, but they
-share the structure that makes up their last three elements. The
-original list is also still a valid three-element list.
-
-Write a function `arrayToList` that builds up a list structure like
-the one shown when given `[1, 2, 3]` as argument. Also write a
-`listToArray` function that produces an array from a list. Then add a
-helper function `prepend`, which takes an element and a list and
-creates a new list that adds the element to the front of the input
-list, and `nth`, which takes a list and a number and returns the
-element at the given position in the list (with zero referring to the
-first element) or `undefined` when there is no such element.
+A nice thing about lists is that they can share parts of their structure. For example, if I create two new values `{value: 0, rest: list}` and `{value: -1, rest: list}` (with `list` referring to the binding defined earlier), they are both independent lists, but they share the structure that makes up their last three elements. The original list is also still a valid three-element list.
+
+Write a function `arrayToList` that builds up a list structure like the one shown when given `[1, 2, 3]` as argument. Also write a `listToArray` function that produces an array from a list. Then add a helper function `prepend`, which takes an element and a list and creates a new list that adds the element to the front of the input list, and `nth`, which takes a list and a number and returns the element at the given position in the list (with zero referring to the first element) or `undefined` when there is no such element.
{{index recursion}}
@@ -1550,36 +1085,21 @@ if}}
{{index "list (exercise)", "linked list"}}
-Building up a list is easier when done back to front. So `arrayToList`
-could iterate over the array backwards (see the previous exercise) and, for
-each element, add an object to the list. You can use a local binding
-to hold the part of the list that was built so far and use an
-assignment like `list = {value: X, rest: list}` to add an element.
+Building up a list is easier when done back to front. So `arrayToList` could iterate over the array backwards (see the previous exercise) and, for each element, add an object to the list. You can use a local binding to hold the part of the list that was built so far and use an assignment like `list = {value: X, rest: list}` to add an element.
{{index "for loop"}}
-To run over a list (in `listToArray` and `nth`), a `for` loop
-specification like this can be used:
+To run over a list (in `listToArray` and `nth`), a `for` loop specification like this can be used:
```
for (let node = list; node; node = node.rest) {}
```
-Can you see how that works? Every iteration of the loop, `node` points
-to the current sublist, and the body can read its `value` property to
-get the current element. At the end of an iteration, `node` moves to
-the next sublist. When that is null, we have reached the end of the
-list, and the loop is finished.
+Can you see how that works? Every iteration of the loop, `node` points to the current sublist, and the body can read its `value` property to get the current element. At the end of an iteration, `node` moves to the next sublist. When that is null, we have reached the end of the list, and the loop is finished.
{{index recursion}}
-The recursive version of `nth` will, similarly, look at an ever
-smaller part of the "tail" of the list and at the same time count down
-the index until it reaches zero, at which point it can return the
-`value` property of the node it is looking at. To get the zeroth
-element of a list, you simply take the `value` property of its head
-node. To get element _N_ + 1, you take the *N*th element of the list
-that's in this list's `rest` property.
+The recursive version of `nth` will, similarly, look at an ever smaller part of the "tail" of the list and at the same time count down the index until it reaches zero, at which point it can return the `value` property of the node it is looking at. To get the zeroth element of a list, you simply take the `value` property of its head node. To get element _N_ + 1, you take the *N*th element of the list that's in this list's `rest` property.
hint}}
@@ -1589,27 +1109,17 @@ hint}}
{{index "deep comparison (exercise)", [comparison, deep], "deep comparison", "== operator"}}
-The `==` operator compares objects by identity. But sometimes you'd
-prefer to compare the values of their actual properties.
+The `==` operator compares objects by identity. But sometimes you'd prefer to compare the values of their actual properties.
-Write a function `deepEqual` that takes two values and returns true
-only if they are the same value or are objects with the same
-properties, where the values of the properties are equal when compared
-with a recursive call to `deepEqual`.
+Write a function `deepEqual` that takes two values and returns true only if they are the same value or are objects with the same properties, where the values of the properties are equal when compared with a recursive call to `deepEqual`.
{{index null, "=== operator", "typeof operator"}}
-To find out whether values should be compared directly (use the `===`
-operator for that) or have their properties compared, you can use the
-`typeof` operator. If it produces `"object"` for both values, you
-should do a deep comparison. But you have to take one silly exception
-into account: because of a historical accident, `typeof null` also
-produces `"object"`.
+To find out whether values should be compared directly (use the `===` operator for that) or have their properties compared, you can use the `typeof` operator. If it produces `"object"` for both values, you should do a deep comparison. But you have to take one silly exception into account: because of a historical accident, `typeof null` also produces `"object"`.
{{index "Object.keys function"}}
-The `Object.keys` function will be useful when you need to go over the
-properties of objects to compare them.
+The `Object.keys` function will be useful when you need to go over the properties of objects to compare them.
{{if interactive
@@ -1631,28 +1141,14 @@ if}}
{{index "deep comparison (exercise)", [comparison, deep], "typeof operator", "=== operator"}}
-Your test for whether you are dealing with a real object will look
-something like `typeof x == "object" && x != null`. Be careful to
-compare properties only when _both_ arguments are objects. In all
-other cases you can just immediately return the result of applying
-`===`.
+Your test for whether you are dealing with a real object will look something like `typeof x == "object" && x != null`. Be careful to compare properties only when _both_ arguments are objects. In all other cases you can just immediately return the result of applying `===`.
{{index "Object.keys function"}}
-Use `Object.keys` to go over the properties. You need to test whether
-both objects have the same set of property names and whether those
-properties have identical values. One way to do that is to ensure that
-both objects have the same number of properties (the lengths of the
-property lists are the same). And then, when looping over one of the
-object's properties to compare them, always first make sure
-the other actually has a property by that name. If they have the same
-number of properties and all properties in one also exist in the
-other, they have the same set of property names.
+Use `Object.keys` to go over the properties. You need to test whether both objects have the same set of property names and whether those properties have identical values. One way to do that is to ensure that both objects have the same number of properties (the lengths of the property lists are the same). And then, when looping over one of the object's properties to compare them, always first make sure the other actually has a property by that name. If they have the same number of properties and all properties in one also exist in the other, they have the same set of property names.
{{index "return value"}}
-Returning the correct value from the function is best done by
-immediately returning false when a mismatch is found and returning
-true at the end of the function.
+Returning the correct value from the function is best done by immediately returning false when a mismatch is found and returning true at the end of the function.
hint}}
diff --git a/05_higher_order.md b/05_higher_order.md
index e8e9e1e49..75887dc08 100644
--- a/05_higher_order.md
+++ b/05_higher_order.md
@@ -6,11 +6,7 @@
{{quote {author: "Master Yuan-Ma", title: "The Book of Programming", chapter: true}
-Tzu-li and Tzu-ssu were boasting about the size of their latest
-programs. 'Two-hundred thousand lines,' said Tzu-li, 'not counting
-comments!' Tzu-ssu responded, 'Pssh, mine is almost a *million* lines
-already.' Master Yuan-Ma said, 'My best program has five hundred
-lines.' Hearing this, Tzu-li and Tzu-ssu were enlightened.
+Tzu-li and Tzu-ssu were boasting about the size of their latest programs. 'Two-hundred thousand lines,' said Tzu-li, 'not counting comments!' Tzu-ssu responded, 'Pssh, mine is almost a *million* lines already.' Master Yuan-Ma said, 'My best program has five hundred lines.' Hearing this, Tzu-li and Tzu-ssu were enlightened.
quote}}
@@ -20,10 +16,7 @@ if}}
{{index "Hoare, C.A.R."}}
-There are two ways of constructing a software design: One way is to
-make it so simple that there are obviously no deficiencies, and the
-other way is to make it so complicated that there are no obvious
-deficiencies.
+There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies.
quote}}
@@ -31,17 +24,11 @@ quote}}
{{index "program size"}}
-A large program is a costly program, and not just because of the time
-it takes to build. Size almost always involves ((complexity)), and
-complexity confuses programmers. Confused programmers, in turn,
-introduce mistakes (_((bug))s_) into programs. A large program then
-provides a lot of space for these bugs to hide, making them hard to
-find.
+A large program is a costly program, and not just because of the time it takes to build. Size almost always involves ((complexity)), and complexity confuses programmers. Confused programmers, in turn, introduce mistakes (_((bug))s_) into programs. A large program then provides a lot of space for these bugs to hide, making them hard to find.
{{index "summing example"}}
-Let's briefly go back to the final two example programs in the
-introduction. The first is self-contained and six lines long.
+Let's briefly go back to the final two example programs in the introduction. The first is self-contained and six lines long.
```
let total = 0, count = 1;
@@ -62,44 +49,25 @@ Which one is more likely to contain a bug?
{{index "program size"}}
-If we count the size of the definitions of `sum` and `range`, the
-second program is also big—even bigger than the first. But still, I'd
-argue that it is more likely to be correct.
+If we count the size of the definitions of `sum` and `range`, the second program is also big—even bigger than the first. But still, I'd argue that it is more likely to be correct.
{{index [abstraction, "with higher-order functions"], "domain-specific language"}}
-It is more likely to be correct because the solution is expressed in a
-((vocabulary)) that corresponds to the problem being solved. Summing a
-range of numbers isn't about loops and counters. It is about ranges
-and sums.
+It is more likely to be correct because the solution is expressed in a ((vocabulary)) that corresponds to the problem being solved. Summing a range of numbers isn't about loops and counters. It is about ranges and sums.
-The definitions of this vocabulary (the functions `sum` and `range`)
-will still involve loops, counters, and other incidental details. But
-because they are expressing simpler concepts than the program as a
-whole, they are easier to get right.
+The definitions of this vocabulary (the functions `sum` and `range`) will still involve loops, counters, and other incidental details. But because they are expressing simpler concepts than the program as a whole, they are easier to get right.
## Abstraction
-In the context of programming, these kinds of vocabularies are usually
-called _((abstraction))s_. Abstractions hide details and give us the
-ability to talk about problems at a higher (or more abstract) level.
+In the context of programming, these kinds of vocabularies are usually called _((abstraction))s_. Abstractions hide details and give us the ability to talk about problems at a higher (or more abstract) level.
{{index "recipe analogy", "pea soup"}}
-As an analogy, compare these two recipes for pea soup. The first one
-goes like this:
+As an analogy, compare these two recipes for pea soup. The first one goes like this:
{{quote
-Put 1 cup of dried peas per person into a container. Add water until
-the peas are well covered. Leave the peas in water for at least 12
-hours. Take the peas out of the water and put them in a cooking pan.
-Add 4 cups of water per person. Cover the pan and keep the peas
-simmering for two hours. Take half an onion per person. Cut it into
-pieces with a knife. Add it to the peas. Take a stalk of celery per
-person. Cut it into pieces with a knife. Add it to the peas. Take a
-carrot per person. Cut it into pieces. With a knife! Add it to the
-peas. Cook for 10 more minutes.
+Put 1 cup of dried peas per person into a container. Add water until the peas are well covered. Leave the peas in water for at least 12 hours. Take the peas out of the water and put them in a cooking pan. Add 4 cups of water per person. Cover the pan and keep the peas simmering for two hours. Take half an onion per person. Cut it into pieces with a knife. Add it to the peas. Take a stalk of celery per person. Cut it into pieces with a knife. Add it to the peas. Take a carrot per person. Cut it into pieces. With a knife! Add it to the peas. Cook for 10 more minutes.
quote}}
@@ -107,41 +75,31 @@ And this is the second recipe:
{{quote
-Per person: 1 cup dried split peas, half a chopped onion, a stalk of
-celery, and a carrot.
+Per person: 1 cup dried split peas, half a chopped onion, a stalk of celery, and a carrot.
-Soak peas for 12 hours. Simmer for 2 hours in 4 cups of water
-(per person). Chop and add vegetables. Cook for 10 more minutes.
+Soak peas for 12 hours. Simmer for 2 hours in 4 cups of water (per person). Chop and add vegetables. Cook for 10 more minutes.
quote}}
{{index vocabulary}}
-The second is shorter and easier to interpret. But you do need to
-understand a few more cooking-related words such as _soak_, _simmer_, _chop_,
-and, I guess, _vegetable_.
+The second is shorter and easier to interpret. But you do need to understand a few more cooking-related words such as _soak_, _simmer_, _chop_, and, I guess, _vegetable_.
-When programming, we can't rely on all the words we need to be waiting
-for us in the dictionary. Thus, we might fall into the pattern of the
-first recipe—work out the precise steps the computer has to perform,
-one by one, blind to the higher-level concepts that they express.
+When programming, we can't rely on all the words we need to be waiting for us in the dictionary. Thus, we might fall into the pattern of the first recipe—work out the precise steps the computer has to perform, one by one, blind to the higher-level concepts that they express.
{{index abstraction}}
-It is a useful skill, in programming, to notice when you are working
-at too low a level of abstraction.
+It is a useful skill, in programming, to notice when you are working at too low a level of abstraction.
## Abstracting repetition
{{index [array, iteration]}}
-Plain functions, as we've seen them so far, are a good way to build
-abstractions. But sometimes they fall short.
+Plain functions, as we've seen them so far, are a good way to build abstractions. But sometimes they fall short.
{{index "for loop"}}
-It is common for a program to do something a given number of times.
-You can write a `for` ((loop)) for that, like this:
+It is common for a program to do something a given number of times. You can write a `for` ((loop)) for that, like this:
```
for (let i = 0; i < 10; i++) {
@@ -149,8 +107,7 @@ for (let i = 0; i < 10; i++) {
}
```
-Can we abstract "doing something _N_ times" as a function? Well, it's
-easy to write a function that calls `console.log` _N_ times.
+Can we abstract "doing something _N_ times" as a function? Well, it's easy to write a function that calls `console.log` _N_ times.
```
function repeatLog(n) {
@@ -164,9 +121,7 @@ function repeatLog(n) {
{{indexsee "higher-order function", "function, higher-order"}}
-But what if we want to do something other than logging the numbers?
-Since "doing something" can be represented as a function and functions
-are just values, we can pass our action as a function value.
+But what if we want to do something other than logging the numbers? Since "doing something" can be represented as a function and functions are just values, we can pass our action as a function value.
```{includeCode: "top_lines: 5"}
function repeat(n, action) {
@@ -181,8 +136,7 @@ repeat(3, console.log);
// → 2
```
-We don't have to pass a predefined function to `repeat`. Often, it
-is easier to create a function value on the spot instead.
+We don't have to pass a predefined function to `repeat`. Often, it is easier to create a function value on the spot instead.
```
let labels = [];
@@ -195,30 +149,17 @@ console.log(labels);
{{index "loop body", [braces, body], [parentheses, arguments]}}
-This is structured a little like a `for` loop—it first describes the
-kind of loop and then provides a body. However, the body is now written
-as a function value, which is wrapped in the parentheses of the
-call to `repeat`. This is why it has to be closed with the closing
-brace _and_ closing parenthesis. In cases like this example, where the
-body is a single small expression, you could also omit the
-braces and write the loop on a single line.
+This is structured a little like a `for` loop—it first describes the kind of loop and then provides a body. However, the body is now written as a function value, which is wrapped in the parentheses of the call to `repeat`. This is why it has to be closed with the closing brace _and_ closing parenthesis. In cases like this example, where the body is a single small expression, you could also omit the braces and write the loop on a single line.
## Higher-order functions
{{index [function, "higher-order"], [function, "as value"]}}
-Functions that operate on other functions, either by taking them as
-arguments or by returning them, are called _higher-order functions_.
-Since we have already seen that functions are regular values, there is
-nothing particularly remarkable about the fact that such functions
-exist. The term comes from ((mathematics)), where the distinction
-between functions and other values is taken more seriously.
+Functions that operate on other functions, either by taking them as arguments or by returning them, are called _higher-order functions_. Since we have already seen that functions are regular values, there is nothing particularly remarkable about the fact that such functions exist. The term comes from ((mathematics)), where the distinction between functions and other values is taken more seriously.
{{index abstraction}}
-Higher-order functions allow us to abstract over _actions_, not just
-values. They come in several forms. For example, we can have
-functions that create new functions.
+Higher-order functions allow us to abstract over _actions_, not just values. They come in several forms. For example, we can have functions that create new functions.
```
function greaterThan(n) {
@@ -245,8 +186,7 @@ noisy(Math.min)(3, 2, 1);
// → called with [3, 2, 1] , returned 1
```
-We can even write functions that provide new types of ((control
-flow)).
+We can even write functions that provide new types of ((control flow)).
```
function unless(test, then) {
@@ -264,8 +204,7 @@ repeat(3, n => {
{{index [array, methods], [array, iteration], "forEach method"}}
-There is a built-in array method, `forEach`, that provides something
-like a `for`/`of` loop as a higher-order function.
+There is a built-in array method, `forEach`, that provides something like a `for`/`of` loop as a higher-order function.
```
["A", "B"].forEach(l => console.log(l));
@@ -275,31 +214,17 @@ like a `for`/`of` loop as a higher-order function.
## Script data set
-One area where higher-order functions shine is data processing. To process data, we'll need some actual data. This chapter will
-use a ((data set)) about scripts—((writing system))s such as Latin,
-Cyrillic, or Arabic.
+One area where higher-order functions shine is data processing. To process data, we'll need some actual data. This chapter will use a ((data set)) about scripts—((writing system))s such as Latin, Cyrillic, or Arabic.
-Remember ((Unicode)) from [Chapter ?](values#unicode), the system that
-assigns a number to each character in written language? Most of these
-characters are associated with a specific script. The standard
-contains 140 different scripts—81 are still in use today, and 59
-are historic.
+Remember ((Unicode)) from [Chapter ?](values#unicode), the system that assigns a number to each character in written language? Most of these characters are associated with a specific script. The standard contains 140 different scripts—81 are still in use today, and 59 are historic.
-Though I can fluently read only Latin characters, I appreciate the
-fact that people are writing texts in at least 80 other writing
-systems, many of which I wouldn't even recognize. For example, here's
-a sample of ((Tamil)) handwriting:
+Though I can fluently read only Latin characters, I appreciate the fact that people are writing texts in at least 80 other writing systems, many of which I wouldn't even recognize. For example, here's a sample of ((Tamil)) handwriting:
{{figure {url: "img/tamil.png", alt: "Tamil handwriting"}}}
{{index "SCRIPTS data set"}}
-The example ((data set)) contains some pieces of information about the
-140 scripts defined in Unicode. It is available in the [coding
-sandbox](https://eloquentjavascript.net/code#5) for this chapter[
-([_https://eloquentjavascript.net/code#5_](https://eloquentjavascript.net/code#5))]{if
-book} as the `SCRIPTS` binding. The binding contains an array of
-objects, each of which describes a script.
+The example ((data set)) contains some pieces of information about the 140 scripts defined in Unicode. It is available in the [coding sandbox](https://eloquentjavascript.net/code#5) for this chapter[ ([_https://eloquentjavascript.net/code#5_](https://eloquentjavascript.net/code#5))]{if book} as the `SCRIPTS` binding. The binding contains an array of objects, each of which describes a script.
```{lang: "application/json"}
@@ -313,28 +238,17 @@ objects, each of which describes a script.
}
```
-Such an object tells us the name of the script, the Unicode ranges
-assigned to it, the direction in which it is written, the
-(approximate) origin time, whether it is still in use, and a link to
-more information. The direction may be `"ltr"` for left to right, `"rtl"`
-for right to left (the way Arabic and Hebrew text are written), or
-`"ttb"` for top to bottom (as with Mongolian writing).
+Such an object tells us the name of the script, the Unicode ranges assigned to it, the direction in which it is written, the (approximate) origin time, whether it is still in use, and a link to more information. The direction may be `"ltr"` for left to right, `"rtl"` for right to left (the way Arabic and Hebrew text are written), or `"ttb"` for top to bottom (as with Mongolian writing).
{{index "slice method"}}
-The `ranges` property contains an array of Unicode character
-((range))s, each of which is a two-element array containing a lower bound
-and an upper bound. Any character codes within these ranges are assigned
-to the script. The lower ((bound)) is inclusive (code 994 is a Coptic
-character), and the upper bound is non-inclusive (code 1008 isn't).
+The `ranges` property contains an array of Unicode character ((range))s, each of which is a two-element array containing a lower bound and an upper bound. Any character codes within these ranges are assigned to the script. The lower ((bound)) is inclusive (code 994 is a Coptic character), and the upper bound is non-inclusive (code 1008 isn't).
## Filtering arrays
{{index [array, methods], [array, filtering], "filter method", [function, "higher-order"], "predicate function"}}
-To find the scripts in the data set that are still in use, the
-following function might be helpful. It filters out the elements in an
-array that don't pass a test.
+To find the scripts in the data set that are still in use, the following function might be helpful. It filters out the elements in an array that don't pass a test.
```
function filter(array, test) {
@@ -353,20 +267,13 @@ console.log(filter(SCRIPTS, script => script.living));
{{index [function, "as value"], [function, application]}}
-The function uses the argument named `test`, a function value, to fill
-a "gap" in the computation—the process of deciding which elements to
-collect.
+The function uses the argument named `test`, a function value, to fill a "gap" in the computation—the process of deciding which elements to collect.
{{index "filter method", "pure function", "side effect"}}
-Note how the `filter` function, rather than deleting elements from the
-existing array, builds up a new array with only the elements that pass
-the test. This function is _pure_. It does not modify the array it is
-given.
+Note how the `filter` function, rather than deleting elements from the existing array, builds up a new array with only the elements that pass the test. This function is _pure_. It does not modify the array it is given.
-Like `forEach`, `filter` is a ((standard)) array method. The example
-defined the function only to show what it does internally.
-From now on, we'll use it like this instead:
+Like `forEach`, `filter` is a ((standard)) array method. The example defined the function only to show what it does internally. From now on, we'll use it like this instead:
```
console.log(SCRIPTS.filter(s => s.direction == "ttb"));
@@ -379,16 +286,11 @@ console.log(SCRIPTS.filter(s => s.direction == "ttb"));
{{index [array, methods], "map method"}}
-Say we have an array of objects representing scripts, produced by
-filtering the `SCRIPTS` array somehow. But we want an array of names,
-which is easier to inspect.
+Say we have an array of objects representing scripts, produced by filtering the `SCRIPTS` array somehow. But we want an array of names, which is easier to inspect.
{{index [function, "higher-order"]}}
-The `map` method transforms an array by applying a function to all of
-its elements and building a new array from the returned values. The
-new array will have the same length as the input array, but its
-content will have been _mapped_ to a new form by the function.
+The `map` method transforms an array by applying a function to all of its elements and building a new array from the returned values. The new array will have the same length as the input array, but its content will have been _mapped_ to a new form by the function.
```
function map(array, transform) {
@@ -410,25 +312,15 @@ Like `forEach` and `filter`, `map` is a standard array method.
{{index [array, methods], "summing example", "reduce method"}}
-Another common thing to do with arrays is to compute a single value
-from them. Our recurring example, summing a collection of numbers, is
-an instance of this. Another example is finding the script with
-the most characters.
+Another common thing to do with arrays is to compute a single value from them. Our recurring example, summing a collection of numbers, is an instance of this. Another example is finding the script with the most characters.
{{indexsee "fold", "reduce method"}}
{{index [function, "higher-order"], "reduce method"}}
-The higher-order operation that represents this pattern is called
-_reduce_ (sometimes also called _fold_). It builds a value by
-repeatedly taking a single element from the array and combining it
-with the current value. When summing numbers, you'd start with the
-number zero and, for each element, add that to the sum.
+The higher-order operation that represents this pattern is called _reduce_ (sometimes also called _fold_). It builds a value by repeatedly taking a single element from the array and combining it with the current value. When summing numbers, you'd start with the number zero and, for each element, add that to the sum.
-The parameters to `reduce` are, apart from the array, a combining
-function and a start value. This function is a little less
-straightforward than `filter` and `map`, so take a close look at
-it:
+The parameters to `reduce` are, apart from the array, a combining function and a start value. This function is a little less straightforward than `filter` and `map`, so take a close look at it:
```
function reduce(array, combine, start) {
@@ -445,11 +337,7 @@ console.log(reduce([1, 2, 3, 4], (a, b) => a + b, 0));
{{index "reduce method", "SCRIPTS data set"}}
-The standard array method `reduce`, which of course corresponds to
-this function, has an added convenience. If your array contains at
-least one element, you are allowed to leave off the `start` argument.
-The method will take the first element of the array as its start value
-and start reducing at the second element.
+The standard array method `reduce`, which of course corresponds to this function, has an added convenience. If your array contains at least one element, you are allowed to leave off the `start` argument. The method will take the first element of the array as its start value and start reducing at the second element.
```
console.log([1, 2, 3, 4].reduce((a, b) => a + b));
@@ -458,8 +346,7 @@ console.log([1, 2, 3, 4].reduce((a, b) => a + b));
{{index maximum, "characterCount function"}}
-To use `reduce` (twice) to find the script with the most characters,
-we can write something like this:
+To use `reduce` (twice) to find the script with the most characters, we can write something like this:
```
function characterCount(script) {
@@ -474,28 +361,15 @@ console.log(SCRIPTS.reduce((a, b) => {
// → {name: "Han", …}
```
-The `characterCount` function reduces the ranges assigned to a script
-by summing their sizes. Note the use of destructuring in the parameter
-list of the reducer function. The second call to `reduce` then uses
-this to find the largest script by repeatedly comparing two scripts
-and returning the larger one.
+The `characterCount` function reduces the ranges assigned to a script by summing their sizes. Note the use of destructuring in the parameter list of the reducer function. The second call to `reduce` then uses this to find the largest script by repeatedly comparing two scripts and returning the larger one.
-The Han script has more than 89,000 characters assigned to it in the
-Unicode standard, making it by far the biggest writing system in the
-data set. Han is a script (sometimes) used for Chinese, Japanese, and
-Korean text. Those languages share a lot of characters, though they
-tend to write them differently. The (U.S.-based) Unicode Consortium
-decided to treat them as a single writing system to save
-character codes. This is called _Han unification_ and still makes some
-people very angry.
+The Han script has more than 89,000 characters assigned to it in the Unicode standard, making it by far the biggest writing system in the data set. Han is a script (sometimes) used for Chinese, Japanese, and Korean text. Those languages share a lot of characters, though they tend to write them differently. The (U.S.-based) Unicode Consortium decided to treat them as a single writing system to save character codes. This is called _Han unification_ and still makes some people very angry.
## Composability
{{index loop, maximum}}
-Consider how we would have written the previous example (finding the
-biggest script) without higher-order functions. The code is not that
-much worse.
+Consider how we would have written the previous example (finding the biggest script) without higher-order functions. The code is not that much worse.
```{test: no}
let biggest = null;
@@ -509,16 +383,13 @@ console.log(biggest);
// → {name: "Han", …}
```
-There are a few more bindings, and the program is four lines
-longer. But it is still very readable.
+There are a few more bindings, and the program is four lines longer. But it is still very readable.
{{index "average function", composability, [function, "higher-order"], "filter method", "map method", "reduce method"}}
{{id average_function}}
-Higher-order functions start to shine when you need to _compose_
-operations. As an example, let's write code that finds the average
-year of origin for living and dead scripts in the data set.
+Higher-order functions start to shine when you need to _compose_ operations. As an example, let's write code that finds the average year of origin for living and dead scripts in the data set.
```
function average(array) {
@@ -533,12 +404,7 @@ console.log(Math.round(average(
// → 204
```
-So the dead scripts in Unicode are, on average, older than the living
-ones. This is not a terribly meaningful or surprising statistic. But I
-hope you'll agree that the code used to compute it isn't hard to read.
-You can see it as a pipeline: we start with all scripts, filter out
-the living (or dead) ones, take the years from those, average them,
-and round the result.
+So the dead scripts in Unicode are, on average, older than the living ones. This is not a terribly meaningful or surprising statistic. But I hope you'll agree that the code used to compute it isn't hard to read. You can see it as a pipeline: we start with all scripts, filter out the living (or dead) ones, take the years from those, average them, and round the result.
You could definitely also write this computation as one big ((loop)).
@@ -554,30 +420,19 @@ console.log(Math.round(total / count));
// → 1165
```
-But it is harder to see what was being computed and how. And because
-intermediate results aren't represented as coherent values, it'd be a
-lot more work to extract something like `average` into a separate
-function.
+But it is harder to see what was being computed and how. And because intermediate results aren't represented as coherent values, it'd be a lot more work to extract something like `average` into a separate function.
{{index efficiency, [array, creation]}}
-In terms of what the computer is actually doing, these two approaches
-are also quite different. The first will build up new arrays when
-running `filter` and `map`, whereas the second computes only some
-numbers, doing less work. You can usually afford the readable
-approach, but if you're processing huge arrays, and doing so many
-times, the less abstract style might be worth the extra speed.
+In terms of what the computer is actually doing, these two approaches are also quite different. The first will build up new arrays when running `filter` and `map`, whereas the second computes only some numbers, doing less work. You can usually afford the readable approach, but if you're processing huge arrays, and doing so many times, the less abstract style might be worth the extra speed.
## Strings and character codes
{{index "SCRIPTS data set"}}
-One use of the data set would be figuring out what script a piece of
-text is using. Let's go through a program that does this.
+One use of the data set would be figuring out what script a piece of text is using. Let's go through a program that does this.
-Remember that each script has an array of character code ranges
-associated with it. So given a character code, we could use a function
-like this to find the corresponding script (if any):
+Remember that each script has an array of character code ranges associated with it. So given a character code, we could use a function like this to find the corresponding script (if any):
{{index "some method", "predicate function", [array, methods]}}
@@ -597,41 +452,21 @@ console.log(characterScript(121));
// → {name: "Latin", …}
```
-The `some` method is another higher-order function. It takes a test
-function and tells you whether that function returns true for any of the
-elements in the array.
+The `some` method is another higher-order function. It takes a test function and tells you whether that function returns true for any of the elements in the array.
{{id code_units}}
But how do we get the character codes in a string?
-In [Chapter ?](values) I mentioned that JavaScript ((string))s are
-encoded as a sequence of 16-bit numbers. These are called _((code
-unit))s_. A ((Unicode)) ((character)) code was initially supposed to
-fit within such a unit (which gives you a little over 65,000
-characters). When it became clear that wasn't going to be enough, many
-people balked at the need to use more memory per character. To address
-these concerns, ((UTF-16)), the format used by JavaScript strings, was
-invented. It describes most common characters using a single 16-bit
-code unit but uses a pair of two such units for others.
+In [Chapter ?](values) I mentioned that JavaScript ((string))s are encoded as a sequence of 16-bit numbers. These are called _((code unit))s_. A ((Unicode)) ((character)) code was initially supposed to fit within such a unit (which gives you a little over 65,000 characters). When it became clear that wasn't going to be enough, many people balked at the need to use more memory per character. To address these concerns, ((UTF-16)), the format used by JavaScript strings, was invented. It describes most common characters using a single 16-bit code unit but uses a pair of two such units for others.
{{index error}}
-UTF-16 is generally considered a bad idea today. It seems almost
-intentionally designed to invite mistakes. It's easy to write programs
-that pretend code units and characters are the same thing. And if your
-language doesn't use two-unit characters, that will appear to work
-just fine. But as soon as someone tries to use such a program with
-some less common ((Chinese characters)), it breaks. Fortunately, with
-the advent of ((emoji)), everybody has started using two-unit
-characters, and the burden of dealing with such problems is more
-fairly distributed.
+UTF-16 is generally considered a bad idea today. It seems almost intentionally designed to invite mistakes. It's easy to write programs that pretend code units and characters are the same thing. And if your language doesn't use two-unit characters, that will appear to work just fine. But as soon as someone tries to use such a program with some less common ((Chinese characters)), it breaks. Fortunately, with the advent of ((emoji)), everybody has started using two-unit characters, and the burden of dealing with such problems is more fairly distributed.
{{index [string, length], [string, indexing], "charCodeAt method"}}
-Unfortunately, obvious operations on JavaScript strings, such as
-getting their length through the `length` property and accessing their
-content using square brackets, deal only with code units.
+Unfortunately, obvious operations on JavaScript strings, such as getting their length through the `length` property and accessing their content using square brackets, deal only with code units.
```{test: no}
// Two emoji characters, horse and shoe
@@ -648,21 +483,11 @@ console.log(horseShoe.codePointAt(0));
{{index "codePointAt method"}}
-JavaScript's `charCodeAt` method gives you a code unit, not a full
-character code. The `codePointAt` method, added later, does give a
-full Unicode character. So we could use that to get characters from a
-string. But the argument passed to `codePointAt` is still an index
-into the sequence of code units. So to run over all characters in a
-string, we'd still need to deal with the question of whether a
-character takes up one or two code units.
+JavaScript's `charCodeAt` method gives you a code unit, not a full character code. The `codePointAt` method, added later, does give a full Unicode character. So we could use that to get characters from a string. But the argument passed to `codePointAt` is still an index into the sequence of code units. So to run over all characters in a string, we'd still need to deal with the question of whether a character takes up one or two code units.
{{index "for/of loop", character}}
-In the [previous chapter](data#for_of_loop), I mentioned that a
-`for`/`of` loop can also be used on strings. Like `codePointAt`, this
-type of loop was introduced at a time where people were acutely aware
-of the problems with UTF-16. When you use it to loop over a string, it
-gives you real characters, not code units.
+In the [previous chapter](data#for_of_loop), I mentioned that a `for`/`of` loop can also be used on strings. Like `codePointAt`, this type of loop was introduced at a time where people were acutely aware of the problems with UTF-16. When you use it to loop over a string, it gives you real characters, not code units.
```
let roseDragon = "🌹🐉";
@@ -673,17 +498,13 @@ for (let char of roseDragon) {
// → 🐉
```
-If you have a character (which will be a string of one or two code
-units), you can use `codePointAt(0)` to get its code.
+If you have a character (which will be a string of one or two code units), you can use `codePointAt(0)` to get its code.
## Recognizing text
{{index "SCRIPTS data set", "countBy function", [array, counting]}}
-We have a `characterScript` function and a way to correctly loop over
-characters. The next step is to count the characters that belong
-to each script. The following counting abstraction will be useful
-there:
+We have a `characterScript` function and a way to correctly loop over characters. The next step is to count the characters that belong to each script. The following counting abstraction will be useful there:
```{includeCode: strip_log}
function countBy(items, groupName) {
@@ -704,23 +525,15 @@ console.log(countBy([1, 2, 3, 4, 5], n => n > 2));
// → [{name: false, count: 2}, {name: true, count: 3}]
```
-The `countBy` function expects a collection (anything that we can loop
-over with `for`/`of`) and a function that computes a group name for a
-given element. It returns an array of
-objects, each of which names a group and tells you the number of
-elements that were found in that group.
+The `countBy` function expects a collection (anything that we can loop over with `for`/`of`) and a function that computes a group name for a given element. It returns an array of objects, each of which names a group and tells you the number of elements that were found in that group.
{{index "findIndex method", "indexOf method"}}
-It uses another array method—`findIndex`. This method is somewhat like
-`indexOf`, but instead of looking for a specific value, it finds the
-first value for which the given function returns true. Like `indexOf`,
-it returns -1 when no such element is found.
+It uses another array method—`findIndex`. This method is somewhat like `indexOf`, but instead of looking for a specific value, it finds the first value for which the given function returns true. Like `indexOf`, it returns -1 when no such element is found.
{{index "textScripts function", "Chinese characters"}}
-Using `countBy`, we can write the function that tells us which scripts
-are used in a piece of text.
+Using `countBy`, we can write the function that tells us which scripts are used in a piece of text.
```{includeCode: strip_log, startCode: true}
function textScripts(text) {
@@ -743,36 +556,17 @@ console.log(textScripts('英国的狗说"woof", 俄罗斯的狗说"тяв"'));
{{index "characterScript function", "filter method"}}
-The function first counts the characters by name, using
-`characterScript` to assign them a name and falling back to the
-string `"none"` for characters that aren't part of any script. The
-`filter` call drops the entry for `"none"` from the resulting array
-since we aren't interested in those characters.
+The function first counts the characters by name, using `characterScript` to assign them a name and falling back to the string `"none"` for characters that aren't part of any script. The `filter` call drops the entry for `"none"` from the resulting array since we aren't interested in those characters.
{{index "reduce method", "map method", "join method", [array, methods]}}
-To be able to compute ((percentage))s, we first need the total number
-of characters that belong to a script, which we can compute with
-`reduce`. If no such characters are found, the function returns a
-specific string. Otherwise, it transforms the counting entries into
-readable strings with `map` and then combines them with `join`.
+To be able to compute ((percentage))s, we first need the total number of characters that belong to a script, which we can compute with `reduce`. If no such characters are found, the function returns a specific string. Otherwise, it transforms the counting entries into readable strings with `map` and then combines them with `join`.
## Summary
-Being able to pass function values to other functions is a deeply
-useful aspect of JavaScript. It allows us to write functions that
-model computations with "gaps" in them. The code that calls these
-functions can fill in the gaps by providing function values.
-
-Arrays provide a number of useful higher-order methods. You can use
-`forEach` to loop over the elements in an array. The `filter` method
-returns a new array containing only the elements that pass the
-((predicate function)). Transforming an array by putting each element
-through a function is done with `map`. You can use `reduce` to combine
-all the elements in an array into a single value. The `some` method
-tests whether any element matches a given predicate function. And
-`findIndex` finds the position of the first element that matches a
-predicate.
+Being able to pass function values to other functions is a deeply useful aspect of JavaScript. It allows us to write functions that model computations with "gaps" in them. The code that calls these functions can fill in the gaps by providing function values.
+
+Arrays provide a number of useful higher-order methods. You can use `forEach` to loop over the elements in an array. The `filter` method returns a new array containing only the elements that pass the ((predicate function)). Transforming an array by putting each element through a function is done with `map`. You can use `reduce` to combine all the elements in an array into a single value. The `some` method tests whether any element matches a given predicate function. And `findIndex` finds the position of the first element that matches a predicate.
## Exercises
@@ -780,9 +574,7 @@ predicate.
{{index "flattening (exercise)", "reduce method", "concat method", [array, flattening]}}
-Use the `reduce` method in combination with the `concat` method to
-"flatten" an array of arrays into a single array that has all the
-elements of the original arrays.
+Use the `reduce` method in combination with the `concat` method to "flatten" an array of arrays into a single array that has all the elements of the original arrays.
{{if interactive
@@ -797,16 +589,9 @@ if}}
{{index "your own loop (example)", "for loop"}}
-Write a higher-order function `loop` that provides something like a
-`for` loop statement. It takes a value, a test function, an update
-function, and a body function. Each iteration, it first runs the test
-function on the current loop value and stops if that returns false.
-Then it calls the body function, giving it the current value.
-Finally, it calls the update function to create a new value and
-starts from the beginning.
+Write a higher-order function `loop` that provides something like a `for` loop statement. It takes a value, a test function, an update function, and a body function. Each iteration, it first runs the test function on the current loop value and stops if that returns false. Then it calls the body function, giving it the current value. Finally, it calls the update function to create a new value and starts from the beginning.
-When defining the function, you can use a regular loop to do the
-actual looping.
+When defining the function, you can use a regular loop to do the actual looping.
{{if interactive
@@ -825,14 +610,9 @@ if}}
{{index "predicate function", "everything (exercise)", "every method", "some method", [array, methods], "&& operator", "|| operator"}}
-Analogous to the `some` method, arrays also have an `every` method.
-This one returns true when the given function returns true for _every_
-element in the array. In a way, `some` is a version of the `||`
-operator that acts on arrays, and `every` is like the `&&` operator.
+Analogous to the `some` method, arrays also have an `every` method. This one returns true when the given function returns true for _every_ element in the array. In a way, `some` is a version of the `||` operator that acts on arrays, and `every` is like the `&&` operator.
-Implement `every` as a function that takes an array and a predicate
-function as parameters. Write two versions, one using a loop and one
-using the `some` method.
+Implement `every` as a function that takes an array and a predicate function as parameters. Write two versions, one using a loop and one using the `some` method.
{{if interactive
@@ -855,18 +635,9 @@ if}}
{{index "everything (exercise)", "short-circuit evaluation", "return keyword"}}
-Like the `&&` operator, the `every` method can stop evaluating further
-elements as soon as it has found one that doesn't match. So the
-loop-based version can jump out of the loop—with `break` or
-`return`—as soon as it runs into an element for which the predicate
-function returns false. If the loop runs to its end without finding
-such an element, we know that all elements matched and we should
-return true.
+Like the `&&` operator, the `every` method can stop evaluating further elements as soon as it has found one that doesn't match. So the loop-based version can jump out of the loop—with `break` or `return`—as soon as it runs into an element for which the predicate function returns false. If the loop runs to its end without finding such an element, we know that all elements matched and we should return true.
-To build `every` on top of `some`, we can apply _((De Morgan's
-laws))_, which state that `a && b` equals `!(!a || !b)`. This can be
-generalized to arrays, where all elements in the array match if there
-is no element in the array that does not match.
+To build `every` on top of `some`, we can apply _((De Morgan's laws))_, which state that `a && b` equals `!(!a || !b)`. This can be generalized to arrays, where all elements in the array match if there is no element in the array that does not match.
hint}}
@@ -874,17 +645,11 @@ hint}}
{{index "SCRIPTS data set", "direction (writing)", "groupBy function", "dominant direction (exercise)"}}
-Write a function that computes the dominant writing direction in a
-string of text. Remember that each script object has a `direction`
-property that can be `"ltr"` (left to right), `"rtl"` (right to left),
-or `"ttb"` (top to bottom).
+Write a function that computes the dominant writing direction in a string of text. Remember that each script object has a `direction` property that can be `"ltr"` (left to right), `"rtl"` (right to left), or `"ttb"` (top to bottom).
{{index "characterScript function", "countBy function"}}
-The dominant direction is the direction of a majority of the
-characters that have a script associated with them. The
-`characterScript` and `countBy` functions defined earlier in the
-chapter are probably useful here.
+The dominant direction is the direction of a majority of the characters that have a script associated with them. The `characterScript` and `countBy` functions defined earlier in the chapter are probably useful here.
{{if interactive
@@ -904,16 +669,10 @@ if}}
{{index "dominant direction (exercise)", "textScripts function", "filter method", "characterScript function"}}
-Your solution might look a lot like the first half of the
-`textScripts` example. You again have to count characters by a
-criterion based on `characterScript` and then filter out the part of
-the result that refers to uninteresting (script-less) characters.
+Your solution might look a lot like the first half of the `textScripts` example. You again have to count characters by a criterion based on `characterScript` and then filter out the part of the result that refers to uninteresting (script-less) characters.
{{index "reduce method"}}
-Finding the direction with the highest character count can be done
-with `reduce`. If it's not clear how, refer to the example
-earlier in the chapter, where `reduce` was used to find the script
-with the most characters.
+Finding the direction with the highest character count can be done with `reduce`. If it's not clear how, refer to the example earlier in the chapter, where `reduce` was used to find the script with the most characters.
hint}}
diff --git a/06_object.md b/06_object.md
index eea6f8c4a..57dcfc1e3 100644
--- a/06_object.md
+++ b/06_object.md
@@ -4,9 +4,7 @@
{{quote {author: "Barbara Liskov", title: "Programming with Abstract Data Types", chapter: true}
-An abstract data type is realized by writing a special kind of program
-[…] which defines the type in terms of the operations which can be
-performed on it.
+An abstract data type is realized by writing a special kind of program […] which defines the type in terms of the operations which can be performed on it.
quote}}
@@ -14,61 +12,34 @@ quote}}
{{figure {url: "img/chapter_picture_6.jpg", alt: "Picture of a rabbit with its proto-rabbit", chapter: framed}}}
-[Chapter ?](data) introduced JavaScript's objects. In programming
-culture, we have a thing called _((object-oriented programming))_, a
-set of techniques that use objects (and related concepts) as the
-central principle of program organization.
+[Chapter ?](data) introduced JavaScript's objects. In programming culture, we have a thing called _((object-oriented programming))_, a set of techniques that use objects (and related concepts) as the central principle of program organization.
-Though no one really agrees on its precise definition, object-oriented
-programming has shaped the design of many programming languages,
-including JavaScript. This chapter will describe the way these ideas
-can be applied in JavaScript.
+Though no one really agrees on its precise definition, object-oriented programming has shaped the design of many programming languages, including JavaScript. This chapter will describe the way these ideas can be applied in JavaScript.
## Encapsulation
{{index encapsulation, isolation, modularity}}
-The core idea in object-oriented programming is to divide programs
-into smaller pieces and make each piece responsible for managing its
-own state.
+The core idea in object-oriented programming is to divide programs into smaller pieces and make each piece responsible for managing its own state.
-This way, some knowledge about the way a piece of the program works
-can be kept _local_ to that piece. Someone working on the rest of the
-program does not have to remember or even be aware of that knowledge.
-Whenever these local details change, only the code directly around it
-needs to be updated.
+This way, some knowledge about the way a piece of the program works can be kept _local_ to that piece. Someone working on the rest of the program does not have to remember or even be aware of that knowledge. Whenever these local details change, only the code directly around it needs to be updated.
{{id interface}}
{{index [interface, object]}}
-Different pieces of such a program interact with each other through
-_interfaces_, limited sets of functions or bindings that provide
-useful functionality at a more abstract level, hiding their precise
-implementation.
+Different pieces of such a program interact with each other through _interfaces_, limited sets of functions or bindings that provide useful functionality at a more abstract level, hiding their precise implementation.
{{index "public properties", "private properties", "access control", [method, interface]}}
-Such program pieces are modeled using ((object))s. Their interface
-consists of a specific set of methods and properties. Properties
-that are part of the interface are called _public_. The others, which
-outside code should not be touching, are called _private_.
+Such program pieces are modeled using ((object))s. Their interface consists of a specific set of methods and properties. Properties that are part of the interface are called _public_. The others, which outside code should not be touching, are called _private_.
{{index "underscore character"}}
-Many languages provide a way to distinguish public and private
-properties and prevent outside code from accessing the private
-ones altogether. JavaScript, once again taking the minimalist
-approach, does not—not yet at least. There is work underway to add
-this to the language.
+Many languages provide a way to distinguish public and private properties and prevent outside code from accessing the private ones altogether. JavaScript, once again taking the minimalist approach, does not—not yet at least. There is work underway to add this to the language.
-Even though the language doesn't have this distinction built in,
-JavaScript programmers _are_ successfully using this idea. Typically,
-the available interface is described in documentation or comments. It
-is also common to put an underscore (`_`) character at the start of
-property names to indicate that those properties are private.
+Even though the language doesn't have this distinction built in, JavaScript programmers _are_ successfully using this idea. Typically, the available interface is described in documentation or comments. It is also common to put an underscore (`_`) character at the start of property names to indicate that those properties are private.
-Separating interface from implementation is a great idea. It is
-usually called _((encapsulation))_.
+Separating interface from implementation is a great idea. It is usually called _((encapsulation))_.
{{id obj_methods}}
@@ -76,8 +47,7 @@ usually called _((encapsulation))_.
{{index "rabbit example", method, [property, access]}}
-Methods are nothing more than properties that hold function values.
-This is a simple method:
+Methods are nothing more than properties that hold function values. This is a simple method:
```
let rabbit = {};
@@ -91,10 +61,7 @@ rabbit.speak("I'm alive.");
{{index "this binding", "method call"}}
-Usually a method needs to do something with the object it was called
-on. When a function is called as a method—looked up as a property and
-immediately called, as in `object.method()`—the binding called `this`
-in its body automatically points at the object that it was called on.
+Usually a method needs to do something with the object it was called on. When a function is called as a method—looked up as a property and immediately called, as in `object.method()`—the binding called `this` in its body automatically points at the object that it was called on.
```{includeCode: "top_lines:6", test: join}
function speak(line) {
@@ -115,26 +82,18 @@ hungryRabbit.speak("I could use a carrot right now.");
{{index "call method"}}
-You can think of `this` as an extra ((parameter)) that is passed in a
-different way. If you want to pass it explicitly, you can use a
-function's `call` method, which takes the `this` value as its first
-argument and treats further arguments as normal parameters.
+You can think of `this` as an extra ((parameter)) that is passed in a different way. If you want to pass it explicitly, you can use a function's `call` method, which takes the `this` value as its first argument and treats further arguments as normal parameters.
```
speak.call(hungryRabbit, "Burp!");
// → The hungry rabbit says 'Burp!'
```
-Since each function has its own `this` binding, whose value depends on
-the way it is called, you cannot refer to the `this` of the wrapping
-scope in a regular function defined with the `function` keyword.
+Since each function has its own `this` binding, whose value depends on the way it is called, you cannot refer to the `this` of the wrapping scope in a regular function defined with the `function` keyword.
{{index "this binding", "arrow function"}}
-Arrow functions are different—they do not bind their own `this` but
-can see the `this` binding of the scope around them. Thus, you can do
-something like the following code, which references `this` from inside
-a local function:
+Arrow functions are different—they do not bind their own `this` but can see the `this` binding of the scope around them. Thus, you can do something like the following code, which references `this` from inside a local function:
```
function normalize() {
@@ -146,8 +105,7 @@ normalize.call({coords: [0, 2, 3], length: 5});
{{index "map method"}}
-If I had written the argument to `map` using the `function` keyword,
-the code wouldn't work.
+If I had written the argument to `map` using the `function` keyword, the code wouldn't work.
{{id prototypes}}
@@ -171,19 +129,11 @@ I pulled a property out of an empty object. Magic!
{{index [property, inheritance], [object, property]}}
-Well, not really. I have simply been withholding information about the
-way JavaScript objects work. In addition to their set of properties,
-most objects also have a _((prototype))_. A prototype is another
-object that is used as a fallback source of properties. When an object
-gets a request for a property that it does not have, its prototype
-will be searched for the property, then the prototype's prototype, and
-so on.
+Well, not really. I have simply been withholding information about the way JavaScript objects work. In addition to their set of properties, most objects also have a _((prototype))_. A prototype is another object that is used as a fallback source of properties. When an object gets a request for a property that it does not have, its prototype will be searched for the property, then the prototype's prototype, and so on.
{{index "Object prototype"}}
-So who is the ((prototype)) of that empty object? It is the great
-ancestral prototype, the entity behind almost all objects,
-`Object.prototype`.
+So who is the ((prototype)) of that empty object? It is the great ancestral prototype, the entity behind almost all objects, `Object.prototype`.
```
console.log(Object.getPrototypeOf({}) ==
@@ -195,22 +145,15 @@ console.log(Object.getPrototypeOf(Object.prototype));
{{index "getPrototypeOf function"}}
-As you guess, `Object.getPrototypeOf` returns the prototype of an
-object.
+As you guess, `Object.getPrototypeOf` returns the prototype of an object.
{{index "toString method"}}
-The prototype relations of JavaScript objects form a ((tree))-shaped
-structure, and at the root of this structure sits `Object.prototype`.
-It provides a few methods that show up in all objects, such as
-`toString`, which converts an object to a string representation.
+The prototype relations of JavaScript objects form a ((tree))-shaped structure, and at the root of this structure sits `Object.prototype`. It provides a few methods that show up in all objects, such as `toString`, which converts an object to a string representation.
{{index inheritance, "Function prototype", "Array prototype", "Object prototype"}}
-Many objects don't directly have `Object.prototype` as their
-((prototype)) but instead have another object that provides a different set of
-default properties. Functions derive from `Function.prototype`, and
-arrays derive from `Array.prototype`.
+Many objects don't directly have `Object.prototype` as their ((prototype)) but instead have another object that provides a different set of default properties. Functions derive from `Function.prototype`, and arrays derive from `Array.prototype`.
```
console.log(Object.getPrototypeOf(Math.max) ==
@@ -223,14 +166,11 @@ console.log(Object.getPrototypeOf([]) ==
{{index "Object prototype"}}
-Such a prototype object will itself have a prototype, often
-`Object.prototype`, so that it still indirectly provides methods like
-`toString`.
+Such a prototype object will itself have a prototype, often `Object.prototype`, so that it still indirectly provides methods like `toString`.
{{index "rabbit example", "Object.create function"}}
-You can use `Object.create` to create an object with a specific
-((prototype)).
+You can use `Object.create` to create an object with a specific ((prototype)).
```
let protoRabbit = {
@@ -246,14 +186,9 @@ killerRabbit.speak("SKREEEE!");
{{index "shared property"}}
-A property like `speak(line)` in an object expression is a shorthand way
-of defining a method. It creates a property called `speak` and gives
-it a function as its value.
+A property like `speak(line)` in an object expression is a shorthand way of defining a method. It creates a property called `speak` and gives it a function as its value.
-The "proto" rabbit acts as a container for the properties that are
-shared by all rabbits. An individual rabbit object, like the killer
-rabbit, contains properties that apply only to itself—in this case its
-type—and derives shared properties from its prototype.
+The "proto" rabbit acts as a container for the properties that are shared by all rabbits. An individual rabbit object, like the killer rabbit, contains properties that apply only to itself—in this case its type—and derives shared properties from its prototype.
{{id classes}}
@@ -261,26 +196,15 @@ type—and derives shared properties from its prototype.
{{index "object-oriented programming"}}
-JavaScript's ((prototype)) system can be interpreted as a somewhat
-informal take on an object-oriented concept called _((class))es_. A
-class defines the shape of a type of object—what methods and
-properties it has. Such an object is called an _((instance))_ of the
-class.
+JavaScript's ((prototype)) system can be interpreted as a somewhat informal take on an object-oriented concept called _((class))es_. A class defines the shape of a type of object—what methods and properties it has. Such an object is called an _((instance))_ of the class.
{{index [property, inheritance]}}
-Prototypes are useful for defining properties for which all instances
-of a class share the same value, such as ((method))s. Properties that
-differ per instance, such as our rabbits' `type` property, need to
-be stored directly in the objects themselves.
+Prototypes are useful for defining properties for which all instances of a class share the same value, such as ((method))s. Properties that differ per instance, such as our rabbits' `type` property, need to be stored directly in the objects themselves.
{{id constructors}}
-So to create an instance of a given class, you have to make
-an object that derives from the proper prototype, but you _also_ have
-to make sure it, itself, has the properties that instances of this
-class are supposed to have. This is what a _((constructor))_ function
-does.
+So to create an instance of a given class, you have to make an object that derives from the proper prototype, but you _also_ have to make sure it, itself, has the properties that instances of this class are supposed to have. This is what a _((constructor))_ function does.
```
function makeRabbit(type) {
@@ -292,16 +216,11 @@ function makeRabbit(type) {
{{index "new operator", "this binding", "return keyword", [object, creation]}}
-JavaScript provides a way to make defining this type of function
-easier. If you put the keyword `new` in front of a function call, the
-function is treated as a constructor. This means that an object with
-the right prototype is automatically created, bound to `this` in the
-function, and returned at the end of the function.
+JavaScript provides a way to make defining this type of function easier. If you put the keyword `new` in front of a function call, the function is treated as a constructor. This means that an object with the right prototype is automatically created, bound to `this` in the function, and returned at the end of the function.
{{index "prototype property"}}
-The prototype object used when constructing objects is found by taking
-the `prototype` property of the constructor function.
+The prototype object used when constructing objects is found by taking the `prototype` property of the constructor function.
{{index "rabbit example"}}
@@ -318,26 +237,15 @@ let weirdRabbit = new Rabbit("weird");
{{index constructor}}
-Constructors (all functions, in fact) automatically get a property
-named `prototype`, which by default holds a plain, empty object that
-derives from `Object.prototype`. You can overwrite it with a new
-object if you want. Or you can add properties to the existing object,
-as the example does.
+Constructors (all functions, in fact) automatically get a property named `prototype`, which by default holds a plain, empty object that derives from `Object.prototype`. You can overwrite it with a new object if you want. Or you can add properties to the existing object, as the example does.
{{index capitalization}}
-By convention, the names of constructors are capitalized so that they
-can easily be distinguished from other functions.
+By convention, the names of constructors are capitalized so that they can easily be distinguished from other functions.
{{index "prototype property", "getPrototypeOf function"}}
-It is important to understand the distinction between the way a
-prototype is associated with a constructor (through its `prototype`
-property) and the way objects _have_ a prototype (which can be found
-with `Object.getPrototypeOf`). The actual prototype of a constructor
-is `Function.prototype` since constructors are functions. Its
-`prototype` _property_ holds the prototype used for instances created
-through it.
+It is important to understand the distinction between the way a prototype is associated with a constructor (through its `prototype` property) and the way objects _have_ a prototype (which can be found with `Object.getPrototypeOf`). The actual prototype of a constructor is `Function.prototype` since constructors are functions. Its `prototype` _property_ holds the prototype used for instances created through it.
```
console.log(Object.getPrototypeOf(Rabbit) ==
@@ -350,10 +258,7 @@ console.log(Object.getPrototypeOf(weirdRabbit) ==
## Class notation
-So JavaScript ((class))es are ((constructor)) functions with a
-((prototype)) property. That is how they work, and until 2015, that
-was how you had to write them. These days, we have a less awkward
-notation.
+So JavaScript ((class))es are ((constructor)) functions with a ((prototype)) property. That is how they work, and until 2015, that was how you had to write them. These days, we have a less awkward notation.
```{includeCode: true}
class Rabbit {
@@ -371,28 +276,13 @@ let blackRabbit = new Rabbit("black");
{{index "rabbit example", [braces, class]}}
-The `class` keyword starts a ((class declaration)), which allows us to
-define a constructor and a set of methods all in a single place. Any
-number of methods may be written inside the declaration's braces.
-The one named `constructor` is treated specially. It
-provides the actual constructor function, which will be bound to the
-name `Rabbit`. The others are packaged into that constructor's
-prototype. Thus, the earlier class declaration is equivalent to the
-constructor definition from the previous section. It just looks nicer.
+The `class` keyword starts a ((class declaration)), which allows us to define a constructor and a set of methods all in a single place. Any number of methods may be written inside the declaration's braces. The one named `constructor` is treated specially. It provides the actual constructor function, which will be bound to the name `Rabbit`. The others are packaged into that constructor's prototype. Thus, the earlier class declaration is equivalent to the constructor definition from the previous section. It just looks nicer.
{{index ["class declaration", properties]}}
-Class declarations currently allow only _methods_—properties that hold
-functions—to be added to the ((prototype)). This can be somewhat
-inconvenient when you want to save a non-function value in there.
-The next version of the language will probably improve this. For now, you
-can create such properties by directly manipulating the
-prototype after you've defined the class.
+Class declarations currently allow only _methods_—properties that hold functions—to be added to the ((prototype)). This can be somewhat inconvenient when you want to save a non-function value in there. The next version of the language will probably improve this. For now, you can create such properties by directly manipulating the prototype after you've defined the class.
-Like `function`, `class` can be used both in statements and in
-expressions. When used as an expression, it doesn't define a
-binding but just produces the constructor as a value. You are allowed
-to omit the class name in a class expression.
+Like `function`, `class` can be used both in statements and in expressions. When used as an expression, it doesn't define a binding but just produces the constructor as a value. You are allowed to omit the class name in a class expression.
```
let object = new class { getWord() { return "hello"; } };
@@ -404,11 +294,7 @@ console.log(object.getWord());
{{index "shared property", overriding, [property, inheritance]}}
-When you add a property to an object, whether it is present in the
-prototype or not, the property is added to the object _itself_.
-If there was already a property with
-the same name in the prototype, this property will no longer affect
-the object, as it is now hidden behind the object's own property.
+When you add a property to an object, whether it is present in the prototype or not, the property is added to the object _itself_. If there was already a property with the same name in the prototype, this property will no longer affect the object, as it is now hidden behind the object's own property.
```
Rabbit.prototype.teeth = "small";
@@ -425,25 +311,17 @@ console.log(Rabbit.prototype.teeth);
{{index [prototype, diagram]}}
-The following diagram sketches the situation after this code has run.
-The `Rabbit` and `Object` ((prototype))s lie behind `killerRabbit` as
-a kind of backdrop, where properties that are not found in the object
-itself can be looked up.
+The following diagram sketches the situation after this code has run. The `Rabbit` and `Object` ((prototype))s lie behind `killerRabbit` as a kind of backdrop, where properties that are not found in the object itself can be looked up.
{{figure {url: "img/rabbits.svg", alt: "Rabbit object prototype schema",width: "8cm"}}}
{{index "shared property"}}
-Overriding properties that exist in a prototype can be a useful thing
-to do. As the rabbit teeth example shows, overriding can be used to express
-exceptional properties in instances of a more generic class of
-objects, while letting the nonexceptional objects take a
-standard value from their prototype.
+Overriding properties that exist in a prototype can be a useful thing to do. As the rabbit teeth example shows, overriding can be used to express exceptional properties in instances of a more generic class of objects, while letting the nonexceptional objects take a standard value from their prototype.
{{index "toString method", "Array prototype", "Function prototype"}}
-Overriding is also used to give the standard function and array prototypes a
-different `toString` method than the basic object prototype.
+Overriding is also used to give the standard function and array prototypes a different `toString` method than the basic object prototype.
```
console.log(Array.prototype.toString ==
@@ -455,12 +333,7 @@ console.log([1, 2].toString());
{{index "toString method", "join method", "call method"}}
-Calling `toString` on an array gives a result similar to calling
-`.join(",")` on it—it puts commas between the values in the array.
-Directly calling `Object.prototype.toString` with an array produces a
-different string. That function doesn't know about arrays, so it
-simply puts the word _object_ and the name of the type between square
-brackets.
+Calling `toString` on an array gives a result similar to calling `.join(",")` on it—it puts commas between the values in the array. Directly calling `Object.prototype.toString` with an array produces a different string. That function doesn't know about arrays, so it simply puts the word _object_ and the name of the type between square brackets.
```
console.log(Object.prototype.toString.call([1, 2]));
@@ -471,16 +344,11 @@ console.log(Object.prototype.toString.call([1, 2]));
{{index "map method"}}
-We saw the word _map_ used in the [previous chapter](higher_order#map)
-for an operation that transforms a data structure by applying a
-function to its elements. Confusing as it is, in programming the same
-word is also used for a related but rather different thing.
+We saw the word _map_ used in the [previous chapter](higher_order#map) for an operation that transforms a data structure by applying a function to its elements. Confusing as it is, in programming the same word is also used for a related but rather different thing.
{{index "map (data structure)", "ages example", ["data structure", map]}}
-A _map_ (noun) is a data structure that associates values (the keys)
-with other values. For example, you might want to map names to ages.
-It is possible to use objects for this.
+A _map_ (noun) is a data structure that associates values (the keys) with other values. For example, you might want to map names to ages. It is possible to use objects for this.
```
let ages = {
@@ -499,18 +367,11 @@ console.log("Is toString's age known?", "toString" in ages);
{{index "Object.prototype", "toString method"}}
-Here, the object's property names are the people's names, and the
-property values are their ages. But we certainly didn't list anybody named
-toString in our map. Yet, because plain objects derive from
-`Object.prototype`, it looks like the property is there.
+Here, the object's property names are the people's names, and the property values are their ages. But we certainly didn't list anybody named toString in our map. Yet, because plain objects derive from `Object.prototype`, it looks like the property is there.
{{index "Object.create function", prototype}}
-As such, using plain objects as maps is dangerous. There are several
-possible ways to avoid this problem. First, it is possible to create
-objects with _no_ prototype. If you pass `null` to `Object.create`,
-the resulting object will not derive from `Object.prototype` and can
-safely be used as a map.
+As such, using plain objects as maps is dangerous. There are several possible ways to avoid this problem. First, it is possible to create objects with _no_ prototype. If you pass `null` to `Object.create`, the resulting object will not derive from `Object.prototype` and can safely be used as a map.
```
console.log("toString" in Object.create(null));
@@ -519,15 +380,11 @@ console.log("toString" in Object.create(null));
{{index [property, naming]}}
-Object property names must be strings. If you need a map whose
-keys can't easily be converted to strings—such as objects—you cannot
-use an object as your map.
+Object property names must be strings. If you need a map whose keys can't easily be converted to strings—such as objects—you cannot use an object as your map.
{{index "Map class"}}
-Fortunately, JavaScript comes with a class called `Map` that is
-written for this exact purpose. It stores a mapping and allows any
-type of keys.
+Fortunately, JavaScript comes with a class called `Map` that is written for this exact purpose. It stores a mapping and allows any type of keys.
```
let ages = new Map();
@@ -545,19 +402,11 @@ console.log(ages.has("toString"));
{{index [interface, object], "set method", "get method", "has method", encapsulation}}
-The methods `set`, `get`, and `has` are part of the interface of the
-`Map` object. Writing a data structure that can quickly update and
-search a large set of values isn't easy, but we don't have to worry
-about that. Someone else did it for us, and we can go through this
-simple interface to use their work.
+The methods `set`, `get`, and `has` are part of the interface of the `Map` object. Writing a data structure that can quickly update and search a large set of values isn't easy, but we don't have to worry about that. Someone else did it for us, and we can go through this simple interface to use their work.
{{index "hasOwnProperty method", "in operator"}}
-If you do have a plain object that you need to treat as a map for some
-reason, it is useful to know that `Object.keys` returns only an
-object's _own_ keys, not those in the prototype. As an alternative to
-the `in` operator, you can use the `hasOwnProperty` method, which
-ignores the object's prototype.
+If you do have a plain object that you need to treat as a map for some reason, it is useful to know that `Object.keys` returns only an object's _own_ keys, not those in the prototype. As an alternative to the `in` operator, you can use the `hasOwnProperty` method, which ignores the object's prototype.
```
console.log({x: 1}.hasOwnProperty("x"));
@@ -570,12 +419,7 @@ console.log({x: 1}.hasOwnProperty("toString"));
{{index "toString method", "String function", polymorphism, overriding, "object-oriented programming"}}
-When you call the `String` function (which converts a value to a
-string) on an object, it will call the `toString` method on that
-object to try to create a meaningful string from it. I mentioned that
-some of the standard prototypes define their own version of `toString`
-so they can create a string that contains more useful information than
-`"[object Object]"`. You can also do that yourself.
+When you call the `String` function (which converts a value to a string) on an object, it will call the `toString` method on that object to try to create a meaningful string from it. I mentioned that some of the standard prototypes define their own version of `toString` so they can create a string that contains more useful information than `"[object Object]"`. You can also do that yourself.
```{includeCode: "top_lines: 3"}
Rabbit.prototype.toString = function() {
@@ -588,44 +432,23 @@ console.log(String(blackRabbit));
{{index "object-oriented programming", [interface, object]}}
-This is a simple instance of a powerful idea. When a piece of code is
-written to work with objects that have a certain interface—in this
-case, a `toString` method—any kind of object that happens to support
-this interface can be plugged into the code, and it will just work.
+This is a simple instance of a powerful idea. When a piece of code is written to work with objects that have a certain interface—in this case, a `toString` method—any kind of object that happens to support this interface can be plugged into the code, and it will just work.
-This technique is called _polymorphism_. Polymorphic code can work
-with values of different shapes, as long as they support the interface
-it expects.
+This technique is called _polymorphism_. Polymorphic code can work with values of different shapes, as long as they support the interface it expects.
{{index "for/of loop", "iterator interface"}}
-I mentioned in [Chapter ?](data#for_of_loop) that a `for`/`of` loop
-can loop over several kinds of data structures. This is another case
-of polymorphism—such loops expect the data structure to expose a
-specific interface, which arrays and strings do. And we can also add
-this interface to our own objects! But before we can do that, we need
-to know what symbols are.
+I mentioned in [Chapter ?](data#for_of_loop) that a `for`/`of` loop can loop over several kinds of data structures. This is another case of polymorphism—such loops expect the data structure to expose a specific interface, which arrays and strings do. And we can also add this interface to our own objects! But before we can do that, we need to know what symbols are.
## Symbols
-It is possible for multiple interfaces to use the same property name
-for different things. For example, I could define an interface in which
-the `toString` method is supposed to convert the object into a piece
-of yarn. It would not be possible for an object to conform to both
-that interface and the standard use of `toString`.
+It is possible for multiple interfaces to use the same property name for different things. For example, I could define an interface in which the `toString` method is supposed to convert the object into a piece of yarn. It would not be possible for an object to conform to both that interface and the standard use of `toString`.
-That would be a bad idea, and this problem isn't that common. Most
-JavaScript programmers simply don't think about it. But the language
-designers, whose _job_ it is to think about this stuff, have provided
-us with a solution anyway.
+That would be a bad idea, and this problem isn't that common. Most JavaScript programmers simply don't think about it. But the language designers, whose _job_ it is to think about this stuff, have provided us with a solution anyway.
{{index "Symbol function", [property, naming]}}
-When I claimed that property names are strings, that wasn't entirely
-accurate. They usually are, but they can also be _((symbol))s_.
-Symbols are values created with the `Symbol` function. Unlike strings,
-newly created symbols are unique—you cannot create the same symbol
-twice.
+When I claimed that property names are strings, that wasn't entirely accurate. They usually are, but they can also be _((symbol))s_. Symbols are values created with the `Symbol` function. Unlike strings, newly created symbols are unique—you cannot create the same symbol twice.
```
let sym = Symbol("name");
@@ -636,14 +459,9 @@ console.log(blackRabbit[sym]);
// → 55
```
-The string you pass to `Symbol` is included when you convert it to a
-string and can make it easier to recognize a symbol when, for
-example, showing it in the console. But it has no meaning beyond
-that—multiple symbols may have the same name.
+The string you pass to `Symbol` is included when you convert it to a string and can make it easier to recognize a symbol when, for example, showing it in the console. But it has no meaning beyond that—multiple symbols may have the same name.
-Being both unique and usable as property names makes symbols suitable
-for defining interfaces that can peacefully live alongside other
-properties, no matter what their names are.
+Being both unique and usable as property names makes symbols suitable for defining interfaces that can peacefully live alongside other properties, no matter what their names are.
```{includeCode: "top_lines: 1"}
const toStringSymbol = Symbol("toString");
@@ -659,11 +477,7 @@ console.log([1, 2][toStringSymbol]());
{{index [property, naming]}}
-It is possible to include symbol properties in object expressions and
-classes by using ((square bracket))s around the property name.
-That causes the property name to be evaluated, much like the square
-bracket property access notation, which allows us to refer to a
-binding that holds the symbol.
+It is possible to include symbol properties in object expressions and classes by using ((square bracket))s around the property name. That causes the property name to be evaluated, much like the square bracket property access notation, which allows us to refer to a binding that holds the symbol.
```
let stringObject = {
@@ -677,23 +491,13 @@ console.log(stringObject[toStringSymbol]());
{{index "iterable interface", "Symbol.iterator symbol", "for/of loop"}}
-The object given to a `for`/`of` loop is expected to be _iterable_.
-This means it has a method named with the `Symbol.iterator`
-symbol (a symbol value defined by the language, stored as a property
-of the `Symbol` function).
+The object given to a `for`/`of` loop is expected to be _iterable_. This means it has a method named with the `Symbol.iterator` symbol (a symbol value defined by the language, stored as a property of the `Symbol` function).
{{index "iterator interface", "next method"}}
-When called, that method should return an object that provides a
-second interface, _iterator_. This is the actual thing that iterates.
-It has a `next` method that returns the next result. That result
-should be an object with a `value` property that provides the next value,
-if there is one, and a `done` property, which should be true when there
-are no more results and false otherwise.
+When called, that method should return an object that provides a second interface, _iterator_. This is the actual thing that iterates. It has a `next` method that returns the next result. That result should be an object with a `value` property that provides the next value, if there is one, and a `done` property, which should be true when there are no more results and false otherwise.
-Note that the `next`, `value`, and `done` property names are plain
-strings, not symbols. Only `Symbol.iterator`, which is likely to be
-added to a _lot_ of different objects, is an actual symbol.
+Note that the `next`, `value`, and `done` property names are plain strings, not symbols. Only `Symbol.iterator`, which is likely to be added to a _lot_ of different objects, is an actual symbol.
We can directly use this interface ourselves.
@@ -711,8 +515,7 @@ console.log(okIterator.next());
{{id matrix}}
-Let's implement an iterable data structure. We'll build a _matrix_
-class, acting as a two-dimensional array.
+Let's implement an iterable data structure. We'll build a _matrix_ class, acting as a two-dimensional array.
```{includeCode: true}
class Matrix {
@@ -737,19 +540,11 @@ class Matrix {
}
```
-The class stores its content in a single array of _width_ × _height_
-elements. The elements are stored row by row, so, for example, the third
-element in the fifth row is (using zero-based indexing) stored at
-position 4 × _width_ + 2.
+The class stores its content in a single array of _width_ × _height_ elements. The elements are stored row by row, so, for example, the third element in the fifth row is (using zero-based indexing) stored at position 4 × _width_ + 2.
-The constructor function takes a width, a height, and an optional
-`element` function that will be used to fill in the initial values.
-There are `get` and `set` methods to retrieve and update elements in
-the matrix.
+The constructor function takes a width, a height, and an optional `element` function that will be used to fill in the initial values. There are `get` and `set` methods to retrieve and update elements in the matrix.
-When looping over a matrix, you are usually interested in the position
-of the elements as well as the elements themselves, so we'll have our
-iterator produce objects with `x`, `y`, and `value` properties.
+When looping over a matrix, you are usually interested in the position of the elements as well as the elements themselves, so we'll have our iterator produce objects with `x`, `y`, and `value` properties.
{{index "MatrixIterator class"}}
@@ -777,18 +572,9 @@ class MatrixIterator {
}
```
-The class tracks the progress of iterating over a matrix in its `x`
-and `y` properties. The `next` method starts by checking whether the
-bottom of the matrix has been reached. If it hasn't, it _first_
-creates the object holding the current value and _then_ updates its
-position, moving to the next row if necessary.
+The class tracks the progress of iterating over a matrix in its `x` and `y` properties. The `next` method starts by checking whether the bottom of the matrix has been reached. If it hasn't, it _first_ creates the object holding the current value and _then_ updates its position, moving to the next row if necessary.
-Let's set up the `Matrix` class to be iterable. Throughout this book,
-I'll occasionally use after-the-fact prototype manipulation to add
-methods to classes so that the individual pieces of code remain small
-and self-contained. In a regular program, where there is no need to
-split the code into small pieces, you'd declare these methods directly
-in the class instead.
+Let's set up the `Matrix` class to be iterable. Throughout this book, I'll occasionally use after-the-fact prototype manipulation to add methods to classes so that the individual pieces of code remain small and self-contained. In a regular program, where there is no need to split the code into small pieces, you'd declare these methods directly in the class instead.
```{includeCode: true}
Matrix.prototype[Symbol.iterator] = function() {
@@ -815,16 +601,9 @@ for (let {x, y, value} of matrix) {
{{index [interface, object], [property, definition], "Map class"}}
-Interfaces often consist mostly of methods, but it is also okay to
-include properties that hold non-function values. For example, `Map`
-objects have a `size` property that tells you how many keys are stored
-in them.
+Interfaces often consist mostly of methods, but it is also okay to include properties that hold non-function values. For example, `Map` objects have a `size` property that tells you how many keys are stored in them.
-It is not even necessary for such an object to compute and store such
-a property directly in the instance. Even properties that are accessed
-directly may hide a method call. Such methods are called
-_((getter))s_, and they are defined by writing `get` in front of the
-method name in an object expression or class declaration.
+It is not even necessary for such an object to compute and store such a property directly in the instance. Even properties that are accessed directly may hide a method call. Such methods are called _((getter))s_, and they are defined by writing `get` in front of the method name in an object expression or class declaration.
```{test: no}
let varyingSize = {
@@ -841,9 +620,7 @@ console.log(varyingSize.size);
{{index "temperature example"}}
-Whenever someone reads from this object's `size` property, the
-associated method is called. You can do a similar thing when a
-property is written to, using a _((setter))_.
+Whenever someone reads from this object's `size` property, the associated method is called. You can do a similar thing when a property is written to, using a _((setter))_.
```{test: no, startCode: true}
class Temperature {
@@ -870,47 +647,27 @@ console.log(temp.celsius);
// → 30
```
-The `Temperature` class allows you to read and write the temperature
-in either degrees ((Celsius)) or degrees ((Fahrenheit)), but
-internally it stores only Celsius and automatically converts to
-and from Celsius in the `fahrenheit` getter and setter.
+The `Temperature` class allows you to read and write the temperature in either degrees ((Celsius)) or degrees ((Fahrenheit)), but internally it stores only Celsius and automatically converts to and from Celsius in the `fahrenheit` getter and setter.
{{index "static method"}}
-Sometimes you want to attach some properties directly to your
-constructor function, rather than to the prototype. Such methods won't
-have access to a class instance but can, for example, be used to
-provide additional ways to create instances.
+Sometimes you want to attach some properties directly to your constructor function, rather than to the prototype. Such methods won't have access to a class instance but can, for example, be used to provide additional ways to create instances.
-Inside a class declaration, methods that have `static` written before
-their name are stored on the constructor. So the `Temperature` class
-allows you to write `Temperature.fromFahrenheit(100)` to create a
-temperature using degrees Fahrenheit.
+Inside a class declaration, methods that have `static` written before their name are stored on the constructor. So the `Temperature` class allows you to write `Temperature.fromFahrenheit(100)` to create a temperature using degrees Fahrenheit.
## Inheritance
{{index inheritance, "matrix example", "object-oriented programming", "SymmetricMatrix class"}}
-Some matrices are known to be _symmetric_. If you mirror a symmetric
-matrix around its top-left-to-bottom-right diagonal, it stays the
-same. In other words, the value stored at _x_,_y_ is always the same
-as that at _y_,_x_.
+Some matrices are known to be _symmetric_. If you mirror a symmetric matrix around its top-left-to-bottom-right diagonal, it stays the same. In other words, the value stored at _x_,_y_ is always the same as that at _y_,_x_.
-Imagine we need a data structure like `Matrix` but one that enforces
-the fact that the matrix is and remains symmetrical. We could write it
-from scratch, but that would involve repeating some code very similar
-to what we already wrote.
+Imagine we need a data structure like `Matrix` but one that enforces the fact that the matrix is and remains symmetrical. We could write it from scratch, but that would involve repeating some code very similar to what we already wrote.
{{index overriding, prototype}}
-JavaScript's prototype system makes it possible to create a _new_
-class, much like the old class, but with new definitions for some of
-its properties. The prototype for the new class derives from the old
-prototype but adds a new definition for, say, the `set` method.
+JavaScript's prototype system makes it possible to create a _new_ class, much like the old class, but with new definitions for some of its properties. The prototype for the new class derives from the old prototype but adds a new definition for, say, the `set` method.
-In object-oriented programming terms, this is called
-_((inheritance))_. The new class inherits properties and behavior from
-the old class.
+In object-oriented programming terms, this is called _((inheritance))_. The new class inherits properties and behavior from the old class.
```{includeCode: "top_lines: 17"}
class SymmetricMatrix extends Matrix {
@@ -934,51 +691,23 @@ console.log(matrix.get(2, 3));
// → 3,2
```
-The use of the word `extends` indicates that this class shouldn't be
-directly based on the default `Object` prototype but on some other class. This
-is called the _((superclass))_. The derived class is the
-_((subclass))_.
-
-To initialize a `SymmetricMatrix` instance, the constructor calls its
-superclass's constructor through the `super` keyword. This is necessary
-because if this new object is to behave (roughly) like a `Matrix`, it
-is going to need the instance properties that matrices have.
-To ensure the matrix is symmetrical, the constructor wraps the
-`element` function to swap the coordinates for values below the
-diagonal.
-
-The `set` method again uses `super` but this time not to call the
-constructor but to call a specific method from the superclass's set of
-methods. We are redefining `set` but do want to use the original
-behavior. Because `this.set` refers to the _new_ `set` method, calling
-that wouldn't work. Inside class methods, `super` provides a way to
-call methods as they were defined in the superclass.
-
-Inheritance allows us to build slightly different data types from
-existing data types with relatively little work. It is a fundamental
-part of the object-oriented tradition, alongside encapsulation and
-polymorphism. But while the latter two are now generally regarded as
-wonderful ideas, inheritance is more controversial.
+The use of the word `extends` indicates that this class shouldn't be directly based on the default `Object` prototype but on some other class. This is called the _((superclass))_. The derived class is the _((subclass))_.
+
+To initialize a `SymmetricMatrix` instance, the constructor calls its superclass's constructor through the `super` keyword. This is necessary because if this new object is to behave (roughly) like a `Matrix`, it is going to need the instance properties that matrices have. To ensure the matrix is symmetrical, the constructor wraps the `element` function to swap the coordinates for values below the diagonal.
+
+The `set` method again uses `super` but this time not to call the constructor but to call a specific method from the superclass's set of methods. We are redefining `set` but do want to use the original behavior. Because `this.set` refers to the _new_ `set` method, calling that wouldn't work. Inside class methods, `super` provides a way to call methods as they were defined in the superclass.
+
+Inheritance allows us to build slightly different data types from existing data types with relatively little work. It is a fundamental part of the object-oriented tradition, alongside encapsulation and polymorphism. But while the latter two are now generally regarded as wonderful ideas, inheritance is more controversial.
{{index complexity, reuse, "class hierarchy"}}
-Whereas ((encapsulation)) and polymorphism can be used to _separate_
-pieces of code from each other, reducing the tangledness of the
-overall program, ((inheritance)) fundamentally ties classes together,
-creating _more_ tangle. When inheriting from a class, you usually have
-to know more about how it works than when simply using it. Inheritance
-can be a useful tool, and I use it now and then in my own programs,
-but it shouldn't be the first tool you reach for, and you probably
-shouldn't actively go looking for opportunities to construct class
-hierarchies (family trees of classes).
+Whereas ((encapsulation)) and polymorphism can be used to _separate_ pieces of code from each other, reducing the tangledness of the overall program, ((inheritance)) fundamentally ties classes together, creating _more_ tangle. When inheriting from a class, you usually have to know more about how it works than when simply using it. Inheritance can be a useful tool, and I use it now and then in my own programs, but it shouldn't be the first tool you reach for, and you probably shouldn't actively go looking for opportunities to construct class hierarchies (family trees of classes).
## The instanceof operator
{{index type, "instanceof operator", constructor, object}}
-It is occasionally useful to know whether an object was derived from a
-specific class. For this, JavaScript provides a binary operator called
-`instanceof`.
+It is occasionally useful to know whether an object was derived from a specific class. For this, JavaScript provides a binary operator called `instanceof`.
```
console.log(
@@ -994,46 +723,23 @@ console.log([1] instanceof Array);
{{index inheritance}}
-The operator will see through inherited types, so a `SymmetricMatrix`
-is an instance of `Matrix`. The operator can also be applied to
-standard constructors like `Array`. Almost every object is an instance
-of `Object`.
+The operator will see through inherited types, so a `SymmetricMatrix` is an instance of `Matrix`. The operator can also be applied to standard constructors like `Array`. Almost every object is an instance of `Object`.
## Summary
-So objects do more than just hold their own properties. They have
-prototypes, which are other objects. They'll act as if they have
-properties they don't have as long as their prototype has that
-property. Simple objects have `Object.prototype` as their prototype.
+So objects do more than just hold their own properties. They have prototypes, which are other objects. They'll act as if they have properties they don't have as long as their prototype has that property. Simple objects have `Object.prototype` as their prototype.
-Constructors, which are functions whose names usually start with a
-capital letter, can be used with the `new` operator to create new
-objects. The new object's prototype will be the object found in the
-`prototype` property of the constructor. You can make good use of this
-by putting the properties that all values of a given type share into
-their prototype. There's a `class` notation that provides a clear way
-to define a constructor and its prototype.
+Constructors, which are functions whose names usually start with a capital letter, can be used with the `new` operator to create new objects. The new object's prototype will be the object found in the `prototype` property of the constructor. You can make good use of this by putting the properties that all values of a given type share into their prototype. There's a `class` notation that provides a clear way to define a constructor and its prototype.
-You can define getters and setters to secretly call methods every time
-an object's property is accessed. Static methods are methods stored in
-a class's constructor, rather than its prototype.
+You can define getters and setters to secretly call methods every time an object's property is accessed. Static methods are methods stored in a class's constructor, rather than its prototype.
-The `instanceof` operator can, given an object and a constructor, tell
-you whether that object is an instance of that constructor.
+The `instanceof` operator can, given an object and a constructor, tell you whether that object is an instance of that constructor.
-One useful thing to do with objects is to specify an interface for
-them and tell everybody that they are supposed to talk to your object
-only through that interface. The rest of the details that make up your
-object are now _encapsulated_, hidden behind the interface.
+One useful thing to do with objects is to specify an interface for them and tell everybody that they are supposed to talk to your object only through that interface. The rest of the details that make up your object are now _encapsulated_, hidden behind the interface.
-More than one type may implement the same interface. Code written to
-use an interface automatically knows how to work with any number of
-different objects that provide the interface. This is called
-_polymorphism_.
+More than one type may implement the same interface. Code written to use an interface automatically knows how to work with any number of different objects that provide the interface. This is called _polymorphism_.
-When implementing multiple classes that differ in only some details,
-it can be helpful to write the new classes as _subclasses_ of an
-existing class, _inheriting_ part of its behavior.
+When implementing multiple classes that differ in only some details, it can be helpful to write the new classes as _subclasses_ of an existing class, _inheriting_ part of its behavior.
## Exercises
@@ -1043,20 +749,13 @@ existing class, _inheriting_ part of its behavior.
{{index dimensions, "Vec class", coordinates, "vector (exercise)"}}
-Write a ((class)) `Vec` that represents a vector in two-dimensional
-space. It takes `x` and `y` parameters (numbers), which it should save
-to properties of the same name.
+Write a ((class)) `Vec` that represents a vector in two-dimensional space. It takes `x` and `y` parameters (numbers), which it should save to properties of the same name.
{{index addition, subtraction}}
-Give the `Vec` prototype two methods, `plus` and `minus`, that take
-another vector as a parameter and return a new vector that has the sum
-or difference of the two vectors' (`this` and the parameter) _x_ and
-_y_ values.
+Give the `Vec` prototype two methods, `plus` and `minus`, that take another vector as a parameter and return a new vector that has the sum or difference of the two vectors' (`this` and the parameter) _x_ and _y_ values.
-Add a ((getter)) property `length` to the prototype that computes the
-length of the vector—that is, the distance of the point (_x_, _y_) from
-the origin (0, 0).
+Add a ((getter)) property `length` to the prototype that computes the length of the vector—that is, the distance of the point (_x_, _y_) from the origin (0, 0).
{{if interactive
@@ -1076,19 +775,11 @@ if}}
{{index "vector (exercise)"}}
-Look back to the `Rabbit` class example if you're unsure how `class`
-declarations look.
+Look back to the `Rabbit` class example if you're unsure how `class` declarations look.
{{index Pythagoras, "defineProperty function", "square root", "Math.sqrt function"}}
-Adding a getter property to the constructor can be done by putting the
-word `get` before the method name. To compute the distance from (0, 0)
-to (x, y), you can use the Pythagorean theorem, which says that the
-square of the distance we are looking for is equal to the square of
-the x-coordinate plus the square of the y-coordinate. Thus, [√(x^2^ +
-y^2^)]{if html}[[$\sqrt{x^2 + y^2}$]{latex}]{if tex} is the number you
-want, and `Math.sqrt` is the way you compute a square root in
-JavaScript.
+Adding a getter property to the constructor can be done by putting the word `get` before the method name. To compute the distance from (0, 0) to (x, y), you can use the Pythagorean theorem, which says that the square of the distance we are looking for is equal to the square of the x-coordinate plus the square of the y-coordinate. Thus, [√(x^2^ + y^2^)]{if html}[[$\sqrt{x^2 + y^2}$]{latex}]{if tex} is the number you want, and `Math.sqrt` is the way you compute a square root in JavaScript.
hint}}
@@ -1098,31 +789,19 @@ hint}}
{{id groups}}
-The standard JavaScript environment provides another data structure
-called `Set`. Like an instance of `Map`, a set holds a collection of
-values. Unlike `Map`, it does not associate other values with those—it
-just tracks which values are part of the set. A value can be part
-of a set only once—adding it again doesn't have any effect.
+The standard JavaScript environment provides another data structure called `Set`. Like an instance of `Map`, a set holds a collection of values. Unlike `Map`, it does not associate other values with those—it just tracks which values are part of the set. A value can be part of a set only once—adding it again doesn't have any effect.
{{index "add method", "delete method", "has method"}}
-Write a class called `Group` (since `Set` is already taken). Like
-`Set`, it has `add`, `delete`, and `has` methods. Its constructor
-creates an empty group, `add` adds a value to the group (but only if
-it isn't already a member), `delete` removes its argument from the
-group (if it was a member), and `has` returns a Boolean value
-indicating whether its argument is a member of the group.
+Write a class called `Group` (since `Set` is already taken). Like `Set`, it has `add`, `delete`, and `has` methods. Its constructor creates an empty group, `add` adds a value to the group (but only if it isn't already a member), `delete` removes its argument from the group (if it was a member), and `has` returns a Boolean value indicating whether its argument is a member of the group.
{{index "=== operator", "indexOf method"}}
-Use the `===` operator, or something equivalent such as `indexOf`, to
-determine whether two values are the same.
+Use the `===` operator, or something equivalent such as `indexOf`, to determine whether two values are the same.
{{index "static method"}}
-Give the class a static `from` method that takes an iterable object
-as argument and creates a group that contains all the values produced
-by iterating over it.
+Give the class a static `from` method that takes an iterable object as argument and creates a group that contains all the values produced by iterating over it.
{{if interactive
@@ -1148,28 +827,19 @@ if}}
{{index "groups (exercise)", "Group class", "indexOf method", "includes method"}}
-The easiest way to do this is to store an array of group members
-in an instance property. The `includes` or `indexOf` methods can be
-used to check whether a given value is in the array.
+The easiest way to do this is to store an array of group members in an instance property. The `includes` or `indexOf` methods can be used to check whether a given value is in the array.
{{index "push method"}}
-Your class's ((constructor)) can set the member collection to an empty
-array. When `add` is called, it must check whether the given value is
-in the array or add it, for example with `push`, otherwise.
+Your class's ((constructor)) can set the member collection to an empty array. When `add` is called, it must check whether the given value is in the array or add it, for example with `push`, otherwise.
{{index "filter method"}}
-Deleting an element from an array, in `delete`, is less
-straightforward, but you can use `filter` to create a new array
-without the value. Don't forget to overwrite the property holding the
-members with the newly filtered version of the array.
+Deleting an element from an array, in `delete`, is less straightforward, but you can use `filter` to create a new array without the value. Don't forget to overwrite the property holding the members with the newly filtered version of the array.
{{index "for/of loop", "iterable interface"}}
-The `from` method can use a `for`/`of` loop to get the values out of
-the iterable object and call `add` to put them into a newly created
-group.
+The `from` method can use a `for`/`of` loop to get the values out of the iterable object and call `add` to put them into a newly created group.
hint}}
@@ -1179,16 +849,11 @@ hint}}
{{id group_iterator}}
-Make the `Group` class from the previous exercise iterable. Refer
-to the section about the iterator interface earlier in the chapter if
-you aren't clear on the exact form of the interface anymore.
+Make the `Group` class from the previous exercise iterable. Refer to the section about the iterator interface earlier in the chapter if you aren't clear on the exact form of the interface anymore.
-If you used an array to represent the group's members, don't just
-return the iterator created by calling the `Symbol.iterator` method on
-the array. That would work, but it defeats the purpose of this exercise.
+If you used an array to represent the group's members, don't just return the iterator created by calling the `Symbol.iterator` method on the array. That would work, but it defeats the purpose of this exercise.
-It is okay if your iterator behaves strangely when the group is
-modified during iteration.
+It is okay if your iterator behaves strangely when the group is modified during iteration.
{{if interactive
@@ -1209,28 +874,17 @@ if}}
{{index "groups (exercise)", "Group class", "next method"}}
-It is probably worthwhile to define a new class `GroupIterator`.
-Iterator instances should have a property that tracks the current
-position in the group. Every time `next` is called, it checks whether
-it is done and, if not, moves past the current value and returns it.
+It is probably worthwhile to define a new class `GroupIterator`. Iterator instances should have a property that tracks the current position in the group. Every time `next` is called, it checks whether it is done and, if not, moves past the current value and returns it.
-The `Group` class itself gets a method named by `Symbol.iterator`
-that, when called, returns a new instance of the iterator class for
-that group.
+The `Group` class itself gets a method named by `Symbol.iterator` that, when called, returns a new instance of the iterator class for that group.
hint}}
### Borrowing a method
-Earlier in the chapter I mentioned that an object's `hasOwnProperty`
-can be used as a more robust alternative to the `in` operator when you
-want to ignore the prototype's properties. But what if your map needs
-to include the word `"hasOwnProperty"`? You won't be able to call that
-method anymore because the object's own property hides the method
-value.
+Earlier in the chapter I mentioned that an object's `hasOwnProperty` can be used as a more robust alternative to the `in` operator when you want to ignore the prototype's properties. But what if your map needs to include the word `"hasOwnProperty"`? You won't be able to call that method anymore because the object's own property hides the method value.
-Can you think of a way to call `hasOwnProperty` on an object that has
-its own property by that name?
+Can you think of a way to call `hasOwnProperty` on an object that has its own property by that name?
{{if interactive
@@ -1246,10 +900,8 @@ if}}
{{hint
-Remember that methods that exist on plain objects come from
-`Object.prototype`.
+Remember that methods that exist on plain objects come from `Object.prototype`.
-Also remember that you can call a function with a specific `this`
-binding by using its `call` method.
+Also remember that you can call a function with a specific `this` binding by using its `call` method.
hint}}
diff --git a/07_robot.md b/07_robot.md
index 61f29d295..8771fbe68 100644
--- a/07_robot.md
+++ b/07_robot.md
@@ -4,8 +4,7 @@
{{quote {author: "Edsger Dijkstra", title: "The Threats to Computing Science", chapter: true}
-[...] the question of whether Machines Can Think [...] is about as
-relevant as the question of whether Submarines Can Swim.
+[...] the question of whether Machines Can Think [...] is about as relevant as the question of whether Submarines Can Swim.
quote}}
@@ -15,22 +14,15 @@ quote}}
{{index "project chapter", "reading code", "writing code"}}
-In "project" chapters, I'll stop pummeling you with new theory for a
-brief moment, and instead we'll work through a program together. Theory
-is necessary to learn to program, but reading and understanding actual
-programs is just as important.
+In "project" chapters, I'll stop pummeling you with new theory for a brief moment, and instead we'll work through a program together. Theory is necessary to learn to program, but reading and understanding actual programs is just as important.
-Our project in this chapter is to build an ((automaton)), a little
-program that performs a task in a ((virtual world)). Our automaton
-will be a mail-delivery ((robot)) picking up and dropping off parcels.
+Our project in this chapter is to build an ((automaton)), a little program that performs a task in a ((virtual world)). Our automaton will be a mail-delivery ((robot)) picking up and dropping off parcels.
## Meadowfield
{{index "roads array"}}
-The village of ((Meadowfield)) isn't very big. It consists of 11
-places with 14 roads between them. It can be described with this
-array of roads:
+The village of ((Meadowfield)) isn't very big. It consists of 11 places with 14 roads between them. It can be described with this array of roads:
```{includeCode: true}
const roads = [
@@ -46,16 +38,11 @@ const roads = [
{{figure {url: "img/village2x.png", alt: "The village of Meadowfield"}}}
-The network of roads in the village forms a _((graph))_. A graph is a
-collection of points (places in the village) with lines between them
-(roads). This graph will be the world that our robot moves through.
+The network of roads in the village forms a _((graph))_. A graph is a collection of points (places in the village) with lines between them (roads). This graph will be the world that our robot moves through.
{{index "roadGraph object"}}
-The array of strings isn't very easy to work with. What we're
-interested in is the destinations that we can reach from a given
-place. Let's convert the list of roads to a data structure that, for
-each place, tells us what can be reached from there.
+The array of strings isn't very easy to work with. What we're interested in is the destinations that we can reach from a given place. Let's convert the list of roads to a data structure that, for each place, tells us what can be reached from there.
```{includeCode: true}
function buildGraph(edges) {
@@ -77,62 +64,37 @@ function buildGraph(edges) {
const roadGraph = buildGraph(roads);
```
-Given an array of edges, `buildGraph` creates a map object that, for
-each node, stores an array of connected nodes.
+Given an array of edges, `buildGraph` creates a map object that, for each node, stores an array of connected nodes.
{{index "split method"}}
-It uses the `split` method to go from the road strings, which have the
-form `"Start-End"`, to two-element arrays containing the start and end
-as separate strings.
+It uses the `split` method to go from the road strings, which have the form `"Start-End"`, to two-element arrays containing the start and end as separate strings.
## The task
-Our ((robot)) will be moving around the village. There are parcels
-in various places, each addressed to some other place. The robot picks
-up parcels when it comes to them and delivers them when it arrives at
-their destinations.
+Our ((robot)) will be moving around the village. There are parcels in various places, each addressed to some other place. The robot picks up parcels when it comes to them and delivers them when it arrives at their destinations.
-The automaton must decide, at each point, where to go next. It has
-finished its task when all parcels have been delivered.
+The automaton must decide, at each point, where to go next. It has finished its task when all parcels have been delivered.
{{index simulation, "virtual world"}}
-To be able to simulate this process, we must define a virtual world
-that can describe it. This model tells us where the robot is and where
-the parcels are. When the robot has decided to move somewhere, we need
-to update the model to reflect the new situation.
+To be able to simulate this process, we must define a virtual world that can describe it. This model tells us where the robot is and where the parcels are. When the robot has decided to move somewhere, we need to update the model to reflect the new situation.
{{index [state, in objects]}}
-If you're thinking in terms of ((object-oriented programming)), your
-first impulse might be to start defining objects for the various
-elements in the world: a ((class)) for the robot, one for a parcel,
-maybe one for places. These could then hold properties that describe
-their current ((state)), such as the pile of parcels at a location,
-which we could change when updating the world.
+If you're thinking in terms of ((object-oriented programming)), your first impulse might be to start defining objects for the various elements in the world: a ((class)) for the robot, one for a parcel, maybe one for places. These could then hold properties that describe their current ((state)), such as the pile of parcels at a location, which we could change when updating the world.
This is wrong.
-At least, it usually is. The fact that something sounds like an object
-does not automatically mean that it should be an object in your
-program. Reflexively writing classes for every concept in your
-application tends to leave you with a collection of interconnected
-objects that each have their own internal, changing state. Such
-programs are often hard to understand and thus easy to break.
+At least, it usually is. The fact that something sounds like an object does not automatically mean that it should be an object in your program. Reflexively writing classes for every concept in your application tends to leave you with a collection of interconnected objects that each have their own internal, changing state. Such programs are often hard to understand and thus easy to break.
{{index [state, in objects]}}
-Instead, let's condense the village's state down to the minimal
-set of values that define it. There's the robot's current location and
-the collection of undelivered parcels, each of which has a current
-location and a destination address. That's it.
+Instead, let's condense the village's state down to the minimal set of values that define it. There's the robot's current location and the collection of undelivered parcels, each of which has a current location and a destination address. That's it.
{{index "VillageState class", "persistent data structure"}}
-And while we're at it, let's make it so that we don't _change_ this
-state when the robot moves but rather compute a _new_ state for the
-situation after the move.
+And while we're at it, let's make it so that we don't _change_ this state when the robot moves but rather compute a _new_ state for the situation after the move.
```{includeCode: true}
class VillageState {
@@ -155,23 +117,13 @@ class VillageState {
}
```
-The `move` method is where the action happens. It first checks whether
-there is a road going from the current place to the destination, and
-if not, it returns the old state since this is not a valid move.
+The `move` method is where the action happens. It first checks whether there is a road going from the current place to the destination, and if not, it returns the old state since this is not a valid move.
{{index "map method", "filter method"}}
-Then it creates a new state with the destination as the robot's new
-place. But it also needs to create a new set of parcels—parcels that
-the robot is carrying (that are at the robot's current place) need to
-be moved along to the new place. And parcels that are addressed to the
-new place need to be delivered—that is, they need to be removed from
-the set of undelivered parcels. The call to `map` takes care of the
-moving, and the call to `filter` does the delivering.
+Then it creates a new state with the destination as the robot's new place. But it also needs to create a new set of parcels—parcels that the robot is carrying (that are at the robot's current place) need to be moved along to the new place. And parcels that are addressed to the new place need to be delivered—that is, they need to be removed from the set of undelivered parcels. The call to `map` takes care of the moving, and the call to `filter` does the delivering.
-Parcel objects aren't changed when they are moved but re-created. The
-`move` method gives us a new village state but leaves the old one
-entirely intact.
+Parcel objects aren't changed when they are moved but re-created. The `move` method gives us a new village state but leaves the old one entirely intact.
```
let first = new VillageState(
@@ -188,28 +140,15 @@ console.log(first.place);
// → Post Office
```
-The move causes the parcel to be delivered, and this is reflected in
-the next state. But the initial state still describes the situation
-where the robot is at the post office and the parcel is undelivered.
+The move causes the parcel to be delivered, and this is reflected in the next state. But the initial state still describes the situation where the robot is at the post office and the parcel is undelivered.
## Persistent data
{{index "persistent data structure", mutability, ["data structure", immutable]}}
-Data structures that don't change are called _((immutable))_ or
-_persistent_. They behave a lot like strings and numbers in that they
-are who they are and stay that way, rather than containing different
-things at different times.
-
-In JavaScript, just about everything _can_ be changed, so working with
-values that are supposed to be persistent requires some restraint.
-There is a function called `Object.freeze` that changes an object so
-that writing to its properties is ignored. You could use that to make
-sure your objects aren't changed, if you want to be careful. Freezing
-does require the computer to do some extra work, and having updates
-ignored is just about as likely to confuse someone as having them do
-the wrong thing. So I usually prefer to just tell people that a given
-object shouldn't be messed with and hope they remember it.
+Data structures that don't change are called _((immutable))_ or _persistent_. They behave a lot like strings and numbers in that they are who they are and stay that way, rather than containing different things at different times.
+
+In JavaScript, just about everything _can_ be changed, so working with values that are supposed to be persistent requires some restraint. There is a function called `Object.freeze` that changes an object so that writing to its properties is ignored. You could use that to make sure your objects aren't changed, if you want to be careful. Freezing does require the computer to do some extra work, and having updates ignored is just about as likely to confuse someone as having them do the wrong thing. So I usually prefer to just tell people that a given object shouldn't be messed with and hope they remember it.
```
let object = Object.freeze({value: 5});
@@ -218,44 +157,23 @@ console.log(object.value);
// → 5
```
-Why am I going out of my way to not change objects when the language
-is obviously expecting me to?
+Why am I going out of my way to not change objects when the language is obviously expecting me to?
-Because it helps me understand my programs. This is about complexity
-management again. When the objects in my system are fixed, stable
-things, I can consider operations on them in isolation—moving to
-Alice's house from a given start state always produces the same new
-state. When objects change over time, that adds a whole new dimension
-of complexity to this kind of reasoning.
+Because it helps me understand my programs. This is about complexity management again. When the objects in my system are fixed, stable things, I can consider operations on them in isolation—moving to Alice's house from a given start state always produces the same new state. When objects change over time, that adds a whole new dimension of complexity to this kind of reasoning.
-For a small system like the one we are building in this chapter, we
-could handle that bit of extra complexity. But the most important
-limit on what kind of systems we can build is how much we can
-understand. Anything that makes your code easier to understand makes
-it possible to build a more ambitious system.
+For a small system like the one we are building in this chapter, we could handle that bit of extra complexity. But the most important limit on what kind of systems we can build is how much we can understand. Anything that makes your code easier to understand makes it possible to build a more ambitious system.
-Unfortunately, although understanding a system built on persistent data
-structures is easier, _designing_ one, especially when your
-programming language isn't helping, can be a little harder. We'll
-look for opportunities to use persistent data structures in this
-book, but we'll also be using changeable ones.
+Unfortunately, although understanding a system built on persistent data structures is easier, _designing_ one, especially when your programming language isn't helping, can be a little harder. We'll look for opportunities to use persistent data structures in this book, but we'll also be using changeable ones.
## Simulation
{{index simulation, "virtual world"}}
-A delivery ((robot)) looks at the world and decides in which
-direction it wants to move. As such, we could say that a robot is a
-function that takes a `VillageState` object and returns the name of a
-nearby place.
+A delivery ((robot)) looks at the world and decides in which direction it wants to move. As such, we could say that a robot is a function that takes a `VillageState` object and returns the name of a nearby place.
{{index "runRobot function"}}
-Because we want robots to be able to remember things, so that they can
-make and execute plans, we also pass them their memory and allow them
-to return a new memory. Thus, the thing a robot returns is an object
-containing both the direction it wants to move in and a memory value
-that will be given back to it the next time it is called.
+Because we want robots to be able to remember things, so that they can make and execute plans, we also pass them their memory and allow them to return a new memory. Thus, the thing a robot returns is an object containing both the direction it wants to move in and a memory value that will be given back to it the next time it is called.
```{includeCode: true}
function runRobot(state, robot, memory) {
@@ -272,15 +190,9 @@ function runRobot(state, robot, memory) {
}
```
-Consider what a robot has to do to "solve" a given state. It must pick
-up all parcels by visiting every location that has a parcel and
-deliver them by visiting every location that a parcel is addressed to,
-but only after picking up the parcel.
+Consider what a robot has to do to "solve" a given state. It must pick up all parcels by visiting every location that has a parcel and deliver them by visiting every location that a parcel is addressed to, but only after picking up the parcel.
-What is the dumbest strategy that could possibly work? The robot could
-just walk in a random direction every turn. That means, with
-great likelihood, it will eventually run into all parcels and then
-also at some point reach the place where they should be delivered.
+What is the dumbest strategy that could possibly work? The robot could just walk in a random direction every turn. That means, with great likelihood, it will eventually run into all parcels and then also at some point reach the place where they should be delivered.
{{index "randomPick function", "randomRobot function"}}
@@ -299,20 +211,11 @@ function randomRobot(state) {
{{index "Math.random function", "Math.floor function", [array, "random element"]}}
-Remember that `Math.random()` returns a number between zero and
-one—but always below one. Multiplying such a number by the length of an
-array and then applying `Math.floor` to it gives us a random index for
-the array.
+Remember that `Math.random()` returns a number between zero and one—but always below one. Multiplying such a number by the length of an array and then applying `Math.floor` to it gives us a random index for the array.
-Since this robot does not need to remember anything, it ignores its
-second argument (remember that JavaScript functions can be called with
-extra arguments without ill effects) and omits the `memory` property
-in its returned object.
+Since this robot does not need to remember anything, it ignores its second argument (remember that JavaScript functions can be called with extra arguments without ill effects) and omits the `memory` property in its returned object.
-To put this sophisticated robot to work, we'll first need a way to
-create a new state with some parcels. A static method (written here by
-directly adding a property to the constructor) is a good place to put
-that functionality.
+To put this sophisticated robot to work, we'll first need a way to create a new state with some parcels. A static method (written here by directly adding a property to the constructor) is a good place to put that functionality.
```{includeCode: true}
VillageState.random = function(parcelCount = 5) {
@@ -331,9 +234,7 @@ VillageState.random = function(parcelCount = 5) {
{{index "do loop"}}
-We don't want any parcels that are sent from the same place that they
-are addressed to. For this reason, the `do` loop keeps picking new
-places when it gets one that's equal to the address.
+We don't want any parcels that are sent from the same place that they are addressed to. For this reason, the `do` loop keeps picking new places when it gets one that's equal to the address.
Let's start up a virtual world.
@@ -345,25 +246,17 @@ runRobot(VillageState.random(), randomRobot);
// → Done in 63 turns
```
-It takes the robot a lot of turns to deliver the parcels because it
-isn't planning ahead very well. We'll address that soon.
+It takes the robot a lot of turns to deliver the parcels because it isn't planning ahead very well. We'll address that soon.
{{if interactive
-For a more pleasant perspective on the simulation, you can use the
-`runRobotAnimation` function that's available in [this chapter's
-programming environment](https://eloquentjavascript.net/code/#7).
-This runs the simulation, but instead of outputting text, it shows
-you the robot moving around the village map.
+For a more pleasant perspective on the simulation, you can use the `runRobotAnimation` function that's available in [this chapter's programming environment](https://eloquentjavascript.net/code/#7). This runs the simulation, but instead of outputting text, it shows you the robot moving around the village map.
```{test: no}
runRobotAnimation(VillageState.random(), randomRobot);
```
-The way `runRobotAnimation` is implemented will remain a mystery for
-now, but after you've read the [later chapters](dom) of this book,
-which discuss JavaScript integration in web browsers, you'll be able
-to guess how it works.
+The way `runRobotAnimation` is implemented will remain a mystery for now, but after you've read the [later chapters](dom) of this book, which discuss JavaScript integration in web browsers, you'll be able to guess how it works.
if}}
@@ -371,12 +264,7 @@ if}}
{{index "mailRoute array"}}
-We should be able to do a lot better than the random ((robot)). An
-easy improvement would be to take a hint from the way real-world mail
-delivery works. If we find a route that passes all places in the
-village, the robot could run that route twice, at which point it is
-guaranteed to be done. Here is one such route (starting from the post
-office):
+We should be able to do a lot better than the random ((robot)). An easy improvement would be to take a hint from the way real-world mail delivery works. If we find a route that passes all places in the village, the robot could run that route twice, at which point it is guaranteed to be done. Here is one such route (starting from the post office):
```{includeCode: true}
const mailRoute = [
@@ -389,9 +277,7 @@ const mailRoute = [
{{index "routeRobot function"}}
-To implement the route-following robot, we'll need to make use of
-robot memory. The robot keeps the rest of its route in its memory and
-drops the first element every turn.
+To implement the route-following robot, we'll need to make use of robot memory. The robot keeps the rest of its route in its memory and drops the first element every turn.
```{includeCode: true}
function routeRobot(state, memory) {
@@ -402,8 +288,7 @@ function routeRobot(state, memory) {
}
```
-This robot is a lot faster already. It'll take a maximum of 26 turns
-(twice the 13-step route) but usually less.
+This robot is a lot faster already. It'll take a maximum of 26 turns (twice the 13-step route) but usually less.
{{if interactive
@@ -415,37 +300,17 @@ if}}
## Pathfinding
-Still, I wouldn't really call blindly following a fixed route
-intelligent behavior. The ((robot)) could work more efficiently if it
-adjusted its behavior to the actual work that needs to be done.
+Still, I wouldn't really call blindly following a fixed route intelligent behavior. The ((robot)) could work more efficiently if it adjusted its behavior to the actual work that needs to be done.
{{index pathfinding}}
-To do that, it has to be able to deliberately move toward a given
-parcel or toward the location where a parcel has to be delivered.
-Doing that, even when the goal is more than one move away, will
-require some kind of route-finding function.
-
-The problem of finding a route through a ((graph)) is a typical
-_((search problem))_. We can tell whether a given solution (a route)
-is a valid solution, but we can't directly compute the solution the
-way we could for 2 + 2. Instead, we have to keep creating potential
-solutions until we find one that works.
-
-The number of possible routes through a graph is infinite. But
-when searching for a route from _A_ to _B_, we are interested only in
-the ones that start at _A_. We also don't care about routes that visit
-the same place twice—those are definitely not the most efficient route
-anywhere. So that cuts down on the number of routes that the route
-finder has to consider.
-
-In fact, we are mostly interested in the _shortest_ route. So we want
-to make sure we look at short routes before we look at longer ones. A
-good approach would be to "grow" routes from the starting point,
-exploring every reachable place that hasn't been visited yet, until a
-route reaches the goal. That way, we'll only explore routes that are
-potentially interesting, and we'll find the shortest route (or one of the
-shortest routes, if there are more than one) to the goal.
+To do that, it has to be able to deliberately move toward a given parcel or toward the location where a parcel has to be delivered. Doing that, even when the goal is more than one move away, will require some kind of route-finding function.
+
+The problem of finding a route through a ((graph)) is a typical _((search problem))_. We can tell whether a given solution (a route) is a valid solution, but we can't directly compute the solution the way we could for 2 + 2. Instead, we have to keep creating potential solutions until we find one that works.
+
+The number of possible routes through a graph is infinite. But when searching for a route from _A_ to _B_, we are interested only in the ones that start at _A_. We also don't care about routes that visit the same place twice—those are definitely not the most efficient route anywhere. So that cuts down on the number of routes that the route finder has to consider.
+
+In fact, we are mostly interested in the _shortest_ route. So we want to make sure we look at short routes before we look at longer ones. A good approach would be to "grow" routes from the starting point, exploring every reachable place that hasn't been visited yet, until a route reaches the goal. That way, we'll only explore routes that are potentially interesting, and we'll find the shortest route (or one of the shortest routes, if there are more than one) to the goal.
{{index "findRoute function"}}
@@ -468,39 +333,17 @@ function findRoute(graph, from, to) {
}
```
-The exploring has to be done in the right order—the places that were
-reached first have to be explored first. We can't immediately explore
-a place as soon as we reach it because that would mean places reached
-_from there_ would also be explored immediately, and so on, even
-though there may be other, shorter paths that haven't yet been
-explored.
-
-Therefore, the function keeps a _((work list))_. This is an array of
-places that should be explored next, along with the route that got us
-there. It starts with just the start position and an empty route.
-
-The search then operates by taking the next item in the list and
-exploring that, which means all roads going from that place are
-looked at. If one of them is the goal, a finished route can be
-returned. Otherwise, if we haven't looked at this place before, a new
-item is added to the list. If we have looked at it before, since we
-are looking at short routes first, we've found either a longer route
-to that place or one precisely as long as the existing one, and we
-don't need to explore it.
-
-You can visually imagine this as a web of known routes crawling out
-from the start location, growing evenly on all sides (but never
-tangling back into itself). As soon as the first thread reaches the
-goal location, that thread is traced back to the start, giving us our
-route.
+The exploring has to be done in the right order—the places that were reached first have to be explored first. We can't immediately explore a place as soon as we reach it because that would mean places reached _from there_ would also be explored immediately, and so on, even though there may be other, shorter paths that haven't yet been explored.
+
+Therefore, the function keeps a _((work list))_. This is an array of places that should be explored next, along with the route that got us there. It starts with just the start position and an empty route.
+
+The search then operates by taking the next item in the list and exploring that, which means all roads going from that place are looked at. If one of them is the goal, a finished route can be returned. Otherwise, if we haven't looked at this place before, a new item is added to the list. If we have looked at it before, since we are looking at short routes first, we've found either a longer route to that place or one precisely as long as the existing one, and we don't need to explore it.
+
+You can visually imagine this as a web of known routes crawling out from the start location, growing evenly on all sides (but never tangling back into itself). As soon as the first thread reaches the goal location, that thread is traced back to the start, giving us our route.
{{index "connected graph"}}
-Our code doesn't handle the situation where there are no more work
-items on the work list because we know that our graph is _connected_,
-meaning that every location can be reached from all other locations.
-We'll always be able to find a route between two points, and the
-search can't fail.
+Our code doesn't handle the situation where there are no more work items on the work list because we know that our graph is _connected_, meaning that every location can be reached from all other locations. We'll always be able to find a route between two points, and the search can't fail.
```{includeCode: true}
function goalOrientedRobot({place, parcels}, route) {
@@ -518,12 +361,7 @@ function goalOrientedRobot({place, parcels}, route) {
{{index "goalOrientedRobot function"}}
-This robot uses its memory value as a list of directions to move in,
-just like the route-following robot. Whenever that list is empty, it
-has to figure out what to do next. It takes the first undelivered
-parcel in the set and, if that parcel hasn't been picked up yet, plots a
-route toward it. If the parcel _has_ been picked up, it still needs to be
-delivered, so the robot creates a route toward the delivery address instead.
+This robot uses its memory value as a list of directions to move in, just like the route-following robot. Whenever that list is empty, it has to figure out what to do next. It takes the first undelivered parcel in the set and, if that parcel hasn't been picked up yet, plots a route toward it. If the parcel _has_ been picked up, it still needs to be delivered, so the robot creates a route toward the delivery address instead.
{{if interactive
@@ -536,8 +374,7 @@ runRobotAnimation(VillageState.random(),
if}}
-This robot usually finishes the task of delivering 5 parcels in about
-16 turns. That's slightly better than `routeRobot` but still definitely not optimal.
+This robot usually finishes the task of delivering 5 parcels in about 16 turns. That's slightly better than `routeRobot` but still definitely not optimal.
## Exercises
@@ -545,17 +382,11 @@ This robot usually finishes the task of delivering 5 parcels in about
{{index "measuring a robot (exercise)", testing, automation, "compareRobots function"}}
-It's hard to objectively compare ((robot))s by just letting them solve
-a few scenarios. Maybe one robot just happened to get easier tasks or
-the kind of tasks that it is good at, whereas the other didn't.
+It's hard to objectively compare ((robot))s by just letting them solve a few scenarios. Maybe one robot just happened to get easier tasks or the kind of tasks that it is good at, whereas the other didn't.
-Write a function `compareRobots` that takes two robots (and their
-starting memory). It should generate 100 tasks and let each of
-the robots solve each of these tasks. When done, it should output the
-average number of steps each robot took per task.
+Write a function `compareRobots` that takes two robots (and their starting memory). It should generate 100 tasks and let each of the robots solve each of these tasks. When done, it should output the average number of steps each robot took per task.
-For the sake of fairness, make sure you give each task to both
-robots, rather than generating different tasks per robot.
+For the sake of fairness, make sure you give each task to both robots, rather than generating different tasks per robot.
{{if interactive
@@ -572,15 +403,9 @@ if}}
{{index "measuring a robot (exercise)", "runRobot function"}}
-You'll have to write a variant of the `runRobot` function that,
-instead of logging the events to the console, returns the number of
-steps the robot took to complete the task.
+You'll have to write a variant of the `runRobot` function that, instead of logging the events to the console, returns the number of steps the robot took to complete the task.
-Your measurement function can then, in a loop, generate new states and
-count the steps each of the robots takes. When it has generated enough
-measurements, it can use `console.log` to output the average for each
-robot, which is the total number of steps taken divided by the number
-of measurements.
+Your measurement function can then, in a loop, generate new states and count the steps each of the robots takes. When it has generated enough measurements, it can use `console.log` to output the average for each robot, which is the total number of steps taken divided by the number of measurements.
hint}}
@@ -588,12 +413,9 @@ hint}}
{{index "robot efficiency (exercise)"}}
-Can you write a robot that finishes the delivery task faster than
-`goalOrientedRobot`? If you observe that robot's behavior, what
-obviously stupid things does it do? How could those be improved?
+Can you write a robot that finishes the delivery task faster than `goalOrientedRobot`? If you observe that robot's behavior, what obviously stupid things does it do? How could those be improved?
-If you solved the previous exercise, you might want to use your
-`compareRobots` function to verify whether you improved the robot.
+If you solved the previous exercise, you might want to use your `compareRobots` function to verify whether you improved the robot.
{{if interactive
@@ -609,15 +431,9 @@ if}}
{{index "robot efficiency (exercise)"}}
-The main limitation of `goalOrientedRobot` is that it considers only
-one parcel at a time. It will often walk back and forth across the
-village because the parcel it happens to be looking at happens to be
-at the other side of the map, even if there are others much closer.
+The main limitation of `goalOrientedRobot` is that it considers only one parcel at a time. It will often walk back and forth across the village because the parcel it happens to be looking at happens to be at the other side of the map, even if there are others much closer.
-One possible solution would be to compute routes for all packages and
-then take the shortest one. Even better results can be obtained, if
-there are multiple shortest routes, by preferring the ones that go to
-pick up a package instead of delivering a package.
+One possible solution would be to compute routes for all packages and then take the shortest one. Even better results can be obtained, if there are multiple shortest routes, by preferring the ones that go to pick up a package instead of delivering a package.
hint}}
@@ -625,35 +441,21 @@ hint}}
{{index "persistent group (exercise)", "persistent data structure", "Set class", "set (data structure)", "Group class", "PGroup class"}}
-Most data structures provided in a standard JavaScript environment
-aren't very well suited for persistent use. Arrays have `slice` and
-`concat` methods, which allow us to easily create new arrays without
-damaging the old one. But `Set`, for example, has no methods for
-creating a new set with an item added or removed.
+Most data structures provided in a standard JavaScript environment aren't very well suited for persistent use. Arrays have `slice` and `concat` methods, which allow us to easily create new arrays without damaging the old one. But `Set`, for example, has no methods for creating a new set with an item added or removed.
-Write a new class `PGroup`, similar to the `Group` class from [Chapter
-?](object#groups), which stores a set of values. Like `Group`, it has
-`add`, `delete`, and `has` methods.
+Write a new class `PGroup`, similar to the `Group` class from [Chapter ?](object#groups), which stores a set of values. Like `Group`, it has `add`, `delete`, and `has` methods.
-Its `add` method, however, should return a _new_ `PGroup` instance
-with the given member added and leave the old one unchanged.
-Similarly, `delete` creates a new instance without a given member.
+Its `add` method, however, should return a _new_ `PGroup` instance with the given member added and leave the old one unchanged. Similarly, `delete` creates a new instance without a given member.
-The class should work for values of any type, not just strings. It
-does _not_ have to be efficient when used with large amounts of
-values.
+The class should work for values of any type, not just strings. It does _not_ have to be efficient when used with large amounts of values.
{{index [interface, object]}}
-The ((constructor)) shouldn't be part of the class's interface
-(though you'll definitely want to use it internally). Instead, there
-is an empty instance, `PGroup.empty`, that can be used as a starting
-value.
+The ((constructor)) shouldn't be part of the class's interface (though you'll definitely want to use it internally). Instead, there is an empty instance, `PGroup.empty`, that can be used as a starting value.
{{index singleton}}
-Why do you need only one `PGroup.empty` value, rather than having a
-function that creates a new, empty map every time?
+Why do you need only one `PGroup.empty` value, rather than having a function that creates a new, empty map every time?
{{if interactive
@@ -680,27 +482,18 @@ if}}
{{index "persistent map (exercise)", "Set class", [array, creation], "PGroup class"}}
-The most convenient way to represent the set of member values
-is still as an array since arrays are easy to copy.
+The most convenient way to represent the set of member values is still as an array since arrays are easy to copy.
{{index "concat method", "filter method"}}
-When a value is added to the group, you can create a new group with a
-copy of the original array that has the value added (for example, using
-`concat`). When a value is deleted, you filter it from the array.
+When a value is added to the group, you can create a new group with a copy of the original array that has the value added (for example, using `concat`). When a value is deleted, you filter it from the array.
-The class's ((constructor)) can take such an array as argument and
-store it as the instance's (only) property. This array is never
-updated.
+The class's ((constructor)) can take such an array as argument and store it as the instance's (only) property. This array is never updated.
{{index "static method"}}
-To add a property (`empty`) to a constructor that is not a method, you
-have to add it to the constructor after the class definition, as a
-regular property.
+To add a property (`empty`) to a constructor that is not a method, you have to add it to the constructor after the class definition, as a regular property.
-You need only one `empty` instance because all empty groups are the
-same and instances of the class don't change. You can create many
-different groups from that single empty group without affecting it.
+You need only one `empty` instance because all empty groups are the same and instances of the class don't change. You can create many different groups from that single empty group without affecting it.
hint}}
diff --git a/08_error.md b/08_error.md
index 6a591ca9f..0c438a935 100644
--- a/08_error.md
+++ b/08_error.md
@@ -4,9 +4,7 @@
{{quote {author: "Brian Kernighan and P.J. Plauger", title: "The Elements of Programming Style", chapter: true}
-Debugging is twice as hard as writing the code in the first place.
-Therefore, if you write the code as cleverly as possible, you are, by
-definition, not smart enough to debug it.
+Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
quote}}
@@ -14,49 +12,25 @@ quote}}
{{index "Kernighan, Brian", "Plauger, P.J.", debugging, "error handling"}}
-Flaws in computer programs are usually called _((bug))s_. It makes
-programmers feel good to imagine them as little things that just
-happen to crawl into our work. In reality, of course, we put them
-there ourselves.
+Flaws in computer programs are usually called _((bug))s_. It makes programmers feel good to imagine them as little things that just happen to crawl into our work. In reality, of course, we put them there ourselves.
-If a program is crystallized thought, you can roughly categorize bugs
-into those caused by the thoughts being confused and those caused by
-mistakes introduced while converting a thought to code. The former
-type is generally harder to diagnose and fix than the latter.
+If a program is crystallized thought, you can roughly categorize bugs into those caused by the thoughts being confused and those caused by mistakes introduced while converting a thought to code. The former type is generally harder to diagnose and fix than the latter.
## Language
{{index parsing, analysis}}
-Many mistakes could be pointed out to us automatically by the
-computer, if it knew enough about what we're trying to do. But here
-JavaScript's looseness is a hindrance. Its concept of bindings and
-properties is vague enough that it will rarely catch ((typo))s before
-actually running the program. And even then, it allows you to do some
-clearly nonsensical things without complaint, such as computing
-`true * "monkey"`.
+Many mistakes could be pointed out to us automatically by the computer, if it knew enough about what we're trying to do. But here JavaScript's looseness is a hindrance. Its concept of bindings and properties is vague enough that it will rarely catch ((typo))s before actually running the program. And even then, it allows you to do some clearly nonsensical things without complaint, such as computing `true * "monkey"`.
{{index [syntax, error], [property, access]}}
-There are some things that JavaScript does complain about. Writing a
-program that does not follow the language's ((grammar)) will
-immediately make the computer complain. Other things, such as calling
-something that's not a function or looking up a property on an
-((undefined)) value, will cause an error to be reported when the
-program tries to perform the action.
+There are some things that JavaScript does complain about. Writing a program that does not follow the language's ((grammar)) will immediately make the computer complain. Other things, such as calling something that's not a function or looking up a property on an ((undefined)) value, will cause an error to be reported when the program tries to perform the action.
{{index NaN, error}}
-But often, your nonsense computation will merely produce `NaN` (not a
-number) or an undefined value, while the program happily continues,
-convinced that it's doing something meaningful. The mistake will
-manifest itself only later, after the bogus value has traveled through
-several functions. It might not trigger an error at all but silently
-cause the program's output to be wrong. Finding the source of such
-problems can be difficult.
+But often, your nonsense computation will merely produce `NaN` (not a number) or an undefined value, while the program happily continues, convinced that it's doing something meaningful. The mistake will manifest itself only later, after the bogus value has traveled through several functions. It might not trigger an error at all but silently cause the program's output to be wrong. Finding the source of such problems can be difficult.
-The process of finding mistakes—bugs—in programs is called
-_((debugging))_.
+The process of finding mistakes—bugs—in programs is called _((debugging))_.
## Strict mode
@@ -64,9 +38,7 @@ _((debugging))_.
{{indexsee "use strict", "strict mode"}}
-JavaScript can be made a _little_ stricter by enabling _strict
-mode_. This is done by putting the string `"use strict"` at the top of
-a file or a function body. Here's an example:
+JavaScript can be made a _little_ stricter by enabling _strict mode_. This is done by putting the string `"use strict"` at the top of a file or a function body. Here's an example:
```{test: "error \"ReferenceError: counter is not defined\""}
function canYouSpotTheProblem() {
@@ -82,28 +54,13 @@ canYouSpotTheProblem();
{{index "let keyword", [binding, global]}}
-Normally, when you forget to put `let` in front of your binding, as
-with `counter` in the example, JavaScript quietly creates a global
-binding and uses that. In strict mode, an ((error)) is reported
-instead. This is very helpful. It should be noted, though, that this
-doesn't work when the binding in question already exists as a global
-binding. In that case, the loop will still quietly overwrite the value
-of the binding.
+Normally, when you forget to put `let` in front of your binding, as with `counter` in the example, JavaScript quietly creates a global binding and uses that. In strict mode, an ((error)) is reported instead. This is very helpful. It should be noted, though, that this doesn't work when the binding in question already exists as a global binding. In that case, the loop will still quietly overwrite the value of the binding.
{{index "this binding", "global object", undefined, "strict mode"}}
-Another change in strict mode is that the `this` binding holds the
-value `undefined` in functions that are not called as ((method))s.
-When making such a call outside of strict mode, `this` refers to the
-global scope object, which is an object whose properties are the
-global bindings. So if you accidentally call a method or constructor
-incorrectly in strict mode, JavaScript will produce an error as soon
-as it tries to read something from `this`, rather than happily writing
-to the global scope.
+Another change in strict mode is that the `this` binding holds the value `undefined` in functions that are not called as ((method))s. When making such a call outside of strict mode, `this` refers to the global scope object, which is an object whose properties are the global bindings. So if you accidentally call a method or constructor incorrectly in strict mode, JavaScript will produce an error as soon as it tries to read something from `this`, rather than happily writing to the global scope.
-For example, consider the following code, which calls a
-((constructor)) function without the `new` keyword so that its `this`
-will _not_ refer to a newly constructed object:
+For example, consider the following code, which calls a ((constructor)) function without the `new` keyword so that its `this` will _not_ refer to a newly constructed object:
```
function Person(name) { this.name = name; }
@@ -114,9 +71,7 @@ console.log(name);
{{index error}}
-So the bogus call to `Person` succeeded but returned an undefined
-value and created the global binding `name`. In strict mode, the
-result is different.
+So the bogus call to `Person` succeeded but returned an undefined value and created the global binding `name`. In strict mode, the result is different.
```{test: "error \"TypeError: Cannot set property 'name' of undefined\""}
"use strict";
@@ -127,38 +82,23 @@ let ferdinand = Person("Ferdinand"); // forgot new
We are immediately told that something is wrong. This is helpful.
-Fortunately, constructors created with the `class` notation will
-always complain if they are called without `new`, making this less of
-a problem even in non-strict mode.
+Fortunately, constructors created with the `class` notation will always complain if they are called without `new`, making this less of a problem even in non-strict mode.
{{index parameter, [binding, naming], "with statement"}}
-Strict mode does a few more things. It disallows giving a function
-multiple parameters with the same name and removes certain problematic
-language features entirely (such as the `with` statement, which is so
-wrong it is not further discussed in this book).
+Strict mode does a few more things. It disallows giving a function multiple parameters with the same name and removes certain problematic language features entirely (such as the `with` statement, which is so wrong it is not further discussed in this book).
{{index debugging}}
-In short, putting `"use strict"` at the top of your program rarely
-hurts and might help you spot a problem.
+In short, putting `"use strict"` at the top of your program rarely hurts and might help you spot a problem.
## Types
-Some languages want to know the types of all your bindings and
-expressions before even running a program. They will tell you right
-away when a type is used in an inconsistent way. JavaScript considers
-types only when actually running the program, and even there often
-tries to implicitly convert values to the type it expects, so it's not
-much help.
+Some languages want to know the types of all your bindings and expressions before even running a program. They will tell you right away when a type is used in an inconsistent way. JavaScript considers types only when actually running the program, and even there often tries to implicitly convert values to the type it expects, so it's not much help.
-Still, types provide a useful framework for talking about programs. A
-lot of mistakes come from being confused about the kind of value that
-goes into or comes out of a function. If you have that information
-written down, you're less likely to get confused.
+Still, types provide a useful framework for talking about programs. A lot of mistakes come from being confused about the kind of value that goes into or comes out of a function. If you have that information written down, you're less likely to get confused.
-You could add a comment like the following before the `goalOrientedRobot`
-function from the previous chapter to describe its type:
+You could add a comment like the following before the `goalOrientedRobot` function from the previous chapter to describe its type:
```
// (VillageState, Array) → {direction: string, memory: Array}
@@ -167,58 +107,31 @@ function goalOrientedRobot(state, memory) {
}
```
-There are a number of different conventions for annotating JavaScript
-programs with types.
+There are a number of different conventions for annotating JavaScript programs with types.
-One thing about types is that they need to introduce their own
-complexity to be able to describe enough code to be useful. What do
-you think would be the type of the `randomPick` function that returns
-a random element from an array? You'd need to introduce a _((type
-variable))_, _T_, which can stand in for any type, so that you can
-give `randomPick` a type like `([T]) → T` (function from an array of
-*T*s to a *T*).
+One thing about types is that they need to introduce their own complexity to be able to describe enough code to be useful. What do you think would be the type of the `randomPick` function that returns a random element from an array? You'd need to introduce a _((type variable))_, _T_, which can stand in for any type, so that you can give `randomPick` a type like `([T]) → T` (function from an array of *T*s to a *T*).
{{index "type checking", TypeScript}}
{{id typing}}
-When the types of a program are known, it is possible for the computer
-to _check_ them for you, pointing out mistakes before the program is
-run. There are several JavaScript dialects that add types to the
-language and check them. The most popular one is called
-[TypeScript](https://www.typescriptlang.org/). If you are interested
-in adding more rigor to your programs, I recommend you give it a try.
+When the types of a program are known, it is possible for the computer to _check_ them for you, pointing out mistakes before the program is run. There are several JavaScript dialects that add types to the language and check them. The most popular one is called [TypeScript](https://www.typescriptlang.org/). If you are interested in adding more rigor to your programs, I recommend you give it a try.
-In this book, we'll continue using raw, dangerous, untyped JavaScript
-code.
+In this book, we'll continue using raw, dangerous, untyped JavaScript code.
## Testing
{{index "test suite", "run-time error", automation, testing}}
-If the language is not going to do much to help us find mistakes,
-we'll have to find them the hard way: by running the program and
-seeing whether it does the right thing.
+If the language is not going to do much to help us find mistakes, we'll have to find them the hard way: by running the program and seeing whether it does the right thing.
-Doing this by hand, again and again, is a really bad idea. Not only is
-it annoying, it also tends to be ineffective since it takes too much
-time to exhaustively test everything every time you make a change.
+Doing this by hand, again and again, is a really bad idea. Not only is it annoying, it also tends to be ineffective since it takes too much time to exhaustively test everything every time you make a change.
-Computers are good at repetitive tasks, and testing is the ideal
-repetitive task. Automated testing is the process of writing a program
-that tests another program. Writing tests is a bit more work than
-testing manually, but once you've done it, you gain a kind of
-superpower: it takes you only a few seconds to verify that your
-program still behaves properly in all the situations you wrote tests
-for. When you break something, you'll immediately notice, rather than
-randomly running into it at some later time.
+Computers are good at repetitive tasks, and testing is the ideal repetitive task. Automated testing is the process of writing a program that tests another program. Writing tests is a bit more work than testing manually, but once you've done it, you gain a kind of superpower: it takes you only a few seconds to verify that your program still behaves properly in all the situations you wrote tests for. When you break something, you'll immediately notice, rather than randomly running into it at some later time.
{{index "toUpperCase method"}}
-Tests usually take the form of little labeled programs that verify
-some aspect of your code. For example, a set of tests for the
-(standard, probably already tested by someone else) `toUpperCase`
-method might look like this:
+Tests usually take the form of little labeled programs that verify some aspect of your code. For example, a set of tests for the (standard, probably already tested by someone else) `toUpperCase` method might look like this:
```
function test(label, body) {
@@ -238,48 +151,27 @@ test("don't convert case-less characters", () => {
{{index "domain-specific language"}}
-Writing tests like this tends to produce rather repetitive, awkward
-code. Fortunately, there exist pieces of software that help you build
-and run collections of tests (_((test suites))_) by providing a
-language (in the form of functions and methods) suited to expressing
-tests and by outputting informative information when a test fails.
-These are usually called _((test runners))_.
+Writing tests like this tends to produce rather repetitive, awkward code. Fortunately, there exist pieces of software that help you build and run collections of tests (_((test suites))_) by providing a language (in the form of functions and methods) suited to expressing tests and by outputting informative information when a test fails. These are usually called _((test runners))_.
{{index "persistent data structure"}}
-Some code is easier to test than other code. Generally, the more
-external objects that the code interacts with, the harder it is to set
-up the context in which to test it. The style of programming shown in
-the [previous chapter](robot), which uses self-contained persistent
-values rather than changing objects, tends to be easy to test.
+Some code is easier to test than other code. Generally, the more external objects that the code interacts with, the harder it is to set up the context in which to test it. The style of programming shown in the [previous chapter](robot), which uses self-contained persistent values rather than changing objects, tends to be easy to test.
## Debugging
{{index debugging}}
-Once you notice there is something wrong with your program
-because it misbehaves or produces errors, the next step is to figure
-out _what_ the problem is.
+Once you notice there is something wrong with your program because it misbehaves or produces errors, the next step is to figure out _what_ the problem is.
-Sometimes it is obvious. The ((error)) message will point at a
-specific line of your program, and if you look at the error
-description and that line of code, you can often see the problem.
+Sometimes it is obvious. The ((error)) message will point at a specific line of your program, and if you look at the error description and that line of code, you can often see the problem.
{{index "run-time error"}}
-But not always. Sometimes the line that triggered the problem is
-simply the first place where a flaky value produced elsewhere gets
-used in an invalid way. If you have been solving the ((exercises)) in
-earlier chapters, you will probably have already experienced such
-situations.
+But not always. Sometimes the line that triggered the problem is simply the first place where a flaky value produced elsewhere gets used in an invalid way. If you have been solving the ((exercises)) in earlier chapters, you will probably have already experienced such situations.
{{index "decimal number", "binary number"}}
-The following example program tries to convert a whole number to a
-string in a given base (decimal, binary, and so on) by repeatedly
-picking out the last ((digit)) and then dividing the number to get rid
-of this digit. But the strange output that it currently produces
-suggests that it has a ((bug)).
+The following example program tries to convert a whole number to a string in a given base (decimal, binary, and so on) by repeatedly picking out the last ((digit)) and then dividing the number to get rid of this digit. But the strange output that it currently produces suggests that it has a ((bug)).
```
function numberToString(n, base = 10) {
@@ -300,25 +192,15 @@ console.log(numberToString(13, 10));
{{index analysis}}
-Even if you see the problem already, pretend for a moment that you
-don't. We know that our program is malfunctioning, and we want to find
-out why.
+Even if you see the problem already, pretend for a moment that you don't. We know that our program is malfunctioning, and we want to find out why.
{{index "trial and error"}}
-This is where you must resist the urge to start making random changes
-to the code to see whether that makes it better. Instead, _think_. Analyze
-what is happening and come up with a ((theory)) of why it might be
-happening. Then, make additional observations to test this theory—or,
-if you don't yet have a theory, make additional observations to help
-you come up with one.
+This is where you must resist the urge to start making random changes to the code to see whether that makes it better. Instead, _think_. Analyze what is happening and come up with a ((theory)) of why it might be happening. Then, make additional observations to test this theory—or, if you don't yet have a theory, make additional observations to help you come up with one.
{{index "console.log", output, debugging, logging}}
-Putting a few strategic `console.log` calls into the program is a good
-way to get additional information about what the program is doing. In
-this case, we want `n` to take the values `13`, `1`, and then `0`.
-Let's write out its value at the start of the loop.
+Putting a few strategic `console.log` calls into the program is a good way to get additional information about what the program is doing. In this case, we want `n` to take the values `13`, `1`, and then `0`. Let's write out its value at the start of the loop.
```{lang: null}
13
@@ -331,55 +213,31 @@ Let's write out its value at the start of the loop.
{{index rounding}}
-_Right_. Dividing 13 by 10 does not produce a whole number. Instead of
-`n /= base`, what we actually want is `n = Math.floor(n / base)` so
-that the number is properly "shifted" to the right.
+_Right_. Dividing 13 by 10 does not produce a whole number. Instead of `n /= base`, what we actually want is `n = Math.floor(n / base)` so that the number is properly "shifted" to the right.
{{index "JavaScript console", "debugger statement"}}
-An alternative to using `console.log` to peek into the program's
-behavior is to use the _debugger_ capabilities of your browser.
-Browsers come with the ability to set a _((breakpoint))_ on a specific
-line of your code. When the execution of the program reaches a line
-with a breakpoint, it is paused, and you can inspect the values of
-bindings at that point. I won't go into details, as debuggers differ
-from browser to browser, but look in your browser's ((developer
-tools)) or search the Web for more information.
+An alternative to using `console.log` to peek into the program's behavior is to use the _debugger_ capabilities of your browser. Browsers come with the ability to set a _((breakpoint))_ on a specific line of your code. When the execution of the program reaches a line with a breakpoint, it is paused, and you can inspect the values of bindings at that point. I won't go into details, as debuggers differ from browser to browser, but look in your browser's ((developer tools)) or search the Web for more information.
-Another way to set a breakpoint is to include a `debugger` statement
-(consisting of simply that keyword) in your program. If the
-((developer tools)) of your browser are active, the program will pause
-whenever it reaches such a statement.
+Another way to set a breakpoint is to include a `debugger` statement (consisting of simply that keyword) in your program. If the ((developer tools)) of your browser are active, the program will pause whenever it reaches such a statement.
## Error propagation
{{index input, output, "run-time error", error, validation}}
-Not all problems can be prevented by the programmer, unfortunately. If
-your program communicates with the outside world in any way, it is
-possible to get malformed input, to become overloaded with work, or to
-have the network fail.
+Not all problems can be prevented by the programmer, unfortunately. If your program communicates with the outside world in any way, it is possible to get malformed input, to become overloaded with work, or to have the network fail.
{{index "error recovery"}}
-If you're programming only for yourself, you can afford to just ignore
-such problems until they occur. But if you build something that is
-going to be used by anybody else, you usually want the program to do
-better than just crash. Sometimes the right thing to do is take the
-bad input in stride and continue running. In other cases, it is better
-to report to the user what went wrong and then give up. But in either
-situation, the program has to actively do something in response to the
-problem.
+If you're programming only for yourself, you can afford to just ignore such problems until they occur. But if you build something that is going to be used by anybody else, you usually want the program to do better than just crash. Sometimes the right thing to do is take the bad input in stride and continue running. In other cases, it is better to report to the user what went wrong and then give up. But in either situation, the program has to actively do something in response to the problem.
{{index "promptNumber function", validation}}
-Say you have a function `promptNumber` that asks the user for a number
-and returns it. What should it return if the user inputs "orange"?
+Say you have a function `promptNumber` that asks the user for a number and returns it. What should it return if the user inputs "orange"?
{{index null, undefined, "return value", "special return value"}}
-One option is to make it return a special value. Common choices for
-such values are `null`, `undefined`, or -1.
+One option is to make it return a special value. Common choices for such values are `null`, `undefined`, or -1.
```{test: no}
function promptNumber(question) {
@@ -391,21 +249,11 @@ function promptNumber(question) {
console.log(promptNumber("How many trees do you see?"));
```
-Now any code that calls `promptNumber` must check whether an actual
-number was read and, failing that, must somehow recover—maybe by
-asking again or by filling in a default value. Or it could again
-return a special value to _its_ caller to indicate that it failed to
-do what it was asked.
+Now any code that calls `promptNumber` must check whether an actual number was read and, failing that, must somehow recover—maybe by asking again or by filling in a default value. Or it could again return a special value to _its_ caller to indicate that it failed to do what it was asked.
{{index "error handling"}}
-In many situations, mostly when ((error))s are common and the caller
-should be explicitly taking them into account, returning a special
-value is a good way to indicate an error. It does, however, have its
-downsides. First, what if the function can already return every
-possible kind of value? In such a function, you'll have to do
-something like wrap the result in an object to be able to distinguish
-success from failure.
+In many situations, mostly when ((error))s are common and the caller should be explicitly taking them into account, returning a special value is a good way to indicate an error. It does, however, have its downsides. First, what if the function can already return every possible kind of value? In such a function, you'll have to do something like wrap the result in an object to be able to distinguish success from failure.
```
function lastElement(array) {
@@ -419,40 +267,21 @@ function lastElement(array) {
{{index "special return value", readability}}
-The second issue with returning special values is that it can lead to
-awkward code. If a piece of code calls `promptNumber` 10 times,
-it has to check 10 times whether `null` was returned. And if its
-response to finding `null` is to simply return `null` itself, callers
-of the function will in turn have to check for it, and so on.
+The second issue with returning special values is that it can lead to awkward code. If a piece of code calls `promptNumber` 10 times, it has to check 10 times whether `null` was returned. And if its response to finding `null` is to simply return `null` itself, callers of the function will in turn have to check for it, and so on.
## Exceptions
{{index "error handling"}}
-When a function cannot proceed normally, what we would _like_ to do is
-just stop what we are doing and immediately jump to a place that knows
-how to handle the problem. This is what _((exception handling))_ does.
+When a function cannot proceed normally, what we would _like_ to do is just stop what we are doing and immediately jump to a place that knows how to handle the problem. This is what _((exception handling))_ does.
{{index ["control flow", exceptions], "raising (exception)", "throw keyword", "call stack"}}
-Exceptions are a mechanism that makes it possible for code that runs
-into a problem to _raise_ (or _throw_) an exception. An exception can
-be any value. Raising one somewhat resembles a super-charged return
-from a function: it jumps out of not just the current function but
-also its callers, all the way down to the first call that
-started the current execution. This is called _((unwinding the
-stack))_. You may remember the stack of function calls that was
-mentioned in [Chapter ?](functions#stack). An exception zooms down
-this stack, throwing away all the call contexts it encounters.
+Exceptions are a mechanism that makes it possible for code that runs into a problem to _raise_ (or _throw_) an exception. An exception can be any value. Raising one somewhat resembles a super-charged return from a function: it jumps out of not just the current function but also its callers, all the way down to the first call that started the current execution. This is called _((unwinding the stack))_. You may remember the stack of function calls that was mentioned in [Chapter ?](functions#stack). An exception zooms down this stack, throwing away all the call contexts it encounters.
{{index "error handling", [syntax, statement], "catch keyword"}}
-If exceptions always zoomed right down to the bottom of the stack,
-they would not be of much use. They'd just provide a novel way to blow
-up your program. Their power lies in the fact that you can set
-"obstacles" along the stack to _catch_ the exception as it is zooming
-down. Once you've caught an exception, you can do something with it to
-address the problem and then continue to run the program.
+If exceptions always zoomed right down to the bottom of the stack, they would not be of much use. They'd just provide a novel way to blow up your program. Their power lies in the fact that you can set "obstacles" along the stack to _catch_ the exception as it is zooming down. Once you've caught an exception, you can do something with it to address the problem and then continue to run the program.
Here's an example:
@@ -482,33 +311,15 @@ try {
{{index "exception handling", block, "throw keyword", "try keyword", "catch keyword"}}
-The `throw` keyword is used to raise an exception. Catching one is
-done by wrapping a piece of code in a `try` block, followed by the
-keyword `catch`. When the code in the `try` block causes an exception
-to be raised, the `catch` block is evaluated, with the name in
-parentheses bound to the exception value. After the `catch` block
-finishes—or if the `try` block finishes without problems—the program
-proceeds beneath the entire `try/catch` statement.
+The `throw` keyword is used to raise an exception. Catching one is done by wrapping a piece of code in a `try` block, followed by the keyword `catch`. When the code in the `try` block causes an exception to be raised, the `catch` block is evaluated, with the name in parentheses bound to the exception value. After the `catch` block finishes—or if the `try` block finishes without problems—the program proceeds beneath the entire `try/catch` statement.
{{index debugging, "call stack", "Error type"}}
-In this case, we used the `Error` ((constructor)) to create our
-exception value. This is a ((standard)) JavaScript constructor that
-creates an object with a `message` property. In most JavaScript
-environments, instances of this constructor also gather information
-about the call stack that existed when the exception was created, a
-so-called _((stack trace))_. This information is stored in the `stack`
-property and can be helpful when trying to debug a problem: it tells
-us the function where the problem occurred and which functions made
-the failing call.
+In this case, we used the `Error` ((constructor)) to create our exception value. This is a ((standard)) JavaScript constructor that creates an object with a `message` property. In most JavaScript environments, instances of this constructor also gather information about the call stack that existed when the exception was created, a so-called _((stack trace))_. This information is stored in the `stack` property and can be helpful when trying to debug a problem: it tells us the function where the problem occurred and which functions made the failing call.
{{index "exception handling"}}
-Note that the `look` function completely ignores the possibility that
-`promptDirection` might go wrong. This is the big advantage of
-exceptions: error-handling code is necessary only at the point where
-the error occurs and at the point where it is handled. The functions
-in between can forget all about it.
+Note that the `look` function completely ignores the possibility that `promptDirection` might go wrong. This is the big advantage of exceptions: error-handling code is necessary only at the point where the error occurs and at the point where it is handled. The functions in between can forget all about it.
Well, almost...
@@ -516,14 +327,9 @@ Well, almost...
{{index "exception handling", "cleaning up", ["control flow", exceptions]}}
-The effect of an exception is another kind of control flow. Every
-action that might cause an exception, which is pretty much every
-function call and property access, might cause control to suddenly
-leave your code.
+The effect of an exception is another kind of control flow. Every action that might cause an exception, which is pretty much every function call and property access, might cause control to suddenly leave your code.
-This means when code has several side effects, even if its
-"regular" control flow looks like they'll always all happen, an
-exception might prevent some of them from taking place.
+This means when code has several side effects, even if its "regular" control flow looks like they'll always all happen, an exception might prevent some of them from taking place.
{{index "banking example"}}
@@ -551,34 +357,17 @@ function transfer(from, amount) {
}
```
-The `transfer` function transfers a sum of money from a given account
-to another, asking for the name of the other account in the process.
-If given an invalid account name, `getAccount` throws an exception.
+The `transfer` function transfers a sum of money from a given account to another, asking for the name of the other account in the process. If given an invalid account name, `getAccount` throws an exception.
-But `transfer` _first_ removes the money from the account and _then_
-calls `getAccount` before it adds it to another account. If it is
-broken off by an exception at that point, it'll just make the money
-disappear.
+But `transfer` _first_ removes the money from the account and _then_ calls `getAccount` before it adds it to another account. If it is broken off by an exception at that point, it'll just make the money disappear.
-That code could have been written a little more intelligently, for
-example by calling `getAccount` before it starts moving money around.
-But often problems like this occur in more subtle ways. Even functions
-that don't look like they will throw an exception might do so in
-exceptional circumstances or when they contain a programmer mistake.
+That code could have been written a little more intelligently, for example by calling `getAccount` before it starts moving money around. But often problems like this occur in more subtle ways. Even functions that don't look like they will throw an exception might do so in exceptional circumstances or when they contain a programmer mistake.
-One way to address this is to use fewer side effects. Again, a
-programming style that computes new values instead of changing
-existing data helps. If a piece of code stops running in the middle of
-creating a new value, no one ever sees the half-finished value, and
-there is no problem.
+One way to address this is to use fewer side effects. Again, a programming style that computes new values instead of changing existing data helps. If a piece of code stops running in the middle of creating a new value, no one ever sees the half-finished value, and there is no problem.
{{index block, "try keyword", "finally keyword"}}
-But that isn't always practical. So there is another feature that
-`try` statements have. They may be followed by a `finally` block
-either instead of or in addition to a `catch` block. A `finally` block
-says "no matter _what_ happens, run this code after trying to run the
-code in the `try` block."
+But that isn't always practical. So there is another feature that `try` statements have. They may be followed by a `finally` block either instead of or in addition to a `catch` block. A `finally` block says "no matter _what_ happens, run this code after trying to run the code in the `try` block."
```{includeCode: true}
function transfer(from, amount) {
@@ -597,76 +386,43 @@ function transfer(from, amount) {
}
```
-This version of the function tracks its progress, and if, when
-leaving, it notices that it was aborted at a point where it had
-created an inconsistent program state, it repairs the damage it did.
+This version of the function tracks its progress, and if, when leaving, it notices that it was aborted at a point where it had created an inconsistent program state, it repairs the damage it did.
-Note that even though the `finally` code is run when an exception
-is thrown in the `try` block, it does not interfere with the exception.
-After the `finally` block runs, the stack continues unwinding.
+Note that even though the `finally` code is run when an exception is thrown in the `try` block, it does not interfere with the exception. After the `finally` block runs, the stack continues unwinding.
{{index "exception safety"}}
-Writing programs that operate reliably even when exceptions pop up in
-unexpected places is hard. Many people simply don't bother, and
-because exceptions are typically reserved for exceptional
-circumstances, the problem may occur so rarely that it is never even
-noticed. Whether that is a good thing or a really bad thing depends on
-how much damage the software will do when it fails.
+Writing programs that operate reliably even when exceptions pop up in unexpected places is hard. Many people simply don't bother, and because exceptions are typically reserved for exceptional circumstances, the problem may occur so rarely that it is never even noticed. Whether that is a good thing or a really bad thing depends on how much damage the software will do when it fails.
## Selective catching
{{index "uncaught exception", "exception handling", "JavaScript console", "developer tools", "call stack", error}}
-When an exception makes it all the way to the bottom of the stack
-without being caught, it gets handled by the environment. What this
-means differs between environments. In browsers, a description of the
-error typically gets written to the JavaScript console (reachable
-through the browser's Tools or Developer menu). Node.js, the
-browserless JavaScript environment we will discuss in [Chapter
-?](node), is more careful about data corruption. It aborts the whole
-process when an unhandled exception occurs.
+When an exception makes it all the way to the bottom of the stack without being caught, it gets handled by the environment. What this means differs between environments. In browsers, a description of the error typically gets written to the JavaScript console (reachable through the browser's Tools or Developer menu). Node.js, the browserless JavaScript environment we will discuss in [Chapter ?](node), is more careful about data corruption. It aborts the whole process when an unhandled exception occurs.
{{index crash, "error handling"}}
-For programmer mistakes, just letting the error go through is often
-the best you can do. An unhandled exception is a reasonable way to
-signal a broken program, and the JavaScript console will, on modern
-browsers, provide you with some information about which function calls
-were on the stack when the problem occurred.
+For programmer mistakes, just letting the error go through is often the best you can do. An unhandled exception is a reasonable way to signal a broken program, and the JavaScript console will, on modern browsers, provide you with some information about which function calls were on the stack when the problem occurred.
{{index "user interface"}}
-For problems that are _expected_ to happen during routine use,
-crashing with an unhandled exception is a terrible strategy.
+For problems that are _expected_ to happen during routine use, crashing with an unhandled exception is a terrible strategy.
{{index [function, application], "exception handling", "Error type", [binding, undefined]}}
-Invalid uses of the language, such as referencing a nonexistent
-binding, looking up a property on `null`, or calling something
-that's not a function, will also result in exceptions being raised.
-Such exceptions can also be caught.
+Invalid uses of the language, such as referencing a nonexistent binding, looking up a property on `null`, or calling something that's not a function, will also result in exceptions being raised. Such exceptions can also be caught.
{{index "catch keyword"}}
-When a `catch` body is entered, all we know is that _something_ in our
-`try` body caused an exception. But we don't know _what_ did or _which_
-exception it caused.
+When a `catch` body is entered, all we know is that _something_ in our `try` body caused an exception. But we don't know _what_ did or _which_ exception it caused.
{{index "exception handling"}}
-JavaScript (in a rather glaring omission) doesn't provide direct
-support for selectively catching exceptions: either you catch them all
-or you don't catch any. This makes it tempting to _assume_ that the
-exception you get is the one you were thinking about when you wrote
-the `catch` block.
+JavaScript (in a rather glaring omission) doesn't provide direct support for selectively catching exceptions: either you catch them all or you don't catch any. This makes it tempting to _assume_ that the exception you get is the one you were thinking about when you wrote the `catch` block.
{{index "promptDirection function"}}
-But it might not be. Some other ((assumption)) might be violated, or
-you might have introduced a bug that is causing an exception. Here is
-an example that _attempts_ to keep on calling `promptDirection`
-until it gets a valid answer:
+But it might not be. Some other ((assumption)) might be violated, or you might have introduced a bug that is causing an exception. Here is an example that _attempts_ to keep on calling `promptDirection` until it gets a valid answer:
```{test: no}
for (;;) {
@@ -682,37 +438,19 @@ for (;;) {
{{index "infinite loop", "for loop", "catch keyword", debugging}}
-The `for (;;)` construct is a way to intentionally create a loop that
-doesn't terminate on its own. We break out of the loop only when a
-valid direction is given. _But_ we misspelled `promptDirection`, which
-will result in an "undefined variable" error. Because the `catch`
-block completely ignores its exception value (`e`), assuming it knows
-what the problem is, it wrongly treats the binding error as indicating
-bad input. Not only does this cause an infinite loop, it
-"buries" the useful error message about the misspelled binding.
+The `for (;;)` construct is a way to intentionally create a loop that doesn't terminate on its own. We break out of the loop only when a valid direction is given. _But_ we misspelled `promptDirection`, which will result in an "undefined variable" error. Because the `catch` block completely ignores its exception value (`e`), assuming it knows what the problem is, it wrongly treats the binding error as indicating bad input. Not only does this cause an infinite loop, it "buries" the useful error message about the misspelled binding.
-As a general rule, don't blanket-catch exceptions unless it is for the
-purpose of "routing" them somewhere—for example, over the network to
-tell another system that our program crashed. And even then, think
-carefully about how you might be hiding information.
+As a general rule, don't blanket-catch exceptions unless it is for the purpose of "routing" them somewhere—for example, over the network to tell another system that our program crashed. And even then, think carefully about how you might be hiding information.
{{index "exception handling"}}
-So we want to catch a _specific_ kind of exception. We can do this by
-checking in the `catch` block whether the exception we got is the one
-we are interested in and rethrowing it otherwise. But how do we
-recognize an exception?
+So we want to catch a _specific_ kind of exception. We can do this by checking in the `catch` block whether the exception we got is the one we are interested in and rethrowing it otherwise. But how do we recognize an exception?
-We could compare its `message` property against the ((error)) message
-we happen to expect. But that's a shaky way to write code—we'd be
-using information that's intended for human consumption (the message)
-to make a programmatic decision. As soon as someone changes (or
-translates) the message, the code will stop working.
+We could compare its `message` property against the ((error)) message we happen to expect. But that's a shaky way to write code—we'd be using information that's intended for human consumption (the message) to make a programmatic decision. As soon as someone changes (or translates) the message, the code will stop working.
{{index "Error type", "instanceof operator", "promptDirection function"}}
-Rather, let's define a new type of error and use `instanceof` to
-identify it.
+Rather, let's define a new type of error and use `instanceof` to identify it.
```{includeCode: true}
class InputError extends Error {}
@@ -727,12 +465,7 @@ function promptDirection(question) {
{{index "throw keyword", inheritance}}
-The new error class extends `Error`. It doesn't define its own
-constructor, which means that it inherits the `Error` constructor,
-which expects a string message as argument. In fact, it doesn't define
-anything at all—the class is empty. `InputError` objects behave like
-`Error` objects, except that they have a different class by which we
-can recognize them.
+The new error class extends `Error`. It doesn't define its own constructor, which means that it inherits the `Error` constructor, which expects a string message as argument. In fact, it doesn't define anything at all—the class is empty. `InputError` objects behave like `Error` objects, except that they have a different class by which we can recognize them.
{{index "exception handling"}}
@@ -756,20 +489,15 @@ for (;;) {
{{index debugging}}
-This will catch only instances of `InputError` and let unrelated
-exceptions through. If you reintroduce the typo, the undefined binding
-error will be properly reported.
+This will catch only instances of `InputError` and let unrelated exceptions through. If you reintroduce the typo, the undefined binding error will be properly reported.
## Assertions
{{index "assert function", assertion, debugging}}
-_Assertions_ are checks inside a program that verify that something is
-the way it is supposed to be. They are used not to handle situations
-that can come up in normal operation but to find programmer mistakes.
+_Assertions_ are checks inside a program that verify that something is the way it is supposed to be. They are used not to handle situations that can come up in normal operation but to find programmer mistakes.
-If, for example, `firstElement` is described as a function that should
-never be called on empty arrays, we might write it like this:
+If, for example, `firstElement` is described as a function that should never be called on empty arrays, we might write it like this:
```
function firstElement(array) {
@@ -782,36 +510,17 @@ function firstElement(array) {
{{index validation, "run-time error", crash, assumption}}
-Now, instead of silently returning undefined (which you get when
-reading an array property that does not exist), this will loudly blow
-up your program as soon as you misuse it. This makes it less likely
-for such mistakes to go unnoticed and easier to find their cause when
-they occur.
+Now, instead of silently returning undefined (which you get when reading an array property that does not exist), this will loudly blow up your program as soon as you misuse it. This makes it less likely for such mistakes to go unnoticed and easier to find their cause when they occur.
-I do not recommend trying to write assertions for every possible kind
-of bad input. That'd be a lot of work and would lead to very noisy
-code. You'll want to reserve them for mistakes that are easy to make
-(or that you find yourself making).
+I do not recommend trying to write assertions for every possible kind of bad input. That'd be a lot of work and would lead to very noisy code. You'll want to reserve them for mistakes that are easy to make (or that you find yourself making).
## Summary
-Mistakes and bad input are facts of life. An important part of
-programming is finding, diagnosing, and fixing bugs. Problems can
-become easier to notice if you have an automated test suite or add
-assertions to your programs.
+Mistakes and bad input are facts of life. An important part of programming is finding, diagnosing, and fixing bugs. Problems can become easier to notice if you have an automated test suite or add assertions to your programs.
-Problems caused by factors outside the program's control should
-usually be handled gracefully. Sometimes, when the problem can be
-handled locally, special return values are a good way to track them.
-Otherwise, exceptions may be preferable.
+Problems caused by factors outside the program's control should usually be handled gracefully. Sometimes, when the problem can be handled locally, special return values are a good way to track them. Otherwise, exceptions may be preferable.
-Throwing an exception causes the call stack to be unwound until the
-next enclosing `try/catch` block or until the bottom of the stack. The
-exception value will be given to the `catch` block that catches it,
-which should verify that it is actually the expected kind of exception
-and then do something with it. To help address the unpredictable
-control flow caused by exceptions, `finally` blocks can be used to
-ensure that a piece of code _always_ runs when a block finishes.
+Throwing an exception causes the call stack to be unwound until the next enclosing `try/catch` block or until the bottom of the stack. The exception value will be given to the `catch` block that catches it, which should verify that it is actually the expected kind of exception and then do something with it. To help address the unpredictable control flow caused by exceptions, `finally` blocks can be used to ensure that a piece of code _always_ runs when a block finishes.
## Exercises
@@ -819,11 +528,7 @@ ensure that a piece of code _always_ runs when a block finishes.
{{index "primitiveMultiply (exercise)", "exception handling", "throw keyword"}}
-Say you have a function `primitiveMultiply` that in 20 percent of
-cases multiplies two numbers and in the other 80 percent of cases raises an
-exception of type `MultiplicatorUnitFailure`. Write a function that
-wraps this clunky function and just keeps trying until a call
-succeeds, after which it returns the result.
+Say you have a function `primitiveMultiply` that in 20 percent of cases multiplies two numbers and in the other 80 percent of cases raises an exception of type `MultiplicatorUnitFailure`. Write a function that wraps this clunky function and just keeps trying until a call succeeds, after which it returns the result.
{{index "catch keyword"}}
@@ -855,16 +560,9 @@ if}}
{{index "primitiveMultiply (exercise)", "try keyword", "catch keyword", "throw keyword"}}
-The call to `primitiveMultiply` should definitely happen in a `try`
-block. The corresponding `catch` block should rethrow the exception
-when it is not an instance of `MultiplicatorUnitFailure` and ensure
-the call is retried when it is.
+The call to `primitiveMultiply` should definitely happen in a `try` block. The corresponding `catch` block should rethrow the exception when it is not an instance of `MultiplicatorUnitFailure` and ensure the call is retried when it is.
-To do the retrying, you can either use a loop that stops only when a
-call succeeds—as in the [`look` example](error#look) earlier in this
-chapter—or use ((recursion)) and hope you don't get a string of
-failures so long that it overflows the stack (which is a pretty safe
-bet).
+To do the retrying, you can either use a loop that stops only when a call succeeds—as in the [`look` example](error#look) earlier in this chapter—or use ((recursion)) and hope you don't get a string of failures so long that it overflows the stack (which is a pretty safe bet).
hint}}
@@ -889,16 +587,11 @@ const box = {
{{index "private property", "access control"}}
-It is a ((box)) with a lock. There is an array in the box, but you can
-get at it only when the box is unlocked. Directly accessing the
-private `_content` property is forbidden.
+It is a ((box)) with a lock. There is an array in the box, but you can get at it only when the box is unlocked. Directly accessing the private `_content` property is forbidden.
{{index "finally keyword", "exception handling"}}
-Write a function called `withBoxUnlocked` that takes a function value
-as argument, unlocks the box, runs the function, and then ensures that
-the box is locked again before returning, regardless of whether the
-argument function returned normally or threw an exception.
+Write a function called `withBoxUnlocked` that takes a function value as argument, unlocks the box, runs the function, and then ensures that the box is locked again before returning, regardless of whether the argument function returned normally or threw an exception.
{{if interactive
@@ -935,19 +628,14 @@ console.log(box.locked);
if}}
-For extra points, make sure that if you call `withBoxUnlocked` when
-the box is already unlocked, the box stays unlocked.
+For extra points, make sure that if you call `withBoxUnlocked` when the box is already unlocked, the box stays unlocked.
{{hint
{{index "locked box (exercise)", "finally keyword", "try keyword"}}
-This exercise calls for a `finally` block. Your function should first
-unlock the box and then call the argument function from inside a `try`
-body. The `finally` block after it should lock the box again.
+This exercise calls for a `finally` block. Your function should first unlock the box and then call the argument function from inside a `try` body. The `finally` block after it should lock the box again.
-To make sure we don't lock the box when it wasn't already locked,
-check its lock at the start of the function and unlock and lock
-it only when it started out locked.
+To make sure we don't lock the box when it wasn't already locked, check its lock at the start of the function and unlock and lock it only when it started out locked.
hint}}
diff --git a/09_regexp.md b/09_regexp.md
index 75307dc9e..117a907ca 100644
--- a/09_regexp.md
+++ b/09_regexp.md
@@ -2,8 +2,7 @@
{{quote {author: "Jamie Zawinski", chapter: true}
-Some people, when confronted with a problem, think 'I know, I'll use
-regular expressions.' Now they have two problems.
+Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems.
quote}}
@@ -13,9 +12,7 @@ quote}}
{{quote {author: "Master Yuan-Ma", title: "The Book of Programming", chapter: true}
-Yuan-Ma said, 'When you cut against the grain of the wood, much
-strength is needed. When you program against the grain of the problem,
-much code is needed.'
+Yuan-Ma said, 'When you cut against the grain of the wood, much strength is needed. When you program against the grain of the problem, much code is needed.'
quote}}
@@ -25,60 +22,36 @@ if}}
{{index evolution, adoption, integration}}
-Programming ((tool))s and techniques survive and spread in a chaotic,
-evolutionary way. It's not always the pretty or brilliant ones that
-win but rather the ones that function well enough within the right
-niche or that happen to be integrated with another successful piece of
-technology.
+Programming ((tool))s and techniques survive and spread in a chaotic, evolutionary way. It's not always the pretty or brilliant ones that win but rather the ones that function well enough within the right niche or that happen to be integrated with another successful piece of technology.
{{index "domain-specific language"}}
-In this chapter, I will discuss one such tool, _((regular
-expression))s_. Regular expressions are a way to describe ((pattern))s
-in string data. They form a small, separate language that is part of
-JavaScript and many other languages and systems.
+In this chapter, I will discuss one such tool, _((regular expression))s_. Regular expressions are a way to describe ((pattern))s in string data. They form a small, separate language that is part of JavaScript and many other languages and systems.
{{index [interface, design]}}
-Regular expressions are both terribly awkward and extremely useful.
-Their syntax is cryptic, and the programming interface JavaScript
-provides for them is clumsy. But they are a powerful ((tool)) for
-inspecting and processing strings. Properly understanding regular
-expressions will make you a more effective programmer.
+Regular expressions are both terribly awkward and extremely useful. Their syntax is cryptic, and the programming interface JavaScript provides for them is clumsy. But they are a powerful ((tool)) for inspecting and processing strings. Properly understanding regular expressions will make you a more effective programmer.
## Creating a regular expression
{{index ["regular expression", creation], "RegExp class", "literal expression", "slash character"}}
-A regular expression is a type of object. It can be either constructed
-with the `RegExp` constructor or written as a literal value by
-enclosing a pattern in forward slash (`/`) characters.
+A regular expression is a type of object. It can be either constructed with the `RegExp` constructor or written as a literal value by enclosing a pattern in forward slash (`/`) characters.
```
let re1 = new RegExp("abc");
let re2 = /abc/;
```
-Both of those regular expression objects represent the same
-((pattern)): an _a_ character followed by a _b_ followed by a _c_.
+Both of those regular expression objects represent the same ((pattern)): an _a_ character followed by a _b_ followed by a _c_.
{{index ["backslash character", "in regular expressions"], "RegExp class"}}
-When using the `RegExp` constructor, the pattern is written as a
-normal string, so the usual rules apply for backslashes.
+When using the `RegExp` constructor, the pattern is written as a normal string, so the usual rules apply for backslashes.
{{index ["regular expression", escaping], [escaping, "in regexps"], "slash character"}}
-The second notation, where the pattern appears between slash
-characters, treats backslashes somewhat differently. First, since a
-forward slash ends the pattern, we need to put a backslash before any
-forward slash that we want to be _part_ of the pattern. In addition,
-backslashes that aren't part of special character codes (like `\n`)
-will be _preserved_, rather than ignored as they are in strings, and
-change the meaning of the pattern. Some characters, such as question
-marks and plus signs, have special meanings in regular expressions and
-must be preceded by a backslash if they are meant to represent the
-character itself.
+The second notation, where the pattern appears between slash characters, treats backslashes somewhat differently. First, since a forward slash ends the pattern, we need to put a backslash before any forward slash that we want to be _part_ of the pattern. In addition, backslashes that aren't part of special character codes (like `\n`) will be _preserved_, rather than ignored as they are in strings, and change the meaning of the pattern. Some characters, such as question marks and plus signs, have special meanings in regular expressions and must be preceded by a backslash if they are meant to represent the character itself.
```
let eighteenPlus = /eighteen\+/;
@@ -88,10 +61,7 @@ let eighteenPlus = /eighteen\+/;
{{index matching, "test method", ["regular expression", methods]}}
-Regular expression objects have a number of methods. The simplest one
-is `test`. If you pass it a string, it will return a ((Boolean))
-telling you whether the string contains a match of the pattern in the
-expression.
+Regular expression objects have a number of methods. The simplest one is `test`. If you pass it a string, it will return a ((Boolean)) telling you whether the string contains a match of the pattern in the expression.
```
console.log(/abc/.test("abcde"));
@@ -102,22 +72,15 @@ console.log(/abc/.test("abxde"));
{{index pattern}}
-A ((regular expression)) consisting of only nonspecial characters
-simply represents that sequence of characters. If _abc_ occurs
-anywhere in the string we are testing against (not just at the start),
-`test` will return `true`.
+A ((regular expression)) consisting of only nonspecial characters simply represents that sequence of characters. If _abc_ occurs anywhere in the string we are testing against (not just at the start), `test` will return `true`.
## Sets of characters
{{index "regular expression", "indexOf method"}}
-Finding out whether a string contains _abc_ could just as well be done
-with a call to `indexOf`. Regular expressions allow us to express more
-complicated ((pattern))s.
+Finding out whether a string contains _abc_ could just as well be done with a call to `indexOf`. Regular expressions allow us to express more complicated ((pattern))s.
-Say we want to match any ((number)). In a regular expression, putting
-a ((set)) of characters between square brackets makes that part of the
-expression match any of the characters between the brackets.
+Say we want to match any ((number)). In a regular expression, putting a ((set)) of characters between square brackets makes that part of the expression match any of the characters between the brackets.
Both of the following expressions match all strings that contain a ((digit)):
@@ -130,17 +93,11 @@ console.log(/[0-9]/.test("in 1992"));
{{index "hyphen character"}}
-Within square brackets, a hyphen (`-`) between two characters can be
-used to indicate a ((range)) of characters, where the ordering is
-determined by the character's ((Unicode)) number. Characters 0 to 9
-sit right next to each other in this ordering (codes 48 to 57), so
-`[0-9]` covers all of them and matches any ((digit)).
+Within square brackets, a hyphen (`-`) between two characters can be used to indicate a ((range)) of characters, where the ordering is determined by the character's ((Unicode)) number. Characters 0 to 9 sit right next to each other in this ordering (codes 48 to 57), so `[0-9]` covers all of them and matches any ((digit)).
{{index [whitespace, matching], "alphanumeric character", "period character"}}
-A number of common character groups have their own
-built-in shortcuts. Digits are one of them: `\d` means the same thing
-as `[0-9]`.
+A number of common character groups have their own built-in shortcuts. Digits are one of them: `\d` means the same thing as `[0-9]`.
{{index "newline character", [whitespace, matching]}}
@@ -154,8 +111,7 @@ as `[0-9]`.
| `\S` | A nonwhitespace character
| `.` | Any character except for newline
-So you could match a ((date)) and ((time)) format like 01-30-2003
-15:20 with the following expression:
+So you could match a ((date)) and ((time)) format like 01-30-2003 15:20 with the following expression:
```
let dateTime = /\d\d-\d\d-\d\d\d\d \d\d:\d\d/;
@@ -167,23 +123,15 @@ console.log(dateTime.test("30-jan-2003 15:20"));
{{index ["backslash character", "in regular expressions"]}}
-That looks completely awful, doesn't it? Half of it is backslashes,
-producing a background noise that makes it hard to spot the actual
-((pattern)) expressed. We'll see a slightly improved version of this
-expression [later](regexp#date_regexp_counted).
+That looks completely awful, doesn't it? Half of it is backslashes, producing a background noise that makes it hard to spot the actual ((pattern)) expressed. We'll see a slightly improved version of this expression [later](regexp#date_regexp_counted).
{{index [escaping, "in regexps"], "regular expression", set}}
-These backslash codes can also be used inside ((square brackets)). For
-example, `[\d.]` means any digit or a period character. But the period
-itself, between square brackets, loses its special meaning. The same
-goes for other special characters, such as `+`.
+These backslash codes can also be used inside ((square brackets)). For example, `[\d.]` means any digit or a period character. But the period itself, between square brackets, loses its special meaning. The same goes for other special characters, such as `+`.
{{index "square brackets", inversion, "caret character"}}
-To _invert_ a set of characters—that is, to express that you want to
-match any character _except_ the ones in the set—you can write a caret
-(`^`) character after the opening bracket.
+To _invert_ a set of characters—that is, to express that you want to match any character _except_ the ones in the set—you can write a caret (`^`) character after the opening bracket.
```
let notBinary = /[^01]/;
@@ -197,14 +145,11 @@ console.log(notBinary.test("1100100010200110"));
{{index ["regular expression", repetition]}}
-We now know how to match a single digit. What if we want to match a
-whole number—a ((sequence)) of one or more ((digit))s?
+We now know how to match a single digit. What if we want to match a whole number—a ((sequence)) of one or more ((digit))s?
{{index "plus character", repetition, "+ operator"}}
-When you put a plus sign (`+`) after something in a regular
-expression, it indicates that the element may be repeated more than
-once. Thus, `/\d+/` matches one or more digit characters.
+When you put a plus sign (`+`) after something in a regular expression, it indicates that the element may be repeated more than once. Thus, `/\d+/` matches one or more digit characters.
```
console.log(/'\d+'/.test("'123'"));
@@ -219,17 +164,11 @@ console.log(/'\d*'/.test("''"));
{{index "* operator", asterisk}}
-The star (`*`) has a similar meaning but also allows the pattern to
-match zero times. Something with a star after it never prevents a
-pattern from matching—it'll just match zero instances if it can't find
-any suitable text to match.
+The star (`*`) has a similar meaning but also allows the pattern to match zero times. Something with a star after it never prevents a pattern from matching—it'll just match zero instances if it can't find any suitable text to match.
{{index "British English", "American English", "question mark"}}
-A question mark makes a part of a pattern _((optional))_, meaning it
-may occur zero times or one time. In the following example, the _u_
-character is allowed to occur, but the pattern also matches when it is
-missing.
+A question mark makes a part of a pattern _((optional))_, meaning it may occur zero times or one time. In the following example, the _u_ character is allowed to occur, but the pattern also matches when it is missing.
```
let neighbor = /neighbou?r/;
@@ -241,17 +180,11 @@ console.log(neighbor.test("neighbor"));
{{index repetition, [braces, "in regular expression"]}}
-To indicate that a pattern should occur a precise number of times, use
-braces. Putting `{4}` after an element, for example, requires it
-to occur exactly four times. It is also possible to specify a
-((range)) this way: `{2,4}` means the element must occur at least
-twice and at most four times.
+To indicate that a pattern should occur a precise number of times, use braces. Putting `{4}` after an element, for example, requires it to occur exactly four times. It is also possible to specify a ((range)) this way: `{2,4}` means the element must occur at least twice and at most four times.
{{id date_regexp_counted}}
-Here is another version of the ((date)) and ((time)) pattern that
-allows both single- and double-((digit)) days, months, and hours. It
-is also slightly easier to decipher.
+Here is another version of the ((date)) and ((time)) pattern that allows both single- and double-((digit)) days, months, and hours. It is also slightly easier to decipher.
```
let dateTime = /\d{1,2}-\d{1,2}-\d{4} \d{1,2}:\d{2}/;
@@ -259,18 +192,13 @@ console.log(dateTime.test("1-30-2003 8:45"));
// → true
```
-You can also specify open-ended ((range))s when using braces
-by omitting the number after the comma. So, `{5,}` means five or more
-times.
+You can also specify open-ended ((range))s when using braces by omitting the number after the comma. So, `{5,}` means five or more times.
## Grouping subexpressions
{{index ["regular expression", grouping], grouping, [parentheses, "in regular expressions"]}}
-To use an operator like `*` or `+` on more than one element at a time,
-you have to use parentheses. A part of a regular expression that
-is enclosed in parentheses counts as a single element as far as the
-operators following it are concerned.
+To use an operator like `*` or `+` on more than one element at a time, you have to use parentheses. A part of a regular expression that is enclosed in parentheses counts as a single element as far as the operators following it are concerned.
```
let cartoonCrying = /boo+(hoo+)+/i;
@@ -280,25 +208,17 @@ console.log(cartoonCrying.test("Boohoooohoohooo"));
{{index crying}}
-The first and second `+` characters apply only to the second _o_ in
-_boo_ and _hoo_, respectively. The third `+` applies to the whole
-group `(hoo+)`, matching one or more sequences like that.
+The first and second `+` characters apply only to the second _o_ in _boo_ and _hoo_, respectively. The third `+` applies to the whole group `(hoo+)`, matching one or more sequences like that.
{{index "case sensitivity", capitalization, ["regular expression", flags]}}
-The `i` at the end of the expression in the example makes this regular
-expression case insensitive, allowing it to match the uppercase _B_ in
-the input string, even though the pattern is itself all lowercase.
+The `i` at the end of the expression in the example makes this regular expression case insensitive, allowing it to match the uppercase _B_ in the input string, even though the pattern is itself all lowercase.
## Matches and groups
{{index ["regular expression", grouping], "exec method", [array, "RegExp match"]}}
-The `test` method is the absolute simplest way to match a regular
-expression. It tells you only whether it matched and nothing else.
-Regular expressions also have an `exec` (execute) method that will
-return `null` if no match was found and return an object with
-information about the match otherwise.
+The `test` method is the absolute simplest way to match a regular expression. It tells you only whether it matched and nothing else. Regular expressions also have an `exec` (execute) method that will return `null` if no match was found and return an object with information about the match otherwise.
```
let match = /\d+/.exec("one two 100");
@@ -310,11 +230,7 @@ console.log(match.index);
{{index "index property", [string, indexing]}}
-An object returned from `exec` has an `index` property that tells us
-_where_ in the string the successful match begins. Other than that,
-the object looks like (and in fact is) an array of strings, whose
-first element is the string that was matched. In the previous example,
-this is the sequence of ((digit))s that we were looking for.
+An object returned from `exec` has an `index` property that tells us _where_ in the string the successful match begins. Other than that, the object looks like (and in fact is) an array of strings, whose first element is the string that was matched. In the previous example, this is the sequence of ((digit))s that we were looking for.
{{index [string, methods], "match method"}}
@@ -327,12 +243,7 @@ console.log("one two 100".match(/\d+/));
{{index grouping, "capture group", "exec method"}}
-When the regular expression contains subexpressions grouped with
-parentheses, the text that matched those groups will also show up in
-the array. The whole match is always the first element. The next
-element is the part matched by the first group (the one whose opening
-parenthesis comes first in the expression), then the second group, and
-so on.
+When the regular expression contains subexpressions grouped with parentheses, the text that matched those groups will also show up in the array. The whole match is always the first element. The next element is the part matched by the first group (the one whose opening parenthesis comes first in the expression), then the second group, and so on.
```
let quotedText = /'([^']*)'/;
@@ -342,10 +253,7 @@ console.log(quotedText.exec("she said 'hello'"));
{{index "capture group"}}
-When a group does not end up being matched at all (for example, when
-followed by a question mark), its position in the output array will
-hold `undefined`. Similarly, when a group is matched multiple times,
-only the last match ends up in the array.
+When a group does not end up being matched at all (for example, when followed by a question mark), its position in the output array will hold `undefined`. Similarly, when a group is matched multiple times, only the last match ends up in the array.
```
console.log(/bad(ly)?/.exec("bad"));
@@ -356,22 +264,15 @@ console.log(/(\d)+/.exec("123"));
{{index "exec method", ["regular expression", methods], extraction}}
-Groups can be useful for extracting parts of a string. If we don't
-just want to verify whether a string contains a ((date)) but also
-extract it and construct an object that represents it, we can wrap
-parentheses around the digit patterns and directly pick the date out
-of the result of `exec`.
+Groups can be useful for extracting parts of a string. If we don't just want to verify whether a string contains a ((date)) but also extract it and construct an object that represents it, we can wrap parentheses around the digit patterns and directly pick the date out of the result of `exec`.
-But first we'll take a brief detour, in which we discuss the built-in way to
-represent date and ((time)) values in JavaScript.
+But first we'll take a brief detour, in which we discuss the built-in way to represent date and ((time)) values in JavaScript.
## The Date class
{{index constructor, "Date class"}}
-JavaScript has a standard class for representing ((date))s—or, rather,
-points in ((time)). It is called `Date`. If you simply create a date
-object using `new`, you get the current date and time.
+JavaScript has a standard class for representing ((date))s—or, rather, points in ((time)). It is called `Date`. If you simply create a date object using `new`, you get the current date and time.
```{test: no}
console.log(new Date());
@@ -391,20 +292,13 @@ console.log(new Date(2009, 11, 9, 12, 59, 59, 999));
{{index "zero-based counting", [interface, design]}}
-JavaScript uses a convention where month numbers start at zero (so
-December is 11), yet day numbers start at one. This is confusing and
-silly. Be careful.
+JavaScript uses a convention where month numbers start at zero (so December is 11), yet day numbers start at one. This is confusing and silly. Be careful.
-The last four arguments (hours, minutes, seconds, and milliseconds)
-are optional and taken to be zero when not given.
+The last four arguments (hours, minutes, seconds, and milliseconds) are optional and taken to be zero when not given.
{{index "getTime method"}}
-Timestamps are stored as the number of milliseconds since the start of
-1970, in the UTC ((time zone)). This follows a convention set by
-"((Unix time))", which was invented around that time. You can use
-negative numbers for times before 1970. The `getTime` method on a date
-object returns this number. It is big, as you can imagine.
+Timestamps are stored as the number of milliseconds since the start of 1970, in the UTC ((time zone)). This follows a convention set by "((Unix time))", which was invented around that time. You can use negative numbers for times before 1970. The `getTime` method on a date object returns this number. It is big, as you can imagine.
```
console.log(new Date(2013, 11, 19).getTime());
@@ -415,22 +309,15 @@ console.log(new Date(1387407600000));
{{index "Date.now function", "Date class"}}
-If you give the `Date` constructor a single argument, that argument is
-treated as such a millisecond count. You can get the current
-millisecond count by creating a new `Date` object and calling
-`getTime` on it or by calling the `Date.now` function.
+If you give the `Date` constructor a single argument, that argument is treated as such a millisecond count. You can get the current millisecond count by creating a new `Date` object and calling `getTime` on it or by calling the `Date.now` function.
{{index "getFullYear method", "getMonth method", "getDate method", "getHours method", "getMinutes method", "getSeconds method", "getYear method"}}
-Date objects provide methods such as `getFullYear`, `getMonth`,
-`getDate`, `getHours`, `getMinutes`, and `getSeconds` to extract their
-components. Besides `getFullYear` there's also `getYear`, which gives
-you the year minus 1900 (`98` or `119`) and is mostly useless.
+Date objects provide methods such as `getFullYear`, `getMonth`, `getDate`, `getHours`, `getMinutes`, and `getSeconds` to extract their components. Besides `getFullYear` there's also `getYear`, which gives you the year minus 1900 (`98` or `119`) and is mostly useless.
{{index "capture group", "getDate method", [parentheses, "in regular expressions"]}}
-Putting parentheses around the parts of the expression that we are
-interested in, we can now create a date object from a string.
+Putting parentheses around the parts of the expression that we are interested in, we can now create a date object from a string.
```
function getDate(string) {
@@ -444,35 +331,21 @@ console.log(getDate("1-30-2003"));
{{index destructuring, "underscore character"}}
-The `_` (underscore) binding is ignored and used only to skip the
-full match element in the array returned by `exec`.
+The `_` (underscore) binding is ignored and used only to skip the full match element in the array returned by `exec`.
## Word and string boundaries
{{index matching, ["regular expression", boundary]}}
-Unfortunately, `getDate` will also happily extract the nonsensical
-date 00-1-3000 from the string `"100-1-30000"`. A match may happen
-anywhere in the string, so in this case, it'll just start at the
-second character and end at the second-to-last character.
+Unfortunately, `getDate` will also happily extract the nonsensical date 00-1-3000 from the string `"100-1-30000"`. A match may happen anywhere in the string, so in this case, it'll just start at the second character and end at the second-to-last character.
{{index boundary, "caret character", "dollar sign"}}
-If we want to enforce that the match must span the whole string, we
-can add the markers `^` and `$`. The caret matches the start of the
-input string, whereas the dollar sign matches the end. So, `/^\d+$/`
-matches a string consisting entirely of one or more digits, `/^!/`
-matches any string that starts with an exclamation mark, and `/x^/`
-does not match any string (there cannot be an _x_ before the start of
-the string).
+If we want to enforce that the match must span the whole string, we can add the markers `^` and `$`. The caret matches the start of the input string, whereas the dollar sign matches the end. So, `/^\d+$/` matches a string consisting entirely of one or more digits, `/^!/` matches any string that starts with an exclamation mark, and `/x^/` does not match any string (there cannot be an _x_ before the start of the string).
{{index "word boundary", "word character"}}
-If, on the other hand, we just want to make sure the date starts and
-ends on a word boundary, we can use the marker `\b`. A word boundary
-can be the start or end of the string or any point in the string that
-has a word character (as in `\w`) on one side and a nonword character
-on the other.
+If, on the other hand, we just want to make sure the date starts and ends on a word boundary, we can use the marker `\b`. A word boundary can be the start or end of the string or any point in the string that has a word character (as in `\w`) on one side and a nonword character on the other.
```
console.log(/cat/.test("concatenate"));
@@ -483,22 +356,15 @@ console.log(/\bcat\b/.test("concatenate"));
{{index matching}}
-Note that a boundary marker doesn't match an actual character. It just
-enforces that the regular expression matches only when a certain
-condition holds at the place where it appears in the pattern.
+Note that a boundary marker doesn't match an actual character. It just enforces that the regular expression matches only when a certain condition holds at the place where it appears in the pattern.
## Choice patterns
{{index branching, ["regular expression", alternatives], "farm example"}}
-Say we want to know whether a piece of text contains not only a number
-but a number followed by one of the words _pig_, _cow_, or _chicken_,
-or any of their plural forms.
+Say we want to know whether a piece of text contains not only a number but a number followed by one of the words _pig_, _cow_, or _chicken_, or any of their plural forms.
-We could write three regular expressions and test them in turn, but
-there is a nicer way. The ((pipe character)) (`|`) denotes a
-((choice)) between the pattern to its left and the pattern to its
-right. So I can say this:
+We could write three regular expressions and test them in turn, but there is a nicer way. The ((pipe character)) (`|`) denotes a ((choice)) between the pattern to its left and the pattern to its right. So I can say this:
```
let animalCount = /\b\d+ (pig|cow|chicken)s?\b/;
@@ -510,38 +376,25 @@ console.log(animalCount.test("15 pigchickens"));
{{index [parentheses, "in regular expressions"]}}
-Parentheses can be used to limit the part of the pattern that the pipe
-operator applies to, and you can put multiple such operators next to
-each other to express a choice between more than two alternatives.
+Parentheses can be used to limit the part of the pattern that the pipe operator applies to, and you can put multiple such operators next to each other to express a choice between more than two alternatives.
## The mechanics of matching
{{index ["regular expression", matching], [matching, algorithm], "search problem"}}
-Conceptually, when you use `exec` or `test`, the regular expression
-engine looks for a match in your string by trying to match the
-expression first from the start of the string, then from the second
-character, and so on, until it finds a match or reaches the end of the
-string. It'll either return the first match that can be found or fail
-to find any match at all.
+Conceptually, when you use `exec` or `test`, the regular expression engine looks for a match in your string by trying to match the expression first from the start of the string, then from the second character, and so on, until it finds a match or reaches the end of the string. It'll either return the first match that can be found or fail to find any match at all.
{{index ["regular expression", matching], [matching, algorithm]}}
-To do the actual matching, the engine treats a regular expression
-something like a ((flow diagram)). This is the diagram for the
-livestock expression in the previous example:
+To do the actual matching, the engine treats a regular expression something like a ((flow diagram)). This is the diagram for the livestock expression in the previous example:
{{figure {url: "img/re_pigchickens.svg", alt: "Visualization of /\\b\\d+ (pig|cow|chicken)s?\\b/"}}}
{{index traversal}}
-Our expression matches if we can find a path from the left side of the
-diagram to the right side. We keep a current position in the string,
-and every time we move through a box, we verify that the part of the
-string after our current position matches that box.
+Our expression matches if we can find a path from the left side of the diagram to the right side. We keep a current position in the string, and every time we move through a box, we verify that the part of the string after our current position matches that box.
-So if we try to match `"the 3 pigs"` from position 4, our progress
-through the flow chart would look like this:
+So if we try to match `"the 3 pigs"` from position 4, our progress through the flow chart would look like this:
- At position 4, there is a word ((boundary)), so we can move past
the first box.
@@ -574,79 +427,39 @@ through the flow chart would look like this:
{{index ["regular expression", backtracking], "binary number", "decimal number", "hexadecimal number", "flow diagram", [matching, algorithm], backtracking}}
-The regular expression `/\b([01]+b|[\da-f]+h|\d+)\b/` matches either a
-binary number followed by a _b_, a hexadecimal number (that is, base
-16, with the letters _a_ to _f_ standing for the digits 10 to 15)
-followed by an _h_, or a regular decimal number with no suffix
-character. This is the corresponding diagram:
+The regular expression `/\b([01]+b|[\da-f]+h|\d+)\b/` matches either a binary number followed by a _b_, a hexadecimal number (that is, base 16, with the letters _a_ to _f_ standing for the digits 10 to 15) followed by an _h_, or a regular decimal number with no suffix character. This is the corresponding diagram:
{{figure {url: "img/re_number.svg", alt: "Visualization of /\\b([01]+b|\\d+|[\\da-f]+h)\\b/"}}}
{{index branching}}
-When matching this expression, it will often happen that the top
-(binary) branch is entered even though the input does not actually
-contain a binary number. When matching the string `"103"`, for
-example, it becomes clear only at the 3 that we are in the wrong
-branch. The string _does_ match the expression, just not the branch we
-are currently in.
+When matching this expression, it will often happen that the top (binary) branch is entered even though the input does not actually contain a binary number. When matching the string `"103"`, for example, it becomes clear only at the 3 that we are in the wrong branch. The string _does_ match the expression, just not the branch we are currently in.
{{index backtracking, "search problem"}}
-So the matcher _backtracks_. When entering a branch, it remembers its
-current position (in this case, at the start of the string, just past
-the first boundary box in the diagram) so that it can go back and try
-another branch if the current one does not work out. For the string
-`"103"`, after encountering the 3 character, it will start trying the
-branch for hexadecimal numbers, which fails again because there is no
-_h_ after the number. So it tries the decimal number branch. This one
-fits, and a match is reported after all.
+So the matcher _backtracks_. When entering a branch, it remembers its current position (in this case, at the start of the string, just past the first boundary box in the diagram) so that it can go back and try another branch if the current one does not work out. For the string `"103"`, after encountering the 3 character, it will start trying the branch for hexadecimal numbers, which fails again because there is no _h_ after the number. So it tries the decimal number branch. This one fits, and a match is reported after all.
{{index [matching, algorithm]}}
-The matcher stops as soon as it finds a full match. This means that if
-multiple branches could potentially match a string, only the first one
-(ordered by where the branches appear in the regular expression) is
-used.
-
-Backtracking also happens for ((repetition)) operators like + and `*`.
-If you match `/^.*x/` against `"abcxe"`, the `.*` part will first try
-to consume the whole string. The engine will then realize that it
-needs an _x_ to match the pattern. Since there is no _x_ past the end
-of the string, the star operator tries to match one character less.
-But the matcher doesn't find an _x_ after `abcx` either, so it
-backtracks again, matching the star operator to just `abc`. _Now_ it
-finds an _x_ where it needs it and reports a successful match from
-positions 0 to 4.
+The matcher stops as soon as it finds a full match. This means that if multiple branches could potentially match a string, only the first one (ordered by where the branches appear in the regular expression) is used.
+
+Backtracking also happens for ((repetition)) operators like + and `*`. If you match `/^.*x/` against `"abcxe"`, the `.*` part will first try to consume the whole string. The engine will then realize that it needs an _x_ to match the pattern. Since there is no _x_ past the end of the string, the star operator tries to match one character less. But the matcher doesn't find an _x_ after `abcx` either, so it backtracks again, matching the star operator to just `abc`. _Now_ it finds an _x_ where it needs it and reports a successful match from positions 0 to 4.
{{index performance, complexity}}
-It is possible to write regular expressions that will do a _lot_ of
-backtracking. This problem occurs when a pattern can match a piece of
-input in many different ways. For example, if we get confused while
-writing a binary-number regular expression, we might accidentally
-write something like `/([01]+)+b/`.
+It is possible to write regular expressions that will do a _lot_ of backtracking. This problem occurs when a pattern can match a piece of input in many different ways. For example, if we get confused while writing a binary-number regular expression, we might accidentally write something like `/([01]+)+b/`.
{{figure {url: "img/re_slow.svg", alt: "Visualization of /([01]+)+b/",width: "6cm"}}}
{{index "inner loop", [nesting, "in regexps"]}}
-If that tries to match some long series of zeros and ones with no
-trailing _b_ character, the matcher first goes through the inner
-loop until it runs out of digits. Then it notices there is no _b_, so
-it backtracks one position, goes through the outer loop once, and
-gives up again, trying to backtrack out of the inner loop once more.
-It will continue to try every possible route through these two loops.
-This means the amount of work _doubles_ with each additional
-character. For even just a few dozen characters, the resulting match
-will take practically forever.
+If that tries to match some long series of zeros and ones with no trailing _b_ character, the matcher first goes through the inner loop until it runs out of digits. Then it notices there is no _b_, so it backtracks one position, goes through the outer loop once, and gives up again, trying to backtrack out of the inner loop once more. It will continue to try every possible route through these two loops. This means the amount of work _doubles_ with each additional character. For even just a few dozen characters, the resulting match will take practically forever.
## The replace method
{{index "replace method", "regular expression"}}
-String values have a `replace` method that can be used to replace
-part of the string with another string.
+String values have a `replace` method that can be used to replace part of the string with another string.
```
console.log("papa".replace("p", "m"));
@@ -655,10 +468,7 @@ console.log("papa".replace("p", "m"));
{{index ["regular expression", flags], ["regular expression", global]}}
-The first argument can also be a regular expression, in which case the
-first match of the regular expression is replaced. When a `g` option
-(for _global_) is added to the regular expression, _all_ matches in
-the string will be replaced, not just the first.
+The first argument can also be a regular expression, in which case the first match of the regular expression is replaced. When a `g` option (for _global_) is added to the regular expression, _all_ matches in the string will be replaced, not just the first.
```
console.log("Borobudur".replace(/[ou]/, "a"));
@@ -669,20 +479,11 @@ console.log("Borobudur".replace(/[ou]/g, "a"));
{{index [interface, design], argument}}
-It would have been sensible if the choice between replacing one match
-or all matches was made through an additional argument to `replace` or
-by providing a different method, `replaceAll`. But for some
-unfortunate reason, the choice relies on a property of the regular
-expression instead.
+It would have been sensible if the choice between replacing one match or all matches was made through an additional argument to `replace` or by providing a different method, `replaceAll`. But for some unfortunate reason, the choice relies on a property of the regular expression instead.
{{index grouping, "capture group", "dollar sign", "replace method", ["regular expression", grouping]}}
-The real power of using regular expressions with `replace` comes from
-the fact that we can refer to matched groups in the replacement
-string. For example, say we have a big string containing the names of
-people, one name per line, in the format `Lastname, Firstname`. If we
-want to swap these names and remove the comma to get a `Firstname
-Lastname` format, we can use the following code:
+The real power of using regular expressions with `replace` comes from the fact that we can refer to matched groups in the replacement string. For example, say we have a big string containing the names of people, one name per line, in the format `Lastname, Firstname`. If we want to swap these names and remove the comma to get a `Firstname Lastname` format, we can use the following code:
```
console.log(
@@ -693,17 +494,11 @@ console.log(
// Philip Wadler
```
-The `$1` and `$2` in the replacement string refer to the parenthesized
-groups in the pattern. `$1` is replaced by the text that matched
-against the first group, `$2` by the second, and so on, up to `$9`.
-The whole match can be referred to with `$&`.
+The `$1` and `$2` in the replacement string refer to the parenthesized groups in the pattern. `$1` is replaced by the text that matched against the first group, `$2` by the second, and so on, up to `$9`. The whole match can be referred to with `$&`.
{{index [function, "higher-order"], grouping, "capture group"}}
-It is possible to pass a function—rather than a string—as the second
-argument to `replace`. For each replacement, the function will be
-called with the matched groups (as well as the whole match) as
-arguments, and its return value will be inserted into the new string.
+It is possible to pass a function—rather than a string—as the second argument to `replace`. For each replacement, the function will be called with the matched groups (as well as the whole match) as arguments, and its return value will be inserted into the new string.
Here's a small example:
@@ -731,22 +526,15 @@ console.log(stock.replace(/(\d+) (\w+)/g, minusOne));
// → no lemon, 1 cabbage, and 100 eggs
```
-This takes a string, finds all occurrences of a number followed by an
-alphanumeric word, and returns a string wherein every such occurrence
-is decremented by one.
+This takes a string, finds all occurrences of a number followed by an alphanumeric word, and returns a string wherein every such occurrence is decremented by one.
-The `(\d+)` group ends up as the `amount` argument to the function,
-and the `(\w+)` group gets bound to `unit`. The function converts
-`amount` to a number—which always works since it matched `\d+`—and
-makes some adjustments in case there is only one or zero left.
+The `(\d+)` group ends up as the `amount` argument to the function, and the `(\w+)` group gets bound to `unit`. The function converts `amount` to a number—which always works since it matched `\d+`—and makes some adjustments in case there is only one or zero left.
## Greed
{{index greed, "regular expression"}}
-It is possible to use `replace` to write a function that removes all
-((comment))s from a piece of JavaScript ((code)). Here is a first
-attempt:
+It is possible to use `replace` to write a function that removes all ((comment))s from a piece of JavaScript ((code)). Here is a first attempt:
```{test: wrap}
function stripComments(code) {
@@ -762,38 +550,17 @@ console.log(stripComments("1 /* a */+/* b */ 1"));
{{index "period character", "slash character", "newline character", "empty set", "block comment", "line comment"}}
-The part before the _or_ operator matches two slash characters
-followed by any number of non-newline characters. The part for
-multiline comments is more involved. We use `[^]` (any character that
-is not in the empty set of characters) as a way to match any
-character. We cannot just use a period here because block comments can
-continue on a new line, and the period character does not match
-newline characters.
+The part before the _or_ operator matches two slash characters followed by any number of non-newline characters. The part for multiline comments is more involved. We use `[^]` (any character that is not in the empty set of characters) as a way to match any character. We cannot just use a period here because block comments can continue on a new line, and the period character does not match newline characters.
But the output for the last line appears to have gone wrong. Why?
{{index backtracking, greed, "regular expression"}}
-The `[^]*` part of the expression, as I described in the section on
-backtracking, will first match as much as it can. If that causes the
-next part of the pattern to fail, the matcher moves back one character
-and tries again from there. In the example, the matcher first tries to
-match the whole rest of the string and then moves back from there. It
-will find an occurrence of `*/` after going back four characters and
-match that. This is not what we wanted—the intention was to match a
-single comment, not to go all the way to the end of the code and find
-the end of the last block comment.
-
-Because of this behavior, we say the repetition operators (`+`, `*`,
-`?`, and `{}`) are _((greed))y_, meaning they match as much as they
-can and backtrack from there. If you put a ((question mark)) after
-them (`+?`, `*?`, `??`, `{}?`), they become nongreedy and start by
-matching as little as possible, matching more only when the remaining
-pattern does not fit the smaller match.
-
-And that is exactly what we want in this case. By having the star
-match the smallest stretch of characters that brings us to a `*/`, we
-consume one block comment and nothing more.
+The `[^]*` part of the expression, as I described in the section on backtracking, will first match as much as it can. If that causes the next part of the pattern to fail, the matcher moves back one character and tries again from there. In the example, the matcher first tries to match the whole rest of the string and then moves back from there. It will find an occurrence of `*/` after going back four characters and match that. This is not what we wanted—the intention was to match a single comment, not to go all the way to the end of the code and find the end of the last block comment.
+
+Because of this behavior, we say the repetition operators (`+`, `*`, `?`, and `{}`) are _((greed))y_, meaning they match as much as they can and backtrack from there. If you put a ((question mark)) after them (`+?`, `*?`, `??`, `{}?`), they become nongreedy and start by matching as little as possible, matching more only when the remaining pattern does not fit the smaller match.
+
+And that is exactly what we want in this case. By having the star match the smallest stretch of characters that brings us to a `*/`, we consume one block comment and nothing more.
```{test: wrap}
function stripComments(code) {
@@ -803,24 +570,15 @@ console.log(stripComments("1 /* a */+/* b */ 1"));
// → 1 + 1
```
-A lot of ((bug))s in ((regular expression)) programs can be traced to
-unintentionally using a greedy operator where a nongreedy one would
-work better. When using a ((repetition)) operator, consider the
-nongreedy variant first.
+A lot of ((bug))s in ((regular expression)) programs can be traced to unintentionally using a greedy operator where a nongreedy one would work better. When using a ((repetition)) operator, consider the nongreedy variant first.
## Dynamically creating RegExp objects
{{index ["regular expression", creation], "underscore character", "RegExp class"}}
-There are cases where you might not know the exact ((pattern)) you
-need to match against when you are writing your code. Say you want to
-look for the user's name in a piece of text and enclose it in
-underscore characters to make it stand out. Since you will know the
-name only once the program is actually running, you can't use the
-slash-based notation.
+There are cases where you might not know the exact ((pattern)) you need to match against when you are writing your code. Say you want to look for the user's name in a piece of text and enclose it in underscore characters to make it stand out. Since you will know the name only once the program is actually running, you can't use the slash-based notation.
-But you can build up a string and use the `RegExp` ((constructor)) on
-that. Here's an example:
+But you can build up a string and use the `RegExp` ((constructor)) on that. Here's an example:
```
let name = "harry";
@@ -832,20 +590,13 @@ console.log(text.replace(regexp, "_$1_"));
{{index ["regular expression", flags], ["backslash character", "in regular expressions"]}}
-When creating the `\b` ((boundary)) markers, we have to use two
-backslashes because we are writing them in a normal string, not a
-slash-enclosed regular expression. The second argument to the `RegExp`
-constructor contains the options for the regular expression—in this
-case, `"gi"` for global and case insensitive.
+When creating the `\b` ((boundary)) markers, we have to use two backslashes because we are writing them in a normal string, not a slash-enclosed regular expression. The second argument to the `RegExp` constructor contains the options for the regular expression—in this case, `"gi"` for global and case insensitive.
-But what if the name is `"dea+hl[]rd"` because our user is a ((nerd))y
-teenager? That would result in a nonsensical regular expression that
-won't actually match the user's name.
+But what if the name is `"dea+hl[]rd"` because our user is a ((nerd))y teenager? That would result in a nonsensical regular expression that won't actually match the user's name.
{{index ["backslash character", "in regular expressions"], [escaping, "in regexps"], ["regular expression", escaping]}}
-To work around this, we can add backslashes before any character that
-has a special meaning.
+To work around this, we can add backslashes before any character that has a special meaning.
```
let name = "dea+hl[]rd";
@@ -860,10 +611,7 @@ console.log(text.replace(regexp, "_$&_"));
{{index ["regular expression", methods], "indexOf method", "search method"}}
-The `indexOf` method on strings cannot be called with a regular
-expression. But there is another method, `search`, that does expect a
-regular expression. Like `indexOf`, it returns the first index on
-which the expression was found, or -1 when it wasn't found.
+The `indexOf` method on strings cannot be called with a regular expression. But there is another method, `search`, that does expect a regular expression. Like `indexOf`, it returns the first index on which the expression was found, or -1 when it wasn't found.
```
console.log(" word".search(/\S/));
@@ -872,33 +620,21 @@ console.log(" ".search(/\S/));
// → -1
```
-Unfortunately, there is no way to indicate that the match should start
-at a given offset (like we can with the second argument to `indexOf`),
-which would often be useful.
+Unfortunately, there is no way to indicate that the match should start at a given offset (like we can with the second argument to `indexOf`), which would often be useful.
## The lastIndex property
{{index "exec method", "regular expression"}}
-The `exec` method similarly does not provide a convenient way to start
-searching from a given position in the string. But it does provide an
-*in*convenient way.
+The `exec` method similarly does not provide a convenient way to start searching from a given position in the string. But it does provide an *in*convenient way.
{{index ["regular expression", matching], matching, "source property", "lastIndex property"}}
-Regular expression objects have properties. One such property is
-`source`, which contains the string that expression was created from.
-Another property is `lastIndex`, which controls, in some limited
-circumstances, where the next match will start.
+Regular expression objects have properties. One such property is `source`, which contains the string that expression was created from. Another property is `lastIndex`, which controls, in some limited circumstances, where the next match will start.
{{index [interface, design], "exec method", ["regular expression", global]}}
-Those circumstances are that the regular expression must have the
-global (`g`) or sticky (`y`) option enabled, and the match must happen
-through the `exec` method. Again, a less confusing solution would have
-been to just allow an extra argument to be passed to `exec`, but
-confusion is an essential feature of JavaScript's regular expression
-interface.
+Those circumstances are that the regular expression must have the global (`g`) or sticky (`y`) option enabled, and the match must happen through the `exec` method. Again, a less confusing solution would have been to just allow an extra argument to be passed to `exec`, but confusion is an essential feature of JavaScript's regular expression interface.
```
let pattern = /y/g;
@@ -912,15 +648,9 @@ console.log(pattern.lastIndex);
{{index "side effect", "lastIndex property"}}
-If the match was successful, the call to `exec` automatically updates
-the `lastIndex` property to point after the match. If no match was
-found, `lastIndex` is set back to zero, which is also the value it has
-in a newly constructed regular expression object.
+If the match was successful, the call to `exec` automatically updates the `lastIndex` property to point after the match. If no match was found, `lastIndex` is set back to zero, which is also the value it has in a newly constructed regular expression object.
-The difference between the global and the sticky options is that, when
-sticky is enabled, the match will succeed only if it starts directly
-at `lastIndex`, whereas with global, it will search ahead for a
-position where a match can start.
+The difference between the global and the sticky options is that, when sticky is enabled, the match will succeed only if it starts directly at `lastIndex`, whereas with global, it will search ahead for a position where a match can start.
```
let global = /abc/g;
@@ -933,10 +663,7 @@ console.log(sticky.exec("xyz abc"));
{{index bug}}
-When using a shared regular expression value for multiple `exec`
-calls, these automatic updates to the `lastIndex` property can cause
-problems. Your regular expression might be accidentally starting at an
-index that was left over from a previous call.
+When using a shared regular expression value for multiple `exec` calls, these automatic updates to the `lastIndex` property can cause problems. Your regular expression might be accidentally starting at an index that was left over from a previous call.
```
let digit = /\d/g;
@@ -948,29 +675,20 @@ console.log(digit.exec("and now: 1"));
{{index ["regular expression", global], "match method"}}
-Another interesting effect of the global option is that it changes the
-way the `match` method on strings works. When called with a global
-expression, instead of returning an array similar to that returned by
-`exec`, `match` will find _all_ matches of the pattern in the string
-and return an array containing the matched strings.
+Another interesting effect of the global option is that it changes the way the `match` method on strings works. When called with a global expression, instead of returning an array similar to that returned by `exec`, `match` will find _all_ matches of the pattern in the string and return an array containing the matched strings.
```
console.log("Banana".match(/an/g));
// → ["an", "an"]
```
-So be cautious with global regular expressions. The cases where they
-are necessary—calls to `replace` and places where you want to
-explicitly use `lastIndex`—are typically the only places where you
-want to use them.
+So be cautious with global regular expressions. The cases where they are necessary—calls to `replace` and places where you want to explicitly use `lastIndex`—are typically the only places where you want to use them.
### Looping over matches
{{index "lastIndex property", "exec method", loop}}
-A common thing to do is to scan through all occurrences of a pattern
-in a string, in a way that gives us access to the match object in the
-loop body. We can do this by using `lastIndex` and `exec`.
+A common thing to do is to scan through all occurrences of a pattern in a string, in a way that gives us access to the match object in the loop body. We can do this by using `lastIndex` and `exec`.
```
let input = "A string with 3 numbers in it... 42 and 88.";
@@ -986,23 +704,14 @@ while (match = number.exec(input)) {
{{index "while loop", ["= operator", "as expression"], [binding, "as state"]}}
-This makes use of the fact that the value of an ((assignment))
-expression (`=`) is the assigned value. So by using `match =
-number.exec(input)` as the condition in the `while` statement, we
-perform the match at the start of each iteration, save its result in a
-binding, and stop looping when no more matches are found.
+This makes use of the fact that the value of an ((assignment)) expression (`=`) is the assigned value. So by using `match = number.exec(input)` as the condition in the `while` statement, we perform the match at the start of each iteration, save its result in a binding, and stop looping when no more matches are found.
{{id ini}}
## Parsing an INI file
{{index comment, "file format", "enemies example", "INI file"}}
-To conclude the chapter, we'll look at a problem that calls for
-((regular expression))s. Imagine we are writing a program to
-automatically collect information about our enemies from the
-((Internet)). (We will not actually write that program here, just the
-part that reads the ((configuration)) file. Sorry.) The configuration
-file looks like this:
+To conclude the chapter, we'll look at a problem that calls for ((regular expression))s. Imagine we are writing a program to automatically collect information about our enemies from the ((Internet)). (We will not actually write that program here, just the part that reads the ((configuration)) file. Sorry.) The configuration file looks like this:
```{lang: "text/plain"}
searchengine=https://duckduckgo.com/?q=$1
@@ -1023,34 +732,21 @@ outputdir=/home/marijn/enemies/davaeorn
{{index grammar}}
-The exact rules for this format (which is a widely used format,
-usually called an _INI_ file) are as follows:
+The exact rules for this format (which is a widely used format, usually called an _INI_ file) are as follows:
- Blank lines and lines starting with semicolons are ignored.
- Lines wrapped in `[` and `]` start a new ((section)).
-- Lines containing an alphanumeric identifier followed by an `=`
- character add a setting to the current section.
+- Lines containing an alphanumeric identifier followed by an `=` character add a setting to the current section.
- Anything else is invalid.
-Our task is to convert a string like this into an object whose
-properties hold strings for settings written before the first
-section header and subobjects for sections, with those subobjects
-holding the section's settings.
+Our task is to convert a string like this into an object whose properties hold strings for settings written before the first section header and subobjects for sections, with those subobjects holding the section's settings.
{{index "carriage return", "line break", "newline character"}}
-Since the format has to be processed ((line)) by line, splitting up
-the file into separate lines is a good start. We saw
-the `split` method in [Chapter ?](data#split).
-Some operating systems, however, use not just a newline character to
-separate lines but a carriage return character followed by a newline
-(`"\r\n"`). Given that the `split` method also allows a regular
-expression as its argument, we can use a regular expression like
-`/\r?\n/` to split in a way that allows both `"\n"` and `"\r\n"`
-between lines.
+Since the format has to be processed ((line)) by line, splitting up the file into separate lines is a good start. We saw the `split` method in [Chapter ?](data#split). Some operating systems, however, use not just a newline character to separate lines but a carriage return character followed by a newline (`"\r\n"`). Given that the `split` method also allows a regular expression as its argument, we can use a regular expression like `/\r?\n/` to split in a way that allows both `"\n"` and `"\r\n"` between lines.
```{startCode: true}
function parseINI(string) {
@@ -1079,68 +775,33 @@ city=Tessaloniki`));
{{index "parseINI function", parsing}}
-The code goes over the file's lines and builds up an object.
-Properties at the top are stored directly into that object, whereas
-properties found in sections are stored in a separate section object.
-The `section` binding points at the object for the current section.
+The code goes over the file's lines and builds up an object. Properties at the top are stored directly into that object, whereas properties found in sections are stored in a separate section object. The `section` binding points at the object for the current section.
-There are two kinds of significant lines—section headers or property
-lines. When a line is a regular property, it is stored in the current
-section. When it is a section header, a new section object is created,
-and `section` is set to point at it.
+There are two kinds of significant lines—section headers or property lines. When a line is a regular property, it is stored in the current section. When it is a section header, a new section object is created, and `section` is set to point at it.
{{index "caret character", "dollar sign", boundary}}
-Note the recurring use of `^` and `$` to make sure the expression
-matches the whole line, not just part of it. Leaving these out results
-in code that mostly works but behaves strangely for some input, which
-can be a difficult bug to track down.
+Note the recurring use of `^` and `$` to make sure the expression matches the whole line, not just part of it. Leaving these out results in code that mostly works but behaves strangely for some input, which can be a difficult bug to track down.
{{index "if keyword", assignment, ["= operator", "as expression"]}}
-The pattern `if (match = string.match(...))` is similar to the trick
-of using an assignment as the condition for `while`. You often aren't
-sure that your call to `match` will succeed, so you can access the
-resulting object only inside an `if` statement that tests for this. To
-not break the pleasant chain of `else if` forms, we assign the result
-of the match to a binding and immediately use that assignment as the
-test for the `if` statement.
+The pattern `if (match = string.match(...))` is similar to the trick of using an assignment as the condition for `while`. You often aren't sure that your call to `match` will succeed, so you can access the resulting object only inside an `if` statement that tests for this. To not break the pleasant chain of `else if` forms, we assign the result of the match to a binding and immediately use that assignment as the test for the `if` statement.
{{index [parentheses, "in regular expressions"]}}
-If a line is not a section header or a property, the function checks
-whether it is a comment or an empty line using the expression
-`/^\s*(;.*)?$/`. Do you see how it works? The part between the
-parentheses will match comments, and the `?` makes sure it also
-matches lines containing only whitespace. When a line doesn't match
-any of the expected forms, the function throws an exception.
+If a line is not a section header or a property, the function checks whether it is a comment or an empty line using the expression `/^\s*(;.*)?$/`. Do you see how it works? The part between the parentheses will match comments, and the `?` makes sure it also matches lines containing only whitespace. When a line doesn't match any of the expected forms, the function throws an exception.
## International characters
{{index internationalization, Unicode, ["regular expression", internationalization]}}
-Because of JavaScript's initial simplistic implementation and the fact
-that this simplistic approach was later set in stone as ((standard))
-behavior, JavaScript's regular expressions are rather dumb about
-characters that do not appear in the English language. For example, as
-far as JavaScript's regular expressions are concerned, a "((word
-character))" is only one of the 26 characters in the Latin alphabet
-(uppercase or lowercase), decimal digits, and, for some reason, the
-underscore character. Things like _é_ or _β_, which most definitely
-are word characters, will not match `\w` (and _will_ match uppercase
-`\W`, the nonword category).
+Because of JavaScript's initial simplistic implementation and the fact that this simplistic approach was later set in stone as ((standard)) behavior, JavaScript's regular expressions are rather dumb about characters that do not appear in the English language. For example, as far as JavaScript's regular expressions are concerned, a "((word character))" is only one of the 26 characters in the Latin alphabet (uppercase or lowercase), decimal digits, and, for some reason, the underscore character. Things like _é_ or _β_, which most definitely are word characters, will not match `\w` (and _will_ match uppercase `\W`, the nonword category).
{{index [whitespace, matching]}}
-By a strange historical accident, `\s` (whitespace) does not have this
-problem and matches all characters that the Unicode standard considers
-whitespace, including things like the ((nonbreaking space)) and the
-((Mongolian vowel separator)).
+By a strange historical accident, `\s` (whitespace) does not have this problem and matches all characters that the Unicode standard considers whitespace, including things like the ((nonbreaking space)) and the ((Mongolian vowel separator)).
-Another problem is that, by default, regular expressions work on code
-units, as discussed in [Chapter ?](higher_order#code_units), not
-actual characters. This means characters that are composed of two
-code units behave strangely.
+Another problem is that, by default, regular expressions work on code units, as discussed in [Chapter ?](higher_order#code_units), not actual characters. This means characters that are composed of two code units behave strangely.
```
console.log(/🍎{3}/.test("🍎🍎🍎"));
@@ -1151,22 +812,13 @@ console.log(/<.>/u.test("<🌹>"));
// → true
```
-The problem is that the 🍎 in the first line is treated as two code
-units, and the `{3}` part is applied only to the second one.
-Similarly, the dot matches a single code unit, not the two that make
-up the rose ((emoji)).
+The problem is that the 🍎 in the first line is treated as two code units, and the `{3}` part is applied only to the second one. Similarly, the dot matches a single code unit, not the two that make up the rose ((emoji)).
-You must add a `u` option (for ((Unicode))) to your regular
-expression to make it treat such characters properly. The wrong
-behavior remains the default, unfortunately, because changing that
-might cause problems for existing code that depends on it.
+You must add a `u` option (for ((Unicode))) to your regular expression to make it treat such characters properly. The wrong behavior remains the default, unfortunately, because changing that might cause problems for existing code that depends on it.
{{index "character category", [Unicode, property]}}
-Though this was only just standardized and is, at the time of writing,
-not widely supported yet, it is possible to use `\p` in a regular
-expression (that must have the Unicode option enabled) to match all
-characters to which the Unicode standard assigns a given property.
+Though this was only just standardized and is, at the time of writing, not widely supported yet, it is possible to use `\p` in a regular expression (that must have the Unicode option enabled) to match all characters to which the Unicode standard assigns a given property.
```{test: never}
console.log(/\p{Script=Greek}/u.test("α"));
@@ -1179,19 +831,13 @@ console.log(/\p{Alphabetic}/u.test("!"));
// → false
```
-Unicode defines a number of useful properties, though finding the one
-that you need may not always be trivial. You can use the
-`\p{Property=Value}` notation to match any character that has the
-given value for that property. If the property name is left off, as in
-`\p{Name}`, the name is assumed to be either a binary property such as
-`Alphabetic` or a category such as `Number`.
+Unicode defines a number of useful properties, though finding the one that you need may not always be trivial. You can use the `\p{Property=Value}` notation to match any character that has the given value for that property. If the property name is left off, as in `\p{Name}`, the name is assumed to be either a binary property such as `Alphabetic` or a category such as `Number`.
{{id summary_regexp}}
## Summary
-Regular expressions are objects that represent patterns in strings.
-They use their own language to express these patterns.
+Regular expressions are objects that represent patterns in strings. They use their own language to express these patterns.
{{table {cols: [1, 5]}}}
@@ -1214,60 +860,29 @@ They use their own language to express these patterns.
| `/^/` | Start of input
| `/$/` | End of input
-A regular expression has a method `test` to test whether a given
-string matches it. It also has a method `exec` that, when a match is
-found, returns an array containing all matched groups. Such an array
-has an `index` property that indicates where the match started.
-
-Strings have a `match` method to match them against a regular
-expression and a `search` method to search for one, returning only the
-starting position of the match. Their `replace` method can replace
-matches of a pattern with a replacement string or function.
-
-Regular expressions can have options, which are written after the
-closing slash. The `i` option makes the match case insensitive. The
-`g` option makes the expression _global_, which, among other things,
-causes the `replace` method to replace all instances instead of just
-the first. The `y` option makes it sticky, which means that it will
-not search ahead and skip part of the string when looking for a match.
-The `u` option turns on Unicode mode, which fixes a number of problems
-around the handling of characters that take up two code units.
-
-Regular expressions are a sharp ((tool)) with an awkward handle. They
-simplify some tasks tremendously but can quickly become unmanageable
-when applied to complex problems. Part of knowing how to use them is
-resisting the urge to try to shoehorn things that they cannot cleanly
-express into them.
+A regular expression has a method `test` to test whether a given string matches it. It also has a method `exec` that, when a match is found, returns an array containing all matched groups. Such an array has an `index` property that indicates where the match started.
+
+Strings have a `match` method to match them against a regular expression and a `search` method to search for one, returning only the starting position of the match. Their `replace` method can replace matches of a pattern with a replacement string or function.
+
+Regular expressions can have options, which are written after the closing slash. The `i` option makes the match case insensitive. The `g` option makes the expression _global_, which, among other things, causes the `replace` method to replace all instances instead of just the first. The `y` option makes it sticky, which means that it will not search ahead and skip part of the string when looking for a match. The `u` option turns on Unicode mode, which fixes a number of problems around the handling of characters that take up two code units.
+
+Regular expressions are a sharp ((tool)) with an awkward handle. They simplify some tasks tremendously but can quickly become unmanageable when applied to complex problems. Part of knowing how to use them is resisting the urge to try to shoehorn things that they cannot cleanly express into them.
## Exercises
{{index debugging, bug}}
-It is almost unavoidable that, in the course of working on these
-exercises, you will get confused and frustrated by some regular
-expression's inexplicable ((behavior)). Sometimes it helps to enter
-your expression into an online tool like
-[_https://debuggex.com_](https://www.debuggex.com/) to see whether its
-visualization corresponds to what you intended and to ((experiment))
-with the way it responds to various input strings.
+It is almost unavoidable that, in the course of working on these exercises, you will get confused and frustrated by some regular expression's inexplicable ((behavior)). Sometimes it helps to enter your expression into an online tool like [_https://debuggex.com_](https://www.debuggex.com/) to see whether its visualization corresponds to what you intended and to ((experiment)) with the way it responds to various input strings.
### Regexp golf
{{index "program size", "code golf", "regexp golf (exercise)"}}
-_Code golf_ is a term used for the game of trying to express a
-particular program in as few characters as possible. Similarly,
-_regexp golf_ is the practice of writing as tiny a regular expression
-as possible to match a given pattern, and _only_ that pattern.
+_Code golf_ is a term used for the game of trying to express a particular program in as few characters as possible. Similarly, _regexp golf_ is the practice of writing as tiny a regular expression as possible to match a given pattern, and _only_ that pattern.
{{index boundary, matching}}
-For each of the following items, write a ((regular expression)) to
-test whether any of the given substrings occur in a string. The
-regular expression should match only strings containing one of the
-substrings described. Do not worry about word boundaries unless
-explicitly mentioned. When your expression works, see whether you can
-make it any smaller.
+For each of the following items, write a ((regular expression)) to test whether any of the given substrings occur in a string. The regular expression should match only strings containing one of the substrings described. Do not worry about word boundaries unless explicitly mentioned. When your expression works, see whether you can make it any smaller.
1. _car_ and _cat_
2. _pop_ and _prop_
@@ -1277,8 +892,7 @@ make it any smaller.
6. A word longer than six letters
7. A word without the letter _e_ (or _E_)
-Refer to the table in the [chapter summary](regexp#summary_regexp) for
-help. Test each solution with a few test strings.
+Refer to the table in the [chapter summary](regexp#summary_regexp) for help. Test each solution with a few test strings.
{{if interactive
```
@@ -1331,16 +945,11 @@ if}}
{{index "quoting style (exercise)", "single-quote character", "double-quote character"}}
-Imagine you have written a story and used single ((quotation mark))s
-throughout to mark pieces of dialogue. Now you want to replace all the
-dialogue quotes with double quotes, while keeping the single quotes
-used in contractions like _aren't_.
+Imagine you have written a story and used single ((quotation mark))s throughout to mark pieces of dialogue. Now you want to replace all the dialogue quotes with double quotes, while keeping the single quotes used in contractions like _aren't_.
{{index "replace method"}}
-Think of a pattern that distinguishes these two
-kinds of quote usage and craft a call to the `replace` method that
-does the proper replacement.
+Think of a pattern that distinguishes these two kinds of quote usage and craft a call to the `replace` method that does the proper replacement.
{{if interactive
```{test: no}
@@ -1355,17 +964,11 @@ if}}
{{index "quoting style (exercise)", boundary}}
-The most obvious solution is to replace only quotes with a nonword
-character on at least one side—something like `/\W'|'\W/`. But you
-also have to take the start and end of the line into account.
+The most obvious solution is to replace only quotes with a nonword character on at least one side—something like `/\W'|'\W/`. But you also have to take the start and end of the line into account.
{{index grouping, "replace method", [parentheses, "in regular expressions"]}}
-In addition, you must ensure that the replacement also includes the
-characters that were matched by the `\W` pattern so that those are not
-dropped. This can be done by wrapping them in parentheses and
-including their groups in the replacement string (`$1`, `$2`). Groups
-that are not matched will be replaced by nothing.
+In addition, you must ensure that the replacement also includes the characters that were matched by the `\W` pattern so that those are not dropped. This can be done by wrapping them in parentheses and including their groups in the replacement string (`$1`, `$2`). Groups that are not matched will be replaced by nothing.
hint}}
@@ -1373,13 +976,7 @@ hint}}
{{index sign, "fractional number", [syntax, number], minus, "plus character", exponent, "scientific notation", "period character"}}
-Write an expression that matches only JavaScript-style ((number))s. It
-must support an optional minus _or_ plus sign in front of the number,
-the decimal dot, and exponent notation—`5e-3` or `1E10`—again with an
-optional sign in front of the exponent. Also note that it is not
-necessary for there to be digits in front of or after the dot, but the
-number cannot be a dot alone. That is, `.5` and `5.` are valid
-JavaScript numbers, but a lone dot _isn't_.
+Write an expression that matches only JavaScript-style ((number))s. It must support an optional minus _or_ plus sign in front of the number, the decimal dot, and exponent notation—`5e-3` or `1E10`—again with an optional sign in front of the exponent. Also note that it is not necessary for there to be digits in front of or after the dot, but the number cannot be a dot alone. That is, `.5` and `5.` are valid JavaScript numbers, but a lone dot _isn't_.
{{if interactive
```{test: no}
@@ -1409,21 +1006,14 @@ if}}
First, do not forget the backslash in front of the period.
-Matching the optional ((sign)) in front of the ((number)), as well as
-in front of the ((exponent)), can be done with `[+\-]?` or `(\+|-|)`
-(plus, minus, or nothing).
+Matching the optional ((sign)) in front of the ((number)), as well as in front of the ((exponent)), can be done with `[+\-]?` or `(\+|-|)` (plus, minus, or nothing).
{{index "pipe character"}}
-The more complicated part of the exercise is the problem of matching
-both `"5."` and `".5"` without also matching `"."`. For this, a good
-solution is to use the `|` operator to separate the two cases—either
-one or more digits optionally followed by a dot and zero or more
-digits _or_ a dot followed by one or more digits.
+The more complicated part of the exercise is the problem of matching both `"5."` and `".5"` without also matching `"."`. For this, a good solution is to use the `|` operator to separate the two cases—either one or more digits optionally followed by a dot and zero or more digits _or_ a dot followed by one or more digits.
{{index exponent, "case sensitivity", ["regular expression", flags]}}
-Finally, to make the _e_ case insensitive, either add an `i` option to
-the regular expression or use `[eE]`.
+Finally, to make the _e_ case insensitive, either add an `i` option to the regular expression or use `[eE]`.
hint}}
diff --git a/10_modules.md b/10_modules.md
index 530a29d36..6c0890b6a 100644
--- a/10_modules.md
+++ b/10_modules.md
@@ -14,181 +14,95 @@ quote}}
{{index organization, [code, "structure of"]}}
-The ideal program has a crystal-clear structure. The way it works is
-easy to explain, and each part plays a well-defined role.
+The ideal program has a crystal-clear structure. The way it works is easy to explain, and each part plays a well-defined role.
{{index "organic growth"}}
-A typical real program grows organically. New pieces of functionality
-are added as new needs come up. Structuring—and preserving
-structure—is additional work. It's work that will pay off only in the
-future, the _next_ time someone works on the program. So it is
-tempting to neglect it and allow the parts of the program to become
-deeply entangled.
+A typical real program grows organically. New pieces of functionality are added as new needs come up. Structuring—and preserving structure—is additional work. It's work that will pay off only in the future, the _next_ time someone works on the program. So it is tempting to neglect it and allow the parts of the program to become deeply entangled.
{{index readability, reuse, isolation}}
-This causes two practical issues. First, understanding such a system
-is hard. If everything can touch everything else, it is difficult to
-look at any given piece in isolation. You are forced to build up a
-holistic understanding of the entire thing. Second, if you want to
-use any of the functionality from such a program in another situation,
-rewriting it may be easier than trying to disentangle it from its
-context.
+This causes two practical issues. First, understanding such a system is hard. If everything can touch everything else, it is difficult to look at any given piece in isolation. You are forced to build up a holistic understanding of the entire thing. Second, if you want to use any of the functionality from such a program in another situation, rewriting it may be easier than trying to disentangle it from its context.
-The phrase "((big ball of mud))" is often used for such large,
-structureless programs. Everything sticks together, and when you try
-to pick out a piece, the whole thing comes apart, and your hands get
-dirty.
+The phrase "((big ball of mud))" is often used for such large, structureless programs. Everything sticks together, and when you try to pick out a piece, the whole thing comes apart, and your hands get dirty.
## Modules
{{index dependency, [interface, module]}}
-_Modules_ are an attempt to avoid these problems. A ((module)) is a
-piece of program that specifies which other pieces it relies on
-and which functionality it provides for other modules
-to use (its _interface_).
+_Modules_ are an attempt to avoid these problems. A ((module)) is a piece of program that specifies which other pieces it relies on and which functionality it provides for other modules to use (its _interface_).
{{index "big ball of mud"}}
-Module interfaces have a lot in common with object interfaces, as we
-saw them in [Chapter ?](object#interface). They make part of the
-module available to the outside world and keep the rest private. By
-restricting the ways in which modules interact with each other, the
-system becomes more like ((LEGO)), where pieces interact through
-well-defined connectors, and less like mud, where everything mixes
-with everything.
+Module interfaces have a lot in common with object interfaces, as we saw them in [Chapter ?](object#interface). They make part of the module available to the outside world and keep the rest private. By restricting the ways in which modules interact with each other, the system becomes more like ((LEGO)), where pieces interact through well-defined connectors, and less like mud, where everything mixes with everything.
{{index dependency}}
-The relations between modules are called _dependencies_. When a module
-needs a piece from another module, it is said to depend on that
-module. When this fact is clearly specified in the module itself, it
-can be used to figure out which other modules need to be present to be
-able to use a given module and to automatically load dependencies.
+The relations between modules are called _dependencies_. When a module needs a piece from another module, it is said to depend on that module. When this fact is clearly specified in the module itself, it can be used to figure out which other modules need to be present to be able to use a given module and to automatically load dependencies.
To separate modules in that way, each needs its own private ((scope)).
-Just putting your JavaScript code into different ((file))s does not
-satisfy these requirements. The files still share the same global
-namespace. They can, intentionally or accidentally, interfere with
-each other's bindings. And the dependency structure remains unclear.
-We can do better, as we'll see later in the chapter.
+Just putting your JavaScript code into different ((file))s does not satisfy these requirements. The files still share the same global namespace. They can, intentionally or accidentally, interfere with each other's bindings. And the dependency structure remains unclear. We can do better, as we'll see later in the chapter.
{{index design}}
-Designing a fitting module structure for a program can be difficult.
-In the phase where you are still exploring the problem, trying
-different things to see what works, you might want to not worry about
-it too much since it can be a big distraction. Once you have
-something that feels solid, that's a good time to take a step back and
-organize it.
+Designing a fitting module structure for a program can be difficult. In the phase where you are still exploring the problem, trying different things to see what works, you might want to not worry about it too much since it can be a big distraction. Once you have something that feels solid, that's a good time to take a step back and organize it.
## Packages
{{index bug, dependency, structure, reuse}}
-One of the advantages of building a program out of separate pieces,
-and being actually able to run those pieces on their own, is that you
-might be able to apply the same piece in different programs.
+One of the advantages of building a program out of separate pieces, and being actually able to run those pieces on their own, is that you might be able to apply the same piece in different programs.
{{index "parseINI function"}}
-But how do you set this up? Say I want to use the `parseINI` function
-from [Chapter ?](regexp#ini) in another program. If it is clear what
-the function depends on (in this case, nothing), I can just copy all the
-necessary code into my new project and use it. But then, if I find a
-mistake in that code, I'll probably fix it in whichever program
-I'm working with at the time and forget to also fix it in the other
-program.
+But how do you set this up? Say I want to use the `parseINI` function from [Chapter ?](regexp#ini) in another program. If it is clear what the function depends on (in this case, nothing), I can just copy all the necessary code into my new project and use it. But then, if I find a mistake in that code, I'll probably fix it in whichever program I'm working with at the time and forget to also fix it in the other program.
{{index duplication, "copy-paste programming"}}
-Once you start duplicating code, you'll quickly find yourself wasting
-time and energy moving copies around and keeping them up-to-date.
+Once you start duplicating code, you'll quickly find yourself wasting time and energy moving copies around and keeping them up-to-date.
-That's where _((package))s_ come in. A package is a chunk of code that
-can be distributed (copied and installed). It may contain one or more
-modules and has information about which other packages it depends on.
-A package also usually comes with documentation explaining what it
-does so that people who didn't write it might still be able to use
-it.
+That's where _((package))s_ come in. A package is a chunk of code that can be distributed (copied and installed). It may contain one or more modules and has information about which other packages it depends on. A package also usually comes with documentation explaining what it does so that people who didn't write it might still be able to use it.
-When a problem is found in a package or a new feature is added, the
-package is updated. Now the programs that depend on it (which may also
-be packages) can upgrade to the new ((version)).
+When a problem is found in a package or a new feature is added, the package is updated. Now the programs that depend on it (which may also be packages) can upgrade to the new ((version)).
{{id modules_npm}}
{{index installation, upgrading, "package manager", download, reuse}}
-Working in this way requires ((infrastructure)). We need a place to
-store and find packages and a convenient way to install and upgrade
-them. In the JavaScript world, this infrastructure is provided by
-((NPM)) ([_https://npmjs.org_](https://npmjs.org)).
+Working in this way requires ((infrastructure)). We need a place to store and find packages and a convenient way to install and upgrade them. In the JavaScript world, this infrastructure is provided by ((NPM)) ([_https://npmjs.org_](https://npmjs.org)).
-NPM is two things: an online service where one can download (and
-upload) packages and a program (bundled with Node.js) that helps you
-install and manage them.
+NPM is two things: an online service where one can download (and upload) packages and a program (bundled with Node.js) that helps you install and manage them.
{{index "ini package"}}
-At the time of writing, there are more than half a million different
-packages available on NPM. A large portion of those are rubbish, I
-should mention, but almost every useful, publicly available package
-can be found on there. For example, an INI file parser, similar to the
-one we built in [Chapter ?](regexp), is available under the package
-name `ini`.
+At the time of writing, there are more than half a million different packages available on NPM. A large portion of those are rubbish, I should mention, but almost every useful, publicly available package can be found on there. For example, an INI file parser, similar to the one we built in [Chapter ?](regexp), is available under the package name `ini`.
{{index "command line"}}
-[Chapter ?](node) will show how to install such packages locally using
-the `npm` command line program.
+[Chapter ?](node) will show how to install such packages locally using the `npm` command line program.
-Having quality packages available for download is extremely valuable.
-It means that we can often avoid reinventing a program that 100
-people have written before and get a solid, well-tested
-implementation at the press of a few keys.
+Having quality packages available for download is extremely valuable. It means that we can often avoid reinventing a program that 100 people have written before and get a solid, well-tested implementation at the press of a few keys.
{{index maintenance}}
-Software is cheap to copy, so once someone has written it,
-distributing it to other people is an efficient process. But writing
-it in the first place _is_ work, and responding to people who have
-found problems in the code, or who want to propose new features, is
-even more work.
-
-By default, you own the ((copyright)) to the code you write, and other
-people may use it only with your permission. But because some people
-are just nice and because publishing good software can help make you
-a little bit famous among programmers, many packages are published
-under a ((license)) that explicitly allows other people to use it.
-
-Most code on ((NPM)) is licensed this way. Some licenses require you
-to also publish code that you build on top of the package under the
-same license. Others are less demanding, just requiring that you keep
-the license with the code as you distribute it. The JavaScript
-community mostly uses the latter type of license. When using other
-people's packages, make sure you are aware of their license.
+Software is cheap to copy, so once someone has written it, distributing it to other people is an efficient process. But writing it in the first place _is_ work, and responding to people who have found problems in the code, or who want to propose new features, is even more work.
+
+By default, you own the ((copyright)) to the code you write, and other people may use it only with your permission. But because some people are just nice and because publishing good software can help make you a little bit famous among programmers, many packages are published under a ((license)) that explicitly allows other people to use it.
+
+Most code on ((NPM)) is licensed this way. Some licenses require you to also publish code that you build on top of the package under the same license. Others are less demanding, just requiring that you keep the license with the code as you distribute it. The JavaScript community mostly uses the latter type of license. When using other people's packages, make sure you are aware of their license.
## Improvised modules
-Until 2015, the JavaScript language had no built-in module system.
-Yet people had been building large systems in JavaScript for more than a decade, and they _needed_ ((module))s.
+Until 2015, the JavaScript language had no built-in module system. Yet people had been building large systems in JavaScript for more than a decade, and they _needed_ ((module))s.
{{index [function, scope], [interface, module], [object, as module]}}
-So they designed their own ((module system))s on top of the language.
-You can use JavaScript functions to create local scopes and
-objects to represent module interfaces.
+So they designed their own ((module system))s on top of the language. You can use JavaScript functions to create local scopes and objects to represent module interfaces.
{{index "Date class", "weekDay module"}}
-This is a module for going between day names and numbers (as returned
-by `Date`'s `getDay` method). Its interface consists of `weekDay.name`
-and `weekDay.number`, and it hides its local binding `names` inside
-the scope of a function expression that is immediately invoked.
+This is a module for going between day names and numbers (as returned by `Date`'s `getDay` method). Its interface consists of `weekDay.name` and `weekDay.number`, and it hides its local binding `names` inside the scope of a function expression that is immediately invoked.
```
const weekDay = function() {
@@ -206,15 +120,9 @@ console.log(weekDay.name(weekDay.number("Sunday")));
{{index dependency, [interface, module]}}
-This style of modules provides ((isolation)), to a certain degree, but
-it does not declare dependencies. Instead, it just puts its
-interface into the ((global scope)) and expects its dependencies,
-if any, to do the same. For a long time this was the main approach
-used in web programming, but it is mostly obsolete now.
+This style of modules provides ((isolation)), to a certain degree, but it does not declare dependencies. Instead, it just puts its interface into the ((global scope)) and expects its dependencies, if any, to do the same. For a long time this was the main approach used in web programming, but it is mostly obsolete now.
-If we want to make dependency relations part of the code, we'll have
-to take control of loading dependencies. Doing that requires being
-able to execute strings as code. JavaScript can do this.
+If we want to make dependency relations part of the code, we'll have to take control of loading dependencies. Doing that requires being able to execute strings as code. JavaScript can do this.
{{id eval}}
@@ -222,16 +130,11 @@ able to execute strings as code. JavaScript can do this.
{{index evaluation, interpretation}}
-There are several ways to take data (a string of code) and run it as
-part of the current program.
+There are several ways to take data (a string of code) and run it as part of the current program.
{{index isolation, eval}}
-The most obvious way is the special operator `eval`, which will
-execute a string in the _current_ ((scope)). This is usually a bad idea
-because it breaks some of the properties that scopes normally have,
-such as it being easily predictable which binding a given name refers
-to.
+The most obvious way is the special operator `eval`, which will execute a string in the _current_ ((scope)). This is usually a bad idea because it breaks some of the properties that scopes normally have, such as it being easily predictable which binding a given name refers to.
```
const x = 1;
@@ -248,11 +151,7 @@ console.log(x);
{{index "Function constructor"}}
-A less scary way of interpreting data as code is to use the `Function`
-constructor. It takes two arguments: a string containing a
-comma-separated list of argument names and a string containing the
-function body. It wraps the code in a function value so that it gets
-its own scope and won't do odd things with other scopes.
+A less scary way of interpreting data as code is to use the `Function` constructor. It takes two arguments: a string containing a comma-separated list of argument names and a string containing the function body. It wraps the code in a function value so that it gets its own scope and won't do odd things with other scopes.
```
let plusOne = Function("n", "return n + 1;");
@@ -260,9 +159,7 @@ console.log(plusOne(4));
// → 5
```
-This is precisely what we need for a module system. We can wrap the
-module's code in a function and use that function's scope as module
-((scope)).
+This is precisely what we need for a module system. We can wrap the module's code in a function and use that function's scope as module ((scope)).
## CommonJS
@@ -270,35 +167,21 @@ module's code in a function and use that function's scope as module
{{index "CommonJS modules"}}
-The most widely used approach to bolted-on JavaScript modules is
-called _CommonJS modules_. ((Node.js)) uses it and is the system used
-by most packages on ((NPM)).
+The most widely used approach to bolted-on JavaScript modules is called _CommonJS modules_. ((Node.js)) uses it and is the system used by most packages on ((NPM)).
{{index "require function", [interface, module]}}
-The main concept in CommonJS modules is a function called `require`.
-When you call this with the module name of a dependency, it makes sure
-the module is loaded and returns its interface.
+The main concept in CommonJS modules is a function called `require`. When you call this with the module name of a dependency, it makes sure the module is loaded and returns its interface.
{{index "exports object"}}
-Because the loader wraps the module code in a function, modules
-automatically get their own local scope. All they have to
-do is call `require` to access their dependencies and put their
-interface in the object bound to `exports`.
+Because the loader wraps the module code in a function, modules automatically get their own local scope. All they have to do is call `require` to access their dependencies and put their interface in the object bound to `exports`.
{{index "formatDate module", "Date class", "ordinal package", "date-names package"}}
-This example module provides a date-formatting function. It uses two
-((package))s from NPM—`ordinal` to convert numbers to strings like
-`"1st"` and `"2nd"`, and `date-names` to get the English names for
-weekdays and months. It exports a single function, `formatDate`, which
-takes a `Date` object and a ((template)) string.
+This example module provides a date-formatting function. It uses two ((package))s from NPM—`ordinal` to convert numbers to strings like `"1st"` and `"2nd"`, and `date-names` to get the English names for weekdays and months. It exports a single function, `formatDate`, which takes a `Date` object and a ((template)) string.
-The template string may contain codes that direct the format, such as
-`YYYY` for the full year and `Do` for the ordinal day of the month.
-You could give it a string like `"MMMM Do YYYY"` to get output like
-"November 22nd 2017".
+The template string may contain codes that direct the format, such as `YYYY` for the full year and `Do` for the ordinal day of the month. You could give it a string like `"MMMM Do YYYY"` to get output like "November 22nd 2017".
```
const ordinal = require("ordinal");
@@ -318,13 +201,9 @@ exports.formatDate = function(date, format) {
{{index "destructuring binding"}}
-The interface of `ordinal` is a single function, whereas `date-names`
-exports an object containing multiple things—`days` and `months` are
-arrays of names. Destructuring is very convenient when creating
-bindings for imported interfaces.
+The interface of `ordinal` is a single function, whereas `date-names` exports an object containing multiple things—`days` and `months` are arrays of names. Destructuring is very convenient when creating bindings for imported interfaces.
-The module adds its interface function to `exports` so that modules
-that depend on it get access to it. We could use the module like this:
+The module adds its interface function to `exports` so that modules that depend on it get access to it. We could use the module like this:
```
const {formatDate} = require("./format-date");
@@ -357,53 +236,29 @@ function require(name) {
{{index [file, access]}}
-In this code, `readFile` is a made-up function that reads a file and
-returns its contents as a string. Standard JavaScript provides no such
-functionality—but different JavaScript environments, such as the
-browser and Node.js, provide their own ways of accessing files.
-The example just pretends that `readFile` exists.
+In this code, `readFile` is a made-up function that reads a file and returns its contents as a string. Standard JavaScript provides no such functionality—but different JavaScript environments, such as the browser and Node.js, provide their own ways of accessing files. The example just pretends that `readFile` exists.
{{index cache, "Function constructor"}}
-To avoid loading the same module multiple times, `require` keeps a
-store (cache) of already loaded modules. When called, it first checks
-if the requested module has been loaded and, if not, loads it. This
-involves reading the module's code, wrapping it in a function, and
-calling it.
+To avoid loading the same module multiple times, `require` keeps a store (cache) of already loaded modules. When called, it first checks if the requested module has been loaded and, if not, loads it. This involves reading the module's code, wrapping it in a function, and calling it.
{{index "ordinal package", "exports object", "module object", [interface, module]}}
-The interface of the `ordinal` package we saw before is not an
-object but a function. A quirk of the CommonJS modules is that,
-though the module system will create an empty interface object for you
-(bound to `exports`), you can replace that with any value by
-overwriting `module.exports`. This is done by many modules to export a
-single value instead of an interface object.
+The interface of the `ordinal` package we saw before is not an object but a function. A quirk of the CommonJS modules is that, though the module system will create an empty interface object for you (bound to `exports`), you can replace that with any value by overwriting `module.exports`. This is done by many modules to export a single value instead of an interface object.
-By defining `require`, `exports`, and `module` as ((parameter))s for
-the generated wrapper function (and passing the appropriate values
-when calling it), the loader makes sure that these bindings are
-available in the module's ((scope)).
+By defining `require`, `exports`, and `module` as ((parameter))s for the generated wrapper function (and passing the appropriate values when calling it), the loader makes sure that these bindings are available in the module's ((scope)).
{{index resolution, "relative path"}}
-The way the string given to `require` is translated to an actual
-filename or web address differs in different systems. When it starts with
-`"./"` or `"../"`, it is generally interpreted as relative to the
-current module's filename. So `"./format-date"` would be the file
-named `format-date.js` in the same directory.
+The way the string given to `require` is translated to an actual filename or web address differs in different systems. When it starts with `"./"` or `"../"`, it is generally interpreted as relative to the current module's filename. So `"./format-date"` would be the file named `format-date.js` in the same directory.
-When the name isn't relative, Node.js will look for an installed
-package by that name. In the example code in this chapter, we'll
-interpret such names as referring to NPM packages. We'll go into more
-detail on how to install and use NPM modules in [Chapter ?](node).
+When the name isn't relative, Node.js will look for an installed package by that name. In the example code in this chapter, we'll interpret such names as referring to NPM packages. We'll go into more detail on how to install and use NPM modules in [Chapter ?](node).
{{id modules_ini}}
{{index "ini package"}}
-Now, instead of writing our own INI file parser, we can use one from
-((NPM)).
+Now, instead of writing our own INI file parser, we can use one from ((NPM)).
```
const {parse} = require("ini");
@@ -414,29 +269,17 @@ console.log(parse("x = 10\ny = 20"));
## ECMAScript modules
-((CommonJS modules)) work quite well and, in combination with NPM,
-have allowed the JavaScript community to start sharing code on a large
-scale.
+((CommonJS modules)) work quite well and, in combination with NPM, have allowed the JavaScript community to start sharing code on a large scale.
{{index "exports object", linter}}
-But they remain a bit of a duct-tape ((hack)). The ((notation)) is
-slightly awkward—the things you add to `exports` are not available in
-the local ((scope)), for example. And because `require` is a normal
-function call taking any kind of argument, not just a string literal,
-it can be hard to determine the dependencies of a module without
-running its code.
+But they remain a bit of a duct-tape ((hack)). The ((notation)) is slightly awkward—the things you add to `exports` are not available in the local ((scope)), for example. And because `require` is a normal function call taking any kind of argument, not just a string literal, it can be hard to determine the dependencies of a module without running its code.
{{index "import keyword", dependency, "ES modules"}}
{{id es}}
-This is why the JavaScript standard from 2015 introduces its own,
-different module system. It is usually called _((ES modules))_, where
-_ES_ stands for ((ECMAScript)). The main concepts of dependencies and
-interfaces remain the same, but the details differ. For one thing, the
-notation is now integrated into the language. Instead of calling a
-function to access a dependency, you use a special `import` keyword.
+This is why the JavaScript standard from 2015 introduces its own, different module system. It is usually called _((ES modules))_, where _ES_ stands for ((ECMAScript)). The main concepts of dependencies and interfaces remain the same, but the details differ. For one thing, the notation is now integrated into the language. Instead of calling a function to access a dependency, you use a special `import` keyword.
```
import ordinal from "ordinal";
@@ -447,29 +290,17 @@ export function formatDate(date, format) { /* ... */ }
{{index "export keyword", "formatDate module"}}
-Similarly, the `export` keyword is used to export things. It may
-appear in front of a function, class, or binding definition (`let`,
-`const`, or `var`).
+Similarly, the `export` keyword is used to export things. It may appear in front of a function, class, or binding definition (`let`, `const`, or `var`).
{{index [binding, exported]}}
-An ES module's interface is not a single value but a set of named
-bindings. The preceding module binds `formatDate` to a function. When
-you import from another module, you import the _binding_, not the
-value, which means an exporting module may change the value of the
-binding at any time, and the modules that import it will see its new
-value.
+An ES module's interface is not a single value but a set of named bindings. The preceding module binds `formatDate` to a function. When you import from another module, you import the _binding_, not the value, which means an exporting module may change the value of the binding at any time, and the modules that import it will see its new value.
{{index "default export"}}
-When there is a binding named `default`, it is treated as the module's
-main exported value. If you import a module like `ordinal` in the
-example, without braces around the binding name, you get its `default`
-binding. Such modules can still export other bindings under different
-names alongside their `default` export.
+When there is a binding named `default`, it is treated as the module's main exported value. If you import a module like `ordinal` in the example, without braces around the binding name, you get its `default` binding. Such modules can still export other bindings under different names alongside their `default` export.
-To create a default export, you write `export default` before an
-expression, a function declaration, or a class declaration.
+To create a default export, you write `export default` before an expression, a function declaration, or a class declaration.
```
export default ["Winter", "Spring", "Summer", "Autumn"];
@@ -484,167 +315,71 @@ console.log(dayNames.length);
// → 7
```
-Another important difference is that ES module imports happen before
-a module's script starts running. That means `import` declarations
-may not appear inside functions or blocks, and the names of
-dependencies must be quoted strings, not arbitrary expressions.
+Another important difference is that ES module imports happen before a module's script starts running. That means `import` declarations may not appear inside functions or blocks, and the names of dependencies must be quoted strings, not arbitrary expressions.
-At the time of writing, the JavaScript community is in the process of
-adopting this module style. But it has been a slow process. It took
-a few years, after the format was specified, for browsers and Node.js
-to start supporting it. And though they mostly support it now, this
-support still has issues, and the discussion on how such modules
-should be distributed through ((NPM)) is still ongoing.
+At the time of writing, the JavaScript community is in the process of adopting this module style. But it has been a slow process. It took a few years, after the format was specified, for browsers and Node.js to start supporting it. And though they mostly support it now, this support still has issues, and the discussion on how such modules should be distributed through ((NPM)) is still ongoing.
-Many projects are written using ES modules and then automatically
-converted to some other format when published. We are in a
-transitional period in which two different module systems are used
-side by side, and it is useful to be able to read and write code in
-either of them.
+Many projects are written using ES modules and then automatically converted to some other format when published. We are in a transitional period in which two different module systems are used side by side, and it is useful to be able to read and write code in either of them.
## Building and bundling
{{index compilation, "type checking"}}
-In fact, many JavaScript projects aren't even, technically, written in
-JavaScript. There are extensions, such as the type checking
-((dialect)) mentioned in [Chapter ?](error#typing), that are widely
-used. People also often start using planned extensions to the language
-long before they have been added to the platforms that actually run
-JavaScript.
+In fact, many JavaScript projects aren't even, technically, written in JavaScript. There are extensions, such as the type checking ((dialect)) mentioned in [Chapter ?](error#typing), that are widely used. People also often start using planned extensions to the language long before they have been added to the platforms that actually run JavaScript.
-To make this possible, they _compile_ their code, translating it from
-their chosen JavaScript dialect to plain old JavaScript—or even to a
-past version of JavaScript—so that old ((browsers)) can run it.
+To make this possible, they _compile_ their code, translating it from their chosen JavaScript dialect to plain old JavaScript—or even to a past version of JavaScript—so that old ((browsers)) can run it.
{{index latency, performance, [file, access], [network, speed]}}
-Including a modular program that consists of 200 different
-files in a ((web page)) produces its own problems. If fetching a
-single file over the network takes 50 milliseconds, loading
-the whole program takes 10 seconds, or maybe half that if you can
-load several files simultaneously. That's a lot of wasted time.
-Because fetching a single big file tends to be faster than fetching a
-lot of tiny ones, web programmers have started using tools that roll
-their programs (which they painstakingly split into modules) back into
-a single big file before they publish it to the Web. Such tools are
-called _((bundler))s_.
+Including a modular program that consists of 200 different files in a ((web page)) produces its own problems. If fetching a single file over the network takes 50 milliseconds, loading the whole program takes 10 seconds, or maybe half that if you can load several files simultaneously. That's a lot of wasted time. Because fetching a single big file tends to be faster than fetching a lot of tiny ones, web programmers have started using tools that roll their programs (which they painstakingly split into modules) back into a single big file before they publish it to the Web. Such tools are called _((bundler))s_.
{{index "file size"}}
-And we can go further. Apart from the number of files, the _size_ of
-the files also determines how fast they can be transferred over the
-network. Thus, the JavaScript community has invented _((minifier))s_.
-These are tools that take a JavaScript program and make it smaller by
-automatically removing comments and whitespace, renaming bindings, and
-replacing pieces of code with equivalent code that take up less space.
+And we can go further. Apart from the number of files, the _size_ of the files also determines how fast they can be transferred over the network. Thus, the JavaScript community has invented _((minifier))s_. These are tools that take a JavaScript program and make it smaller by automatically removing comments and whitespace, renaming bindings, and replacing pieces of code with equivalent code that take up less space.
{{index pipeline, tool}}
-So it is not uncommon for the code that you find in an NPM package or
-that runs on a web page to have gone through _multiple_ stages of
-transformation—converted from modern JavaScript to historic
-JavaScript, from ES module format to CommonJS, bundled, and minified.
-We won't go into the details of these tools in this book since they
-tend to be boring and change rapidly. Just be aware that the
-JavaScript code you run is often not the code as it was written.
+So it is not uncommon for the code that you find in an NPM package or that runs on a web page to have gone through _multiple_ stages of transformation—converted from modern JavaScript to historic JavaScript, from ES module format to CommonJS, bundled, and minified. We won't go into the details of these tools in this book since they tend to be boring and change rapidly. Just be aware that the JavaScript code you run is often not the code as it was written.
## Module design
{{index [module, design], [interface, module], [code, "structure of"]}}
-Structuring programs is one of the subtler aspects of programming. Any
-nontrivial piece of functionality can be modeled in various ways.
+Structuring programs is one of the subtler aspects of programming. Any nontrivial piece of functionality can be modeled in various ways.
-Good program design is subjective—there are trade-offs involved and
-matters of taste. The best way to learn the value of well-structured
-design is to read or work on a lot of programs and notice what works
-and what doesn't. Don't assume that a painful mess is "just the way it
-is". You can improve the structure of almost everything by putting
-more thought into it.
+Good program design is subjective—there are trade-offs involved and matters of taste. The best way to learn the value of well-structured design is to read or work on a lot of programs and notice what works and what doesn't. Don't assume that a painful mess is "just the way it is". You can improve the structure of almost everything by putting more thought into it.
{{index [interface, module]}}
-One aspect of module design is ease of use. If you are designing
-something that is intended to be used by multiple people—or even by
-yourself, in three months when you no longer remember the specifics of
-what you did—it is helpful if your interface is simple and
-predictable.
+One aspect of module design is ease of use. If you are designing something that is intended to be used by multiple people—or even by yourself, in three months when you no longer remember the specifics of what you did—it is helpful if your interface is simple and predictable.
{{index "ini package", JSON}}
-That may mean following existing conventions. A good example is the
-`ini` package. This module imitates the standard `JSON` object by
-providing `parse` and `stringify` (to write an INI file) functions,
-and, like `JSON`, converts between strings and plain objects. So the
-interface is small and familiar, and after you've worked with it once,
-you're likely to remember how to use it.
+That may mean following existing conventions. A good example is the `ini` package. This module imitates the standard `JSON` object by providing `parse` and `stringify` (to write an INI file) functions, and, like `JSON`, converts between strings and plain objects. So the interface is small and familiar, and after you've worked with it once, you're likely to remember how to use it.
{{index "side effect", "hard disk", composability}}
-Even if there's no standard function or widely used package to
-imitate, you can keep your modules predictable by using simple ((data
-structure))s and doing a single, focused thing. Many of the INI-file
-parsing modules on NPM provide a function that directly reads such a
-file from the hard disk and parses it, for example. This makes it
-impossible to use such modules in the browser, where we don't have
-direct file system access, and adds complexity that would have been
-better addressed by _composing_ the module with some file-reading
-function.
+Even if there's no standard function or widely used package to imitate, you can keep your modules predictable by using simple ((data structure))s and doing a single, focused thing. Many of the INI-file parsing modules on NPM provide a function that directly reads such a file from the hard disk and parses it, for example. This makes it impossible to use such modules in the browser, where we don't have direct file system access, and adds complexity that would have been better addressed by _composing_ the module with some file-reading function.
{{index "pure function"}}
-This points to another helpful aspect of module design—the ease with
-which something can be composed with other code. Focused modules that
-compute values are applicable in a wider range of programs than bigger
-modules that perform complicated actions with side effects. An INI
-file reader that insists on reading the file from disk is useless in a
-scenario where the file's content comes from some other source.
+This points to another helpful aspect of module design—the ease with which something can be composed with other code. Focused modules that compute values are applicable in a wider range of programs than bigger modules that perform complicated actions with side effects. An INI file reader that insists on reading the file from disk is useless in a scenario where the file's content comes from some other source.
{{index "object-oriented programming"}}
-Relatedly, stateful objects are sometimes useful or even necessary,
-but if something can be done with a function, use a function. Several
-of the INI file readers on NPM provide an interface style that
-requires you to first create an object, then load the file into your
-object, and finally use specialized methods to get at the results.
-This type of thing is common in the object-oriented tradition, and
-it's terrible. Instead of making a single function call and moving on,
-you have to perform the ritual of moving your object through various
-states. And because the data is now wrapped in a specialized object
-type, all code that interacts with it has to know about that type,
-creating unnecessary interdependencies.
-
-Often defining new data structures can't be avoided—only a few
-basic ones are provided by the language standard, and many types of
-data have to be more complex than an array or a map. But when an
-array suffices, use an array.
-
-An example of a slightly more complex data structure is the graph from
-[Chapter ?](robot). There is no single obvious way to represent a
-((graph)) in JavaScript. In that chapter, we used an object whose
-properties hold arrays of strings—the other nodes reachable from that
-node.
-
-There are several different pathfinding packages on ((NPM)), but none
-of them uses this graph format. They usually allow the graph's edges to
-have a weight, which is the cost or distance associated with it. That isn't
-possible in our representation.
+Relatedly, stateful objects are sometimes useful or even necessary, but if something can be done with a function, use a function. Several of the INI file readers on NPM provide an interface style that requires you to first create an object, then load the file into your object, and finally use specialized methods to get at the results. This type of thing is common in the object-oriented tradition, and it's terrible. Instead of making a single function call and moving on, you have to perform the ritual of moving your object through various states. And because the data is now wrapped in a specialized object type, all code that interacts with it has to know about that type, creating unnecessary interdependencies.
+
+Often defining new data structures can't be avoided—only a few basic ones are provided by the language standard, and many types of data have to be more complex than an array or a map. But when an array suffices, use an array.
+
+An example of a slightly more complex data structure is the graph from [Chapter ?](robot). There is no single obvious way to represent a ((graph)) in JavaScript. In that chapter, we used an object whose properties hold arrays of strings—the other nodes reachable from that node.
+
+There are several different pathfinding packages on ((NPM)), but none of them uses this graph format. They usually allow the graph's edges to have a weight, which is the cost or distance associated with it. That isn't possible in our representation.
{{index "Dijkstra, Edsger", pathfinding, "Dijkstra's algorithm", "dijkstrajs package"}}
-For example, there's the `dijkstrajs` package. A well-known approach
-to pathfinding, quite similar to our `findRoute` function, is called
-_Dijkstra's algorithm_, after Edsger Dijkstra, who first wrote it
-down. The `js` suffix is often added to package names to indicate the
-fact that they are written in JavaScript. This `dijkstrajs` package
-uses a graph format similar to ours, but instead of arrays, it uses
-objects whose property values are numbers—the weights of the edges.
+For example, there's the `dijkstrajs` package. A well-known approach to pathfinding, quite similar to our `findRoute` function, is called _Dijkstra's algorithm_, after Edsger Dijkstra, who first wrote it down. The `js` suffix is often added to package names to indicate the fact that they are written in JavaScript. This `dijkstrajs` package uses a graph format similar to ours, but instead of arrays, it uses objects whose property values are numbers—the weights of the edges.
-So if we wanted to use that package, we'd have to make sure that our
-graph was stored in the format it expects. All edges get the same
-weight since our simplified model treats each road as having the
-same cost (one turn).
+So if we wanted to use that package, we'd have to make sure that our graph was stored in the format it expects. All edges get the same weight since our simplified model treats each road as having the same cost (one turn).
```
const {find_path} = require("dijkstrajs");
@@ -661,27 +396,15 @@ console.log(find_path(graph, "Post Office", "Cabin"));
// → ["Post Office", "Alice's House", "Cabin"]
```
-This can be a barrier to composition—when various packages are using
-different data structures to describe similar things, combining them
-is difficult. Therefore, if you want to design for composability,
-find out what ((data structure))s other people are using and, when
-possible, follow their example.
+This can be a barrier to composition—when various packages are using different data structures to describe similar things, combining them is difficult. Therefore, if you want to design for composability, find out what ((data structure))s other people are using and, when possible, follow their example.
## Summary
-Modules provide structure to bigger programs by separating the code
-into pieces with clear interfaces and dependencies. The interface is
-the part of the module that's visible from other modules, and the
-dependencies are the other modules that it makes use of.
+Modules provide structure to bigger programs by separating the code into pieces with clear interfaces and dependencies. The interface is the part of the module that's visible from other modules, and the dependencies are the other modules that it makes use of.
-Because JavaScript historically did not provide a module system, the
-CommonJS system was built on top of it. Then at some point it _did_ get
-a built-in system, which now coexists uneasily with the CommonJS
-system.
+Because JavaScript historically did not provide a module system, the CommonJS system was built on top of it. Then at some point it _did_ get a built-in system, which now coexists uneasily with the CommonJS system.
-A package is a chunk of code that can be distributed on its own. NPM
-is a repository of JavaScript packages. You can download all kinds of
-useful (and useless) packages from it.
+A package is a chunk of code that can be distributed on its own. NPM is a repository of JavaScript packages. You can download all kinds of useful (and useless) packages from it.
## Exercises
@@ -691,8 +414,7 @@ useful (and useless) packages from it.
{{id modular_robot}}
-These are the bindings that the project from [Chapter ?](robot)
-creates:
+These are the bindings that the project from [Chapter ?](robot) creates:
```{lang: "text/plain"}
roads
@@ -708,80 +430,35 @@ findRoute
goalOrientedRobot
```
-If you were to write that project as a modular program, what modules
-would you create? Which module would depend on which other module, and
-what would their interfaces look like?
+If you were to write that project as a modular program, what modules would you create? Which module would depend on which other module, and what would their interfaces look like?
-Which pieces are likely to be available prewritten on NPM? Would you
-prefer to use an NPM package or write them yourself?
+Which pieces are likely to be available prewritten on NPM? Would you prefer to use an NPM package or write them yourself?
{{hint
{{index "modular robot (exercise)"}}
-Here's what I would have done (but again, there is no single _right_
-way to design a given module):
+Here's what I would have done (but again, there is no single _right_ way to design a given module):
{{index "dijkstrajs package"}}
-The code used to build the road graph lives in the `graph` module.
-Because I'd rather use `dijkstrajs` from NPM than our own pathfinding
-code, we'll make this build the kind of graph data that `dijkstrajs`
-expects. This module exports a single function, `buildGraph`. I'd have
-`buildGraph` accept an array of two-element arrays, rather than
-strings containing hyphens, to make the module less dependent on the
-input format.
+The code used to build the road graph lives in the `graph` module. Because I'd rather use `dijkstrajs` from NPM than our own pathfinding code, we'll make this build the kind of graph data that `dijkstrajs` expects. This module exports a single function, `buildGraph`. I'd have `buildGraph` accept an array of two-element arrays, rather than strings containing hyphens, to make the module less dependent on the input format.
-The `roads` module contains the raw road data (the `roads` array) and
-the `roadGraph` binding. This module depends on `./graph` and exports
-the road graph.
+The `roads` module contains the raw road data (the `roads` array) and the `roadGraph` binding. This module depends on `./graph` and exports the road graph.
{{index "random-item package"}}
-The `VillageState` class lives in the `state` module. It depends on
-the `./roads` module because it needs to be able to verify that a
-given road exists. It also needs `randomPick`. Since that is a
-three-line function, we could just put it into the `state` module as
-an internal helper function. But `randomRobot` needs it too. So we'd
-have to either duplicate it or put it into its own module. Since this
-function happens to exist on NPM in the `random-item` package, a good
-solution is to just make both modules depend on that. We can add the
-`runRobot` function to this module as well, since it's small and
-closely related to state management. The module exports both the
-`VillageState` class and the `runRobot` function.
-
-Finally, the robots, along with the values they depend on such as
-`mailRoute`, could go into an `example-robots` module, which depends
-on `./roads` and exports the robot functions. To make it possible for
-`goalOrientedRobot` to do route-finding, this module also depends
-on `dijkstrajs`.
-
-By offloading some work to ((NPM)) modules, the code became a little
-smaller. Each individual module does something rather simple and can
-be read on its own. Dividing code into modules also often suggests
-further improvements to the program's design. In this case, it seems a
-little odd that the `VillageState` and the robots depend on a specific
-road graph. It might be a better idea to make the graph an argument to
-the state's constructor and make the robots read it from the state
-object—this reduces dependencies (which is always good) and makes it
-possible to run simulations on different maps (which is even better).
-
-Is it a good idea to use NPM modules for things that we could have
-written ourselves? In principle, yes—for nontrivial things like the
-pathfinding function you are likely to make mistakes and waste time
-writing them yourself. For tiny functions like `random-item`, writing
-them yourself is easy enough. But adding them wherever you need them
-does tend to clutter your modules.
-
-However, you should also not underestimate the work involved in
-_finding_ an appropriate NPM package. And even if you find one, it
-might not work well or may be missing some feature you need. On top
-of that, depending on NPM packages means you have to make sure they
-are installed, you have to distribute them with your program, and you
-might have to periodically upgrade them.
-
-So again, this is a trade-off, and you can decide either way depending
-on how much the packages help you.
+The `VillageState` class lives in the `state` module. It depends on the `./roads` module because it needs to be able to verify that a given road exists. It also needs `randomPick`. Since that is a three-line function, we could just put it into the `state` module as an internal helper function. But `randomRobot` needs it too. So we'd have to either duplicate it or put it into its own module. Since this function happens to exist on NPM in the `random-item` package, a good solution is to just make both modules depend on that. We can add the `runRobot` function to this module as well, since it's small and closely related to state management. The module exports both the `VillageState` class and the `runRobot` function.
+
+Finally, the robots, along with the values they depend on such as `mailRoute`, could go into an `example-robots` module, which depends on `./roads` and exports the robot functions. To make it possible for `goalOrientedRobot` to do route-finding, this module also depends on `dijkstrajs`.
+
+By offloading some work to ((NPM)) modules, the code became a little smaller. Each individual module does something rather simple and can be read on its own. Dividing code into modules also often suggests further improvements to the program's design. In this case, it seems a little odd that the `VillageState` and the robots depend on a specific road graph. It might be a better idea to make the graph an argument to the state's constructor and make the robots read it from the state object—this reduces dependencies (which is always good) and makes it possible to run simulations on different maps (which is even better).
+
+Is it a good idea to use NPM modules for things that we could have written ourselves? In principle, yes—for nontrivial things like the pathfinding function you are likely to make mistakes and waste time writing them yourself. For tiny functions like `random-item`, writing them yourself is easy enough. But adding them wherever you need them does tend to clutter your modules.
+
+However, you should also not underestimate the work involved in _finding_ an appropriate NPM package. And even if you find one, it might not work well or may be missing some feature you need. On top of that, depending on NPM packages means you have to make sure they are installed, you have to distribute them with your program, and you might have to periodically upgrade them.
+
+So again, this is a trade-off, and you can decide either way depending on how much the packages help you.
hint}}
@@ -789,12 +466,7 @@ hint}}
{{index "roads module (exercise)"}}
-Write a ((CommonJS module)), based on the example from [Chapter
-?](robot), that contains the array of roads and exports the graph
-data structure representing them as `roadGraph`. It should depend on a
-module `./graph`, which exports a function `buildGraph` that is used
-to build the graph. This function expects an array of two-element
-arrays (the start and end points of the roads).
+Write a ((CommonJS module)), based on the example from [Chapter ?](robot), that contains the array of roads and exports the graph data structure representing them as `roadGraph`. It should depend on a module `./graph`, which exports a function `buildGraph` that is used to build the graph. This function expects an array of two-element arrays (the start and end points of the roads).
{{if interactive
@@ -818,15 +490,9 @@ if}}
{{index "roads module (exercise)", "destructuring binding", "exports object"}}
-Since this is a ((CommonJS module)), you have to use `require` to
-import the graph module. That was described as exporting a
-`buildGraph` function, which you can pick out of its interface object
-with a destructuring `const` declaration.
+Since this is a ((CommonJS module)), you have to use `require` to import the graph module. That was described as exporting a `buildGraph` function, which you can pick out of its interface object with a destructuring `const` declaration.
-To export `roadGraph`, you add a property to the `exports` object.
-Because `buildGraph` takes a data structure that doesn't precisely
-match `roads`, the splitting of the road strings must happen in your
-module.
+To export `roadGraph`, you add a property to the `exports` object. Because `buildGraph` takes a data structure that doesn't precisely match `roads`, the splitting of the road strings must happen in your module.
hint}}
@@ -834,35 +500,18 @@ hint}}
{{index dependency, "circular dependency", "require function"}}
-A circular dependency is a situation where module A depends on B, and
-B also, directly or indirectly, depends on A. Many module systems
-simply forbid this because whichever order you choose for loading such
-modules, you cannot make sure that each module's dependencies have
-been loaded before it runs.
+A circular dependency is a situation where module A depends on B, and B also, directly or indirectly, depends on A. Many module systems simply forbid this because whichever order you choose for loading such modules, you cannot make sure that each module's dependencies have been loaded before it runs.
-((CommonJS modules)) allow a limited form of cyclic dependencies. As
-long as the modules do not replace their default `exports` object and
-don't access each other's interface until after they finish loading,
-cyclic dependencies are okay.
+((CommonJS modules)) allow a limited form of cyclic dependencies. As long as the modules do not replace their default `exports` object and don't access each other's interface until after they finish loading, cyclic dependencies are okay.
-The `require` function given [earlier in this
-chapter](modules#require) supports this type of dependency cycle. Can
-you see how it handles cycles? What would go wrong when a module in a
-cycle _does_ replace its default `exports` object?
+The `require` function given [earlier in this chapter](modules#require) supports this type of dependency cycle. Can you see how it handles cycles? What would go wrong when a module in a cycle _does_ replace its default `exports` object?
{{hint
{{index overriding, "circular dependency", "exports object"}}
-The trick is that `require` adds modules to its cache _before_ it
-starts loading the module. That way, if any `require` call made while
-it is running tries to load it, it is already known, and the current
-interface will be returned, rather than starting to load the module
-once more (which would eventually overflow the stack).
+The trick is that `require` adds modules to its cache _before_ it starts loading the module. That way, if any `require` call made while it is running tries to load it, it is already known, and the current interface will be returned, rather than starting to load the module once more (which would eventually overflow the stack).
-If a module overwrites its `module.exports` value, any other module
-that has received its interface value before it finished loading will
-have gotten hold of the default interface object (which is likely
-empty), rather than the intended interface value.
+If a module overwrites its `module.exports` value, any other module that has received its interface value before it finished loading will have gotten hold of the default interface object (which is likely empty), rather than the intended interface value.
hint}}
diff --git a/11_async.md b/11_async.md
index 9ee8bd96b..84dba4051 100644
--- a/11_async.md
+++ b/11_async.md
@@ -4,8 +4,7 @@
{{quote {author: "Laozi", title: "Tao Te Ching", chapter: true}
-Who can wait quietly while the mud settles?\
-Who can remain still until the moment of action?
+Who can wait quietly while the mud settles?\ Who can remain still until the moment of action?
quote}}
@@ -13,178 +12,89 @@ quote}}
{{figure {url: "img/chapter_picture_11.jpg", alt: "Picture of two crows on a branch", chapter: framed}}}
-The central part of a computer, the part that carries out the
-individual steps that make up our programs, is called the
-_((processor))_. The programs we have seen so far are things that will
-keep the processor busy until they have finished their work. The speed
-at which something like a loop that manipulates numbers can be
-executed depends pretty much entirely on the speed of the processor.
+The central part of a computer, the part that carries out the individual steps that make up our programs, is called the _((processor))_. The programs we have seen so far are things that will keep the processor busy until they have finished their work. The speed at which something like a loop that manipulates numbers can be executed depends pretty much entirely on the speed of the processor.
{{index [memory, speed], [network, speed]}}
-But many programs interact with things outside of the processor. For
-example, they may communicate over a computer network or request
-data from the ((hard disk))—which is a lot slower than getting it from
-memory.
+But many programs interact with things outside of the processor. For example, they may communicate over a computer network or request data from the ((hard disk))—which is a lot slower than getting it from memory.
-When such a thing is happening, it would be a shame to let the
-processor sit idle—there might be some other work it could do in the
-meantime. In part, this is handled by your operating system, which
-will switch the processor between multiple running programs. But that
-doesn't help when we want a _single_ program to be able to make
-progress while it is waiting for a network request.
+When such a thing is happening, it would be a shame to let the processor sit idle—there might be some other work it could do in the meantime. In part, this is handled by your operating system, which will switch the processor between multiple running programs. But that doesn't help when we want a _single_ program to be able to make progress while it is waiting for a network request.
## Asynchronicity
{{index "synchronous programming"}}
-In a _synchronous_ programming model, things happen one at a time.
-When you call a function that performs a long-running action, it
-returns only when the action has finished and it can return the result.
-This stops your program for the time the action takes.
+In a _synchronous_ programming model, things happen one at a time. When you call a function that performs a long-running action, it returns only when the action has finished and it can return the result. This stops your program for the time the action takes.
{{index "asynchronous programming"}}
-An _asynchronous_ model allows multiple things to happen at the same
-time. When you start an action, your program continues to run. When
-the action finishes, the program is informed and gets access to the
-result (for example, the data read from disk).
+An _asynchronous_ model allows multiple things to happen at the same time. When you start an action, your program continues to run. When the action finishes, the program is informed and gets access to the result (for example, the data read from disk).
-We can compare synchronous and asynchronous programming using a small
-example: a program that fetches two resources from the ((network)) and
-then combines results.
+We can compare synchronous and asynchronous programming using a small example: a program that fetches two resources from the ((network)) and then combines results.
{{index "synchronous programming"}}
-In a synchronous environment, where the request function returns only
-after it has done its work, the easiest way to perform this task is to
-make the requests one after the other. This has the drawback that the
-second request will be started only when the first has finished. The
-total time taken will be at least the sum of the two response times.
+In a synchronous environment, where the request function returns only after it has done its work, the easiest way to perform this task is to make the requests one after the other. This has the drawback that the second request will be started only when the first has finished. The total time taken will be at least the sum of the two response times.
{{index parallelism}}
-The solution to this problem, in a synchronous system, is to start
-additional ((thread))s of control. A _thread_ is another running program
-whose execution may be interleaved with other programs by the
-operating system—since most modern computers contain multiple
-processors, multiple threads may even run at the same time, on
-different processors. A second thread could start the second request,
-and then both threads wait for their results to come back, after which
-they resynchronize to combine their results.
+The solution to this problem, in a synchronous system, is to start additional ((thread))s of control. A _thread_ is another running program whose execution may be interleaved with other programs by the operating system—since most modern computers contain multiple processors, multiple threads may even run at the same time, on different processors. A second thread could start the second request, and then both threads wait for their results to come back, after which they resynchronize to combine their results.
{{index CPU, blocking, "asynchronous programming", timeline, "callback function"}}
-In the following diagram, the thick lines represent time the program
-spends running normally, and the thin lines represent time spent
-waiting for the network. In the synchronous model, the time taken by
-the network is _part_ of the timeline for a given thread of control.
-In the asynchronous model, starting a network action conceptually
-causes a _split_ in the timeline. The program that initiated the
-action continues running, and the action happens alongside it,
-notifying the program when it is finished.
+In the following diagram, the thick lines represent time the program spends running normally, and the thin lines represent time spent waiting for the network. In the synchronous model, the time taken by the network is _part_ of the timeline for a given thread of control. In the asynchronous model, starting a network action conceptually causes a _split_ in the timeline. The program that initiated the action continues running, and the action happens alongside it, notifying the program when it is finished.
{{figure {url: "img/control-io.svg", alt: "Control flow for synchronous and asynchronous programming",width: "8cm"}}}
{{index ["control flow", asynchronous], "asynchronous programming", verbosity}}
-Another way to describe the difference is that waiting for actions to
-finish is _implicit_ in the synchronous model, while it is _explicit_,
-under our control, in the asynchronous one.
+Another way to describe the difference is that waiting for actions to finish is _implicit_ in the synchronous model, while it is _explicit_, under our control, in the asynchronous one.
-Asynchronicity cuts both ways. It makes expressing programs that do
-not fit the straight-line model of control easier, but it can also
-make expressing programs that do follow a straight line more awkward.
-We'll see some ways to address this awkwardness later in the chapter.
+Asynchronicity cuts both ways. It makes expressing programs that do not fit the straight-line model of control easier, but it can also make expressing programs that do follow a straight line more awkward. We'll see some ways to address this awkwardness later in the chapter.
-Both of the important JavaScript programming platforms—((browser))s
-and ((Node.js))—make operations that might take a while asynchronous,
-rather than relying on ((thread))s. Since programming with threads is
-notoriously hard (understanding what a program does is much more
-difficult when it's doing multiple things at once), this is generally
-considered a good thing.
+Both of the important JavaScript programming platforms—((browser))s and ((Node.js))—make operations that might take a while asynchronous, rather than relying on ((thread))s. Since programming with threads is notoriously hard (understanding what a program does is much more difficult when it's doing multiple things at once), this is generally considered a good thing.
## Crow tech
-Most people are aware of the fact that ((crow))s are very smart birds.
-They can use tools, plan ahead, remember things, and even communicate
-these things among themselves.
-
-What most people don't know is that they are capable of many things
-that they keep well hidden from us. I've been told by a reputable (if
-somewhat eccentric) expert on ((corvid))s that crow technology is not
-far behind human technology, and they are catching up.
-
-For example, many crow cultures have the ability to construct
-computing devices. These are not electronic, as human computing
-devices are, but operate through the actions of tiny insects, a
-species closely related to the ((termite)), which has developed a
-((symbiotic relationship)) with the crows. The birds provide them with
-food, and in return the insects build and operate their complex
-colonies that, with the help of the living creatures inside them,
-perform computations.
-
-Such colonies are usually located in big, long-lived nests. The birds
-and insects work together to build a network of bulbous clay
-structures, hidden between the twigs of the nest, in which the insects
-live and work.
-
-To communicate with other devices, these machines use light signals.
-The crows embed pieces of reflective material in special communication
-stalks, and the insects aim these to reflect light at another nest,
-encoding data as a sequence of quick flashes. This means that only
-nests that have an unbroken visual connection can communicate.
-
-Our friend the corvid expert has mapped the network of crow nests in
-the village of ((Hières-sur-Amby)), on the banks of the river Rhône.
-This map shows the nests and their connections:
+Most people are aware of the fact that ((crow))s are very smart birds. They can use tools, plan ahead, remember things, and even communicate these things among themselves.
+
+What most people don't know is that they are capable of many things that they keep well hidden from us. I've been told by a reputable (if somewhat eccentric) expert on ((corvid))s that crow technology is not far behind human technology, and they are catching up.
+
+For example, many crow cultures have the ability to construct computing devices. These are not electronic, as human computing devices are, but operate through the actions of tiny insects, a species closely related to the ((termite)), which has developed a ((symbiotic relationship)) with the crows. The birds provide them with food, and in return the insects build and operate their complex colonies that, with the help of the living creatures inside them, perform computations.
+
+Such colonies are usually located in big, long-lived nests. The birds and insects work together to build a network of bulbous clay structures, hidden between the twigs of the nest, in which the insects live and work.
+
+To communicate with other devices, these machines use light signals. The crows embed pieces of reflective material in special communication stalks, and the insects aim these to reflect light at another nest, encoding data as a sequence of quick flashes. This means that only nests that have an unbroken visual connection can communicate.
+
+Our friend the corvid expert has mapped the network of crow nests in the village of ((Hières-sur-Amby)), on the banks of the river Rhône. This map shows the nests and their connections:
{{figure {url: "img/Hieres-sur-Amby.png", alt: "A network of crow nests in a small village"}}}
-In an astounding example of ((convergent evolution)), crow computers
-run JavaScript. In this chapter we'll write some basic networking
-functions for them.
+In an astounding example of ((convergent evolution)), crow computers run JavaScript. In this chapter we'll write some basic networking functions for them.
## Callbacks
{{indexsee [function, callback], "callback function"}}
-One approach to ((asynchronous programming)) is to make functions that
-perform a slow action take an extra argument, a _((callback
-function))_. The action is started, and when it finishes, the callback
-function is called with the result.
+One approach to ((asynchronous programming)) is to make functions that perform a slow action take an extra argument, a _((callback function))_. The action is started, and when it finishes, the callback function is called with the result.
{{index "setTimeout function", waiting}}
-As an example, the `setTimeout` function, available both in Node.js
-and in browsers, waits a given number of milliseconds (a second is a
-thousand milliseconds) and then calls a function.
+As an example, the `setTimeout` function, available both in Node.js and in browsers, waits a given number of milliseconds (a second is a thousand milliseconds) and then calls a function.
```{test: no}
setTimeout(() => console.log("Tick"), 500);
```
-Waiting is not generally a very important type of work, but it can be
-useful when doing something like updating an animation or checking whether
-something is taking longer than a given amount of ((time)).
+Waiting is not generally a very important type of work, but it can be useful when doing something like updating an animation or checking whether something is taking longer than a given amount of ((time)).
-Performing multiple asynchronous actions in a row using callbacks
-means that you have to keep passing new functions to handle the
-((continuation)) of the computation after the actions.
+Performing multiple asynchronous actions in a row using callbacks means that you have to keep passing new functions to handle the ((continuation)) of the computation after the actions.
{{index "hard disk"}}
-Most crow nest computers have a long-term data storage bulb, where
-pieces of information are etched into twigs so that they can be
-retrieved later. Etching, or finding a piece of data, takes a moment, so
-the interface to long-term storage is asynchronous and uses callback
-functions.
+Most crow nest computers have a long-term data storage bulb, where pieces of information are etched into twigs so that they can be retrieved later. Etching, or finding a piece of data, takes a moment, so the interface to long-term storage is asynchronous and uses callback functions.
-Storage bulbs store pieces of ((JSON))-encodable data under names. A
-((crow)) might store information about the places where it's hidden food under the name `"food caches"`, which could hold an array of
-names that point at other pieces of data, describing the actual cache.
-To look up a food ((cache)) in the storage bulbs of the _Big Oak_
-nest, a crow could run code like this:
+Storage bulbs store pieces of ((JSON))-encodable data under names. A ((crow)) might store information about the places where it's hidden food under the name `"food caches"`, which could hold an array of names that point at other pieces of data, describing the actual cache. To look up a food ((cache)) in the storage bulbs of the _Big Oak_ nest, a crow could run code like this:
{{index "readStorage function"}}
@@ -199,44 +109,24 @@ bigOak.readStorage("food caches", caches => {
});
```
-(All binding names and strings have been translated from crow language
-to English.)
+(All binding names and strings have been translated from crow language to English.)
-This style of programming is workable, but the indentation level
-increases with each asynchronous action because you end up in another
-function. Doing more complicated things, such as running multiple actions
-at the same time, can get a little awkward.
+This style of programming is workable, but the indentation level increases with each asynchronous action because you end up in another function. Doing more complicated things, such as running multiple actions at the same time, can get a little awkward.
-Crow nest computers are built to communicate using
-((request))-((response)) pairs. That means one nest sends a message to
-another nest, which then immediately sends a message back, confirming
-receipt and possibly including a reply to a question asked in the
-message.
+Crow nest computers are built to communicate using ((request))-((response)) pairs. That means one nest sends a message to another nest, which then immediately sends a message back, confirming receipt and possibly including a reply to a question asked in the message.
-Each message is tagged with a _type_, which determines how it is
-handled. Our code can define handlers for specific request types, and
-when such a request comes in, the handler is called to produce a
-response.
+Each message is tagged with a _type_, which determines how it is handled. Our code can define handlers for specific request types, and when such a request comes in, the handler is called to produce a response.
{{index "crow-tech module", "send method"}}
-The interface exported by the `"./crow-tech"` module provides
-callback-based functions for communication. Nests have a `send` method
-that sends off a request. It expects the name of the target nest, the
-type of the request, and the content of the request as its first three
-arguments, and it expects a function to call when a response comes in as its
-fourth and last argument.
+The interface exported by the `"./crow-tech"` module provides callback-based functions for communication. Nests have a `send` method that sends off a request. It expects the name of the target nest, the type of the request, and the content of the request as its first three arguments, and it expects a function to call when a response comes in as its fourth and last argument.
```
bigOak.send("Cow Pasture", "note", "Let's caw loudly at 7PM",
() => console.log("Note delivered."));
```
-But to make nests capable of receiving that request, we first have to
-define a ((request type)) named `"note"`. The code that handles the
-requests has to run not just on this nest-computer but on all nests
-that can receive messages of this type. We'll just assume that a crow
-flies over and installs our handler code on all the nests.
+But to make nests capable of receiving that request, we first have to define a ((request type)) named `"note"`. The code that handles the requests has to run not just on this nest-computer but on all nests that can receive messages of this type. We'll just assume that a crow flies over and installs our handler code on all the nests.
{{index "defineRequestType function"}}
@@ -249,51 +139,25 @@ defineRequestType("note", (nest, content, source, done) => {
});
```
-The `defineRequestType` function defines a new type of request. The
-example adds support for `"note"` requests, which just sends a note to
-a given nest. Our implementation calls `console.log` so that we can
-verify that the request arrived. Nests have a `name` property that
-holds their name.
+The `defineRequestType` function defines a new type of request. The example adds support for `"note"` requests, which just sends a note to a given nest. Our implementation calls `console.log` so that we can verify that the request arrived. Nests have a `name` property that holds their name.
{{index "asynchronous programming"}}
-The fourth argument given to the handler, `done`, is a callback
-function that it must call when it is done with the request. If we had
-used the handler's ((return value)) as the response value, that would
-mean that a request handler can't itself perform asynchronous actions.
-A function doing asynchronous work typically returns before the work
-is done, having arranged for a callback to be called when it
-completes. So we need some asynchronous mechanism—in this case,
-another ((callback function))—to signal when a response is available.
-
-In a way, asynchronicity is _contagious_. Any function that calls a
-function that works asynchronously must itself be asynchronous, using
-a callback or similar mechanism to deliver its result. Calling a
-callback is somewhat more involved and error-prone than simply
-returning a value, so needing to structure large parts of your program
-that way is not great.
+The fourth argument given to the handler, `done`, is a callback function that it must call when it is done with the request. If we had used the handler's ((return value)) as the response value, that would mean that a request handler can't itself perform asynchronous actions. A function doing asynchronous work typically returns before the work is done, having arranged for a callback to be called when it completes. So we need some asynchronous mechanism—in this case, another ((callback function))—to signal when a response is available.
+
+In a way, asynchronicity is _contagious_. Any function that calls a function that works asynchronously must itself be asynchronous, using a callback or similar mechanism to deliver its result. Calling a callback is somewhat more involved and error-prone than simply returning a value, so needing to structure large parts of your program that way is not great.
## Promises
-Working with abstract concepts is often easier when those concepts can
-be represented by ((value))s. In the case of asynchronous actions, you
-could, instead of arranging for a function to be called at some point
-in the future, return an object that represents this future event.
+Working with abstract concepts is often easier when those concepts can be represented by ((value))s. In the case of asynchronous actions, you could, instead of arranging for a function to be called at some point in the future, return an object that represents this future event.
{{index "Promise class", "asynchronous programming"}}
-This is what the standard class `Promise` is for. A _promise_ is an
-asynchronous action that may complete at some point and produce a
-value. It is able to notify anyone who is interested when its value is
-available.
+This is what the standard class `Promise` is for. A _promise_ is an asynchronous action that may complete at some point and produce a value. It is able to notify anyone who is interested when its value is available.
{{index "Promise.resolve function", "resolving (a promise)"}}
-The easiest way to create a promise is by calling `Promise.resolve`.
-This function ensures that the value you give it is wrapped in a
-promise. If it's already a promise, it is simply returned—otherwise,
-you get a new promise that immediately finishes with your
-value as its result.
+The easiest way to create a promise is by calling `Promise.resolve`. This function ensures that the value you give it is wrapped in a promise. If it's already a promise, it is simply returned—otherwise, you get a new promise that immediately finishes with your value as its result.
```
let fifteen = Promise.resolve(15);
@@ -303,37 +167,19 @@ fifteen.then(value => console.log(`Got ${value}`));
{{index "then method"}}
-To get the result of a promise, you can use its `then` method. This
-registers a ((callback function)) to be called when the promise
-resolves and produces a value. You can add multiple callbacks to a
-single promise, and they will be called, even if you add them after
-the promise has already _resolved_ (finished).
+To get the result of a promise, you can use its `then` method. This registers a ((callback function)) to be called when the promise resolves and produces a value. You can add multiple callbacks to a single promise, and they will be called, even if you add them after the promise has already _resolved_ (finished).
-But that's not all the `then` method does. It returns another promise,
-which resolves to the value that the handler function returns or, if
-that returns a promise, waits for that promise and then resolves to
-its result.
+But that's not all the `then` method does. It returns another promise, which resolves to the value that the handler function returns or, if that returns a promise, waits for that promise and then resolves to its result.
-It is useful to think of promises as a device to move values into an
-asynchronous reality. A normal value is simply there. A promised value
-is a value that _might_ already be there or might appear at some point
-in the future. Computations defined in terms of promises act on such
-wrapped values and are executed asynchronously as the values become
-available.
+It is useful to think of promises as a device to move values into an asynchronous reality. A normal value is simply there. A promised value is a value that _might_ already be there or might appear at some point in the future. Computations defined in terms of promises act on such wrapped values and are executed asynchronously as the values become available.
{{index "Promise class"}}
-To create a promise, you can use `Promise` as a constructor. It has a
-somewhat odd interface—the constructor expects a function as argument,
-which it immediately calls, passing it a function that it can use to
-resolve the promise. It works this way, instead of for example with a
-`resolve` method, so that only the code that created the promise can
-resolve it.
+To create a promise, you can use `Promise` as a constructor. It has a somewhat odd interface—the constructor expects a function as argument, which it immediately calls, passing it a function that it can use to resolve the promise. It works this way, instead of for example with a `resolve` method, so that only the code that created the promise can resolve it.
{{index "storage function"}}
-This is how you'd create a promise-based interface for the
-`readStorage` function:
+This is how you'd create a promise-based interface for the `readStorage` function:
```{includeCode: "top_lines: 5"}
function storage(nest, name) {
@@ -346,86 +192,39 @@ storage(bigOak, "enemies")
.then(value => console.log("Got", value));
```
-This asynchronous function returns a meaningful value. This is the
-main advantage of promises—they simplify the use of asynchronous
-functions. Instead of having to pass around callbacks, promise-based
-functions look similar to regular ones: they take input as arguments
-and return their output. The only difference is that the output may
-not be available yet.
+This asynchronous function returns a meaningful value. This is the main advantage of promises—they simplify the use of asynchronous functions. Instead of having to pass around callbacks, promise-based functions look similar to regular ones: they take input as arguments and return their output. The only difference is that the output may not be available yet.
## Failure
{{index "exception handling"}}
-Regular JavaScript computations can fail by throwing an exception.
-Asynchronous computations often need something like that. A network
-request may fail, or some code that is part of the asynchronous
-computation may throw an exception.
+Regular JavaScript computations can fail by throwing an exception. Asynchronous computations often need something like that. A network request may fail, or some code that is part of the asynchronous computation may throw an exception.
{{index "callback function", error}}
-One of the most pressing problems with the callback style of
-asynchronous programming is that it makes it extremely difficult to
-make sure failures are properly reported to the callbacks.
+One of the most pressing problems with the callback style of asynchronous programming is that it makes it extremely difficult to make sure failures are properly reported to the callbacks.
-A widely used convention is that the first argument to the callback is
-used to indicate that the action failed, and the second contains the
-value produced by the action when it was successful. Such callback
-functions must always check whether they received an exception and
-make sure that any problems they cause, including exceptions thrown by
-functions they call, are caught and given to the right function.
+A widely used convention is that the first argument to the callback is used to indicate that the action failed, and the second contains the value produced by the action when it was successful. Such callback functions must always check whether they received an exception and make sure that any problems they cause, including exceptions thrown by functions they call, are caught and given to the right function.
{{index "rejecting (a promise)", "resolving (a promise)", "then method"}}
-Promises make this easier. They can be either resolved (the action
-finished successfully) or rejected (it failed). Resolve handlers (as
-registered with `then`) are called only when the action is successful,
-and rejections are automatically propagated to the new promise that is
-returned by `then`. And when a handler throws an exception, this
-automatically causes the promise produced by its `then` call to be
-rejected. So if any element in a chain of asynchronous actions fails,
-the outcome of the whole chain is marked as rejected, and no success
-handlers are called beyond the point where it failed.
+Promises make this easier. They can be either resolved (the action finished successfully) or rejected (it failed). Resolve handlers (as registered with `then`) are called only when the action is successful, and rejections are automatically propagated to the new promise that is returned by `then`. And when a handler throws an exception, this automatically causes the promise produced by its `then` call to be rejected. So if any element in a chain of asynchronous actions fails, the outcome of the whole chain is marked as rejected, and no success handlers are called beyond the point where it failed.
{{index "Promise.reject function", "Promise class"}}
-Much like resolving a promise provides a value, rejecting one also
-provides one, usually called the _reason_ of the rejection. When an
-exception in a handler function causes the rejection, the exception
-value is used as the reason. Similarly, when a handler returns a
-promise that is rejected, that rejection flows into the next promise.
-There's a `Promise.reject` function that creates a new,
-immediately rejected promise.
+Much like resolving a promise provides a value, rejecting one also provides one, usually called the _reason_ of the rejection. When an exception in a handler function causes the rejection, the exception value is used as the reason. Similarly, when a handler returns a promise that is rejected, that rejection flows into the next promise. There's a `Promise.reject` function that creates a new, immediately rejected promise.
{{index "catch method"}}
-To explicitly handle such rejections, promises have a `catch` method
-that registers a handler to be called when the promise is rejected,
-similar to how `then` handlers handle normal resolution. It's also very
-much like `then` in that it returns a new promise, which resolves to
-the original promise's value if it resolves normally and to the
-result of the `catch` handler otherwise. If a `catch` handler throws
-an error, the new promise is also rejected.
+To explicitly handle such rejections, promises have a `catch` method that registers a handler to be called when the promise is rejected, similar to how `then` handlers handle normal resolution. It's also very much like `then` in that it returns a new promise, which resolves to the original promise's value if it resolves normally and to the result of the `catch` handler otherwise. If a `catch` handler throws an error, the new promise is also rejected.
{{index "then method"}}
-As a shorthand, `then` also accepts a rejection handler as a second
-argument, so you can install both types of handlers in a single method
-call.
+As a shorthand, `then` also accepts a rejection handler as a second argument, so you can install both types of handlers in a single method call.
-A function passed to the `Promise` constructor receives a second
-argument, alongside the resolve function, which it can use to reject
-the new promise.
+A function passed to the `Promise` constructor receives a second argument, alongside the resolve function, which it can use to reject the new promise.
-The chains of promise values created by calls to `then` and `catch`
-can be seen as a pipeline through which asynchronous values or
-failures move. Since such chains are created by registering handlers,
-each link has a success handler or a rejection handler (or both)
-associated with it. Handlers that don't match the type of outcome
-(success or failure) are ignored. But those that do match are called,
-and their outcome determines what kind of value comes next—success
-when it returns a non-promise value, rejection when it throws an
-exception, and the outcome of a promise when it returns one of those.
+The chains of promise values created by calls to `then` and `catch` can be seen as a pipeline through which asynchronous values or failures move. Since such chains are created by registering handlers, each link has a success handler or a rejection handler (or both) associated with it. Handlers that don't match the type of outcome (success or failure) are ignored. But those that do match are called, and their outcome determines what kind of value comes next—success when it returns a non-promise value, rejection when it throws an exception, and the outcome of a promise when it returns one of those.
```{test: no}
new Promise((_, reject) => reject(new Error("Fail")))
@@ -441,50 +240,27 @@ new Promise((_, reject) => reject(new Error("Fail")))
{{index "uncaught exception", "exception handling"}}
-Much like an uncaught exception is handled by the environment,
-JavaScript environments can detect when a promise rejection isn't
-handled and will report this as an error.
+Much like an uncaught exception is handled by the environment, JavaScript environments can detect when a promise rejection isn't handled and will report this as an error.
## Networks are hard
{{index [network, reliability]}}
-Occasionally, there isn't enough light for the ((crow))s' mirror
-systems to transmit a signal or something is blocking the path of the
-signal. It is possible for a signal to be sent but never received.
+Occasionally, there isn't enough light for the ((crow))s' mirror systems to transmit a signal or something is blocking the path of the signal. It is possible for a signal to be sent but never received.
{{index "send method", error, timeout}}
-As it is, that will just cause the callback given to `send` to never
-be called, which will probably cause the program to stop without even
-noticing there is a problem. It would be nice if, after a given period
-of not getting a response, a request would _time out_ and report
-failure.
+As it is, that will just cause the callback given to `send` to never be called, which will probably cause the program to stop without even noticing there is a problem. It would be nice if, after a given period of not getting a response, a request would _time out_ and report failure.
-Often, transmission failures are random accidents, like a car's
-headlight interfering with the light signals, and simply retrying the
-request may cause it to succeed. So while we're at it, let's make our
-request function automatically retry the sending of the request a few
-times before it gives up.
+Often, transmission failures are random accidents, like a car's headlight interfering with the light signals, and simply retrying the request may cause it to succeed. So while we're at it, let's make our request function automatically retry the sending of the request a few times before it gives up.
{{index "Promise class", "callback function", [interface, object]}}
-And, since we've established that promises are a good thing, we'll
-also make our request function return a promise. In terms of what they
-can express, callbacks and promises are equivalent. Callback-based
-functions can be wrapped to expose a promise-based interface, and
-vice versa.
+And, since we've established that promises are a good thing, we'll also make our request function return a promise. In terms of what they can express, callbacks and promises are equivalent. Callback-based functions can be wrapped to expose a promise-based interface, and vice versa.
-Even when a ((request)) and its ((response)) are successfully
-delivered, the response may indicate failure—for example, if the
-request tries to use a request type that hasn't been defined or the
-handler throws an error. To support this, `send` and
-`defineRequestType` follow the convention mentioned before, where the
-first argument passed to callbacks is the failure reason, if any, and
-the second is the actual result.
+Even when a ((request)) and its ((response)) are successfully delivered, the response may indicate failure—for example, if the request tries to use a request type that hasn't been defined or the handler throws an error. To support this, `send` and `defineRequestType` follow the convention mentioned before, where the first argument passed to callbacks is the failure reason, if any, and the second is the actual result.
-These can be translated to promise resolution and rejection by our
-wrapper.
+These can be translated to promise resolution and rejection by our wrapper.
{{index "Timeout class", "request function", retry}}
@@ -513,40 +289,21 @@ function request(nest, target, type, content) {
{{index "Promise class", "resolving (a promise)", "rejecting (a promise)"}}
-Because promises can be resolved (or rejected) only once, this will
-work. The first time `resolve` or `reject` is called determines the
-outcome of the promise, and further calls caused by a request coming
-back after another request finished are ignored.
+Because promises can be resolved (or rejected) only once, this will work. The first time `resolve` or `reject` is called determines the outcome of the promise, and further calls caused by a request coming back after another request finished are ignored.
{{index recursion}}
-To build an asynchronous ((loop)), for the retries, we need to use a
-recursive function—a regular loop doesn't allow us to stop and wait
-for an asynchronous action. The `attempt` function makes a single
-attempt to send a request. It also sets a timeout that, if no response
-has come back after 250 milliseconds, either starts the next attempt
-or, if this was the third attempt, rejects the promise with an
-instance of `Timeout` as the reason.
+To build an asynchronous ((loop)), for the retries, we need to use a recursive function—a regular loop doesn't allow us to stop and wait for an asynchronous action. The `attempt` function makes a single attempt to send a request. It also sets a timeout that, if no response has come back after 250 milliseconds, either starts the next attempt or, if this was the third attempt, rejects the promise with an instance of `Timeout` as the reason.
{{index idempotence}}
-Retrying every quarter-second and giving up when no response has come
-in after three-quarter second is definitely somewhat arbitrary. It is even
-possible, if the request did come through but the handler is just
-taking a bit longer, for requests to be delivered multiple times.
-We'll write our handlers with that problem in mind—duplicate messages
-should be harmless.
+Retrying every quarter-second and giving up when no response has come in after three-quarter second is definitely somewhat arbitrary. It is even possible, if the request did come through but the handler is just taking a bit longer, for requests to be delivered multiple times. We'll write our handlers with that problem in mind—duplicate messages should be harmless.
-In general, we will not be building a world-class, robust network
-today. But that's okay—crows don't have very high expectations yet
-when it comes to computing.
+In general, we will not be building a world-class, robust network today. But that's okay—crows don't have very high expectations yet when it comes to computing.
{{index "defineRequestType function", "requestType function"}}
-To isolate ourselves from callbacks altogether, we'll go ahead and
-also define a wrapper for `defineRequestType` that allows the handler
-function to return a promise or plain value and wires that up to the
-callback for us.
+To isolate ourselves from callbacks altogether, we'll go ahead and also define a wrapper for `defineRequestType` that allows the handler function to return a promise or plain value and wires that up to the callback for us.
```{includeCode: true}
function requestType(name, handler) {
@@ -565,37 +322,21 @@ function requestType(name, handler) {
{{index "Promise.resolve function"}}
-`Promise.resolve` is used to convert the value returned by `handler`
-to a promise if it isn't already.
+`Promise.resolve` is used to convert the value returned by `handler` to a promise if it isn't already.
{{index "try keyword", "callback function"}}
-Note that the call to `handler` had to be wrapped in a `try` block to
-make sure any exception it raises directly is given to the callback.
-This nicely illustrates the difficulty of properly handling errors
-with raw callbacks—it is easy to forget to properly route
-exceptions like that, and if you don't do it, failures won't get
-reported to the right callback. Promises make this mostly automatic
-and thus less error-prone.
+Note that the call to `handler` had to be wrapped in a `try` block to make sure any exception it raises directly is given to the callback. This nicely illustrates the difficulty of properly handling errors with raw callbacks—it is easy to forget to properly route exceptions like that, and if you don't do it, failures won't get reported to the right callback. Promises make this mostly automatic and thus less error-prone.
## Collections of promises
{{index "neighbors property", "ping request"}}
-Each nest computer keeps an array of other nests within transmission
-distance in its `neighbors` property. To check which of those are
-currently reachable, you could write a function that tries to send a
-`"ping"` request (a request that simply asks for a response) to each
-of them and see which ones come back.
+Each nest computer keeps an array of other nests within transmission distance in its `neighbors` property. To check which of those are currently reachable, you could write a function that tries to send a `"ping"` request (a request that simply asks for a response) to each of them and see which ones come back.
{{index "Promise.all function"}}
-When working with collections of promises running at the same time,
-the `Promise.all` function can be useful. It returns a promise that
-waits for all of the promises in the array to resolve and then
-resolves to an array of the values that these promises produced (in
-the same order as the original array). If any promise is rejected, the
-result of `Promise.all` is itself rejected.
+When working with collections of promises running at the same time, the `Promise.all` function can be useful. It returns a promise that waits for all of the promises in the array to resolve and then resolves to an array of the values that these promises produced (in the same order as the original array). If any promise is rejected, the result of `Promise.all` is itself rejected.
```{includeCode: true}
requestType("ping", () => "pong");
@@ -613,29 +354,17 @@ function availableNeighbors(nest) {
{{index "then method"}}
-When a neighbor isn't available, we don't want the entire combined
-promise to fail since then we still wouldn't know anything. So the
-function that is mapped over the set of neighbors to turn them into
-request promises attaches handlers that make successful requests
-produce `true` and rejected ones produce `false`.
+When a neighbor isn't available, we don't want the entire combined promise to fail since then we still wouldn't know anything. So the function that is mapped over the set of neighbors to turn them into request promises attaches handlers that make successful requests produce `true` and rejected ones produce `false`.
{{index "filter method", "map method", "some method"}}
-In the handler for the combined promise, `filter` is used to remove
-those elements from the `neighbors` array whose corresponding value is
-false. This makes use of the fact that `filter` passes the array index
-of the current element as a second argument to its filtering function
-(`map`, `some`, and similar higher-order array methods do the same).
+In the handler for the combined promise, `filter` is used to remove those elements from the `neighbors` array whose corresponding value is false. This makes use of the fact that `filter` passes the array index of the current element as a second argument to its filtering function (`map`, `some`, and similar higher-order array methods do the same).
## Network flooding
-The fact that nests can talk only to their neighbors greatly inhibits
-the usefulness of this network.
+The fact that nests can talk only to their neighbors greatly inhibits the usefulness of this network.
-For broadcasting information to the whole network, one solution is to
-set up a type of request that is automatically forwarded to neighbors.
-These neighbors then in turn forward it to their neighbors, until the
-whole network has received the message.
+For broadcasting information to the whole network, one solution is to set up a type of request that is automatically forwarded to neighbors. These neighbors then in turn forward it to their neighbors, until the whole network has received the message.
{{index "sendGossip function"}}
@@ -664,26 +393,15 @@ requestType("gossip", (nest, message, source) => {
{{index "everywhere function", "gossip property"}}
-To avoid sending the same message around the network forever, each
-nest keeps an array of gossip strings that it has already seen. To
-define this array, we use the `everywhere` function—which runs code on
-every nest—to add a property to the nest's `state` object, which is
-where we'll keep nest-local state.
+To avoid sending the same message around the network forever, each nest keeps an array of gossip strings that it has already seen. To define this array, we use the `everywhere` function—which runs code on every nest—to add a property to the nest's `state` object, which is where we'll keep nest-local state.
-When a nest receives a duplicate gossip message, which is very likely
-to happen with everybody blindly resending them, it ignores it. But
-when it receives a new message, it excitedly tells all its neighbors
-except for the one who sent it the message.
+When a nest receives a duplicate gossip message, which is very likely to happen with everybody blindly resending them, it ignores it. But when it receives a new message, it excitedly tells all its neighbors except for the one who sent it the message.
-This will cause a new piece of gossip to spread through the network
-like an ink stain in water. Even when some connections aren't
-currently working, if there is an alternative route to a given nest,
-the gossip will reach it through there.
+This will cause a new piece of gossip to spread through the network like an ink stain in water. Even when some connections aren't currently working, if there is an alternative route to a given nest, the gossip will reach it through there.
{{index "flooding"}}
-This style of network communication is called _flooding_—it floods the
-network with a piece of information until all nodes have it.
+This style of network communication is called _flooding_—it floods the network with a piece of information until all nodes have it.
{{if interactive
@@ -699,30 +417,17 @@ if}}
{{index efficiency}}
-If a given node wants to talk to a single other node, flooding is not
-a very efficient approach. Especially when the network is big, that
-would lead to a lot of useless data transfers.
+If a given node wants to talk to a single other node, flooding is not a very efficient approach. Especially when the network is big, that would lead to a lot of useless data transfers.
{{index "routing"}}
-An alternative approach is to set up a way for messages to hop from
-node to node until they reach their destination. The difficulty with
-that is it requires knowledge about the layout of the network. To
-send a request in the direction of a faraway nest, it is necessary to
-know which neighboring nest gets it closer to its destination. Sending
-it in the wrong direction will not do much good.
+An alternative approach is to set up a way for messages to hop from node to node until they reach their destination. The difficulty with that is it requires knowledge about the layout of the network. To send a request in the direction of a faraway nest, it is necessary to know which neighboring nest gets it closer to its destination. Sending it in the wrong direction will not do much good.
-Since each nest knows only about its direct neighbors, it doesn't have
-the information it needs to compute a route. We must somehow spread
-the information about these connections to all nests, preferably in a
-way that allows it to change over time, when nests are abandoned or
-new nests are built.
+Since each nest knows only about its direct neighbors, it doesn't have the information it needs to compute a route. We must somehow spread the information about these connections to all nests, preferably in a way that allows it to change over time, when nests are abandoned or new nests are built.
{{index flooding}}
-We can use flooding again, but instead of checking whether a given
-message has already been received, we now check whether the new set of
-neighbors for a given nest matches the current set we have for it.
+We can use flooding again, but instead of checking whether a given message has already been received, we now check whether the new set of neighbors for a given nest matches the current set we have for it.
{{index "broadcastConnections function", "connections binding"}}
@@ -755,28 +460,17 @@ everywhere(nest => {
{{index JSON, "== operator"}}
-The comparison uses `JSON.stringify` because `==`, on objects or
-arrays, will return true only when the two are the exact same value,
-which is not what we need here. Comparing the JSON strings is a crude
-but effective way to compare their content.
+The comparison uses `JSON.stringify` because `==`, on objects or arrays, will return true only when the two are the exact same value, which is not what we need here. Comparing the JSON strings is a crude but effective way to compare their content.
-The nodes immediately start broadcasting their connections, which
-should, unless some nests are completely unreachable, quickly give
-every nest a map of the current network ((graph)).
+The nodes immediately start broadcasting their connections, which should, unless some nests are completely unreachable, quickly give every nest a map of the current network ((graph)).
{{index pathfinding}}
-A thing you can do with graphs is find routes in them, as we saw in
-[Chapter ?](robot). If we have a route toward a message's
-destination, we know which direction to send it in.
+A thing you can do with graphs is find routes in them, as we saw in [Chapter ?](robot). If we have a route toward a message's destination, we know which direction to send it in.
{{index "findRoute function"}}
-This `findRoute` function, which greatly resembles the `findRoute`
-from [Chapter ?](robot#findRoute), searches for a way to reach a given
-node in the network. But instead of returning the whole route, it just
-returns the next step. That next nest will itself, using its current
-information about the network, decide where _it_ sends the message.
+This `findRoute` function, which greatly resembles the `findRoute` from [Chapter ?](robot#findRoute), searches for a way to reach a given node in the network. But instead of returning the whole route, it just returns the next step. That next nest will itself, using its current information about the network, decide where _it_ sends the message.
```{includeCode: true}
function findRoute(from, to, connections) {
@@ -794,11 +488,7 @@ function findRoute(from, to, connections) {
}
```
-Now we can build a function that can send long-distance messages. If
-the message is addressed to a direct neighbor, it is delivered as
-usual. If not, it is packaged in an object and sent to a neighbor that
-is closer to the target, using the `"route"` request type, which will
-cause that neighbor to repeat the same behavior.
+Now we can build a function that can send long-distance messages. If the message is addressed to a direct neighbor, it is delivered as usual. If not, it is packaged in an object and sent to a neighbor that is closer to the target, using the `"route"` request type, which will cause that neighbor to repeat the same behavior.
{{index "routeRequest function"}}
@@ -822,8 +512,7 @@ requestType("route", (nest, {target, type, content}) => {
{{if interactive
-We can now send a message to the nest in the church tower, which is
-four network hops removed.
+We can now send a message to the nest in the church tower, which is four network hops removed.
```
routeRequest(bigOak, "Church Tower", "note",
@@ -834,27 +523,17 @@ if}}
{{index [network, abstraction], layering}}
-We've constructed several layers of functionality on top of a
-primitive communication system to make it convenient to use.
-This is a nice (though simplified) model of how real computer networks
-work.
+We've constructed several layers of functionality on top of a primitive communication system to make it convenient to use. This is a nice (though simplified) model of how real computer networks work.
{{index error}}
-A distinguishing property of computer networks is that they aren't
-reliable—abstractions built on top of them can help, but you can't
-abstract away network failure. So network programming is typically
-very much about anticipating and dealing with failures.
+A distinguishing property of computer networks is that they aren't reliable—abstractions built on top of them can help, but you can't abstract away network failure. So network programming is typically very much about anticipating and dealing with failures.
## Async functions
-To store important information, ((crow))s are known to duplicate it
-across nests. That way, when a hawk destroys a nest, the information
-isn't lost.
+To store important information, ((crow))s are known to duplicate it across nests. That way, when a hawk destroys a nest, the information isn't lost.
-To retrieve a given piece of information that it doesn't have in its
-own storage bulb, a nest computer might consult random other nests in
-the network until it finds one that has it.
+To retrieve a given piece of information that it doesn't have in its own storage bulb, a nest computer might consult random other nests in the network until it finds one that has it.
{{index "findInStorage function", "network function"}}
@@ -892,31 +571,19 @@ function findInRemoteStorage(nest, name) {
{{index "Map class", "Object.keys function", "Array.from function"}}
-Because `connections` is a `Map`, `Object.keys` doesn't work on it. It
-has a `keys` _method_, but that returns an iterator rather than an
-array. An iterator (or iterable value) can be converted to an array
-with the `Array.from` function.
+Because `connections` is a `Map`, `Object.keys` doesn't work on it. It has a `keys` _method_, but that returns an iterator rather than an array. An iterator (or iterable value) can be converted to an array with the `Array.from` function.
{{index "Promise class", recursion}}
-Even with promises this is some rather awkward code. Multiple
-asynchronous actions are chained together in non-obvious ways. We
-again need a recursive function (`next`) to model looping through the
-nests.
+Even with promises this is some rather awkward code. Multiple asynchronous actions are chained together in non-obvious ways. We again need a recursive function (`next`) to model looping through the nests.
{{index "synchronous programming", "asynchronous programming"}}
-And the thing the code actually does is completely linear—it always
-waits for the previous action to complete before starting the next
-one. In a synchronous programming model, it'd be simpler to express.
+And the thing the code actually does is completely linear—it always waits for the previous action to complete before starting the next one. In a synchronous programming model, it'd be simpler to express.
{{index "async function", "await keyword"}}
-The good news is that JavaScript allows you to write pseudo-synchronous
-code to describe asynchronous computation. An `async` function is a
-function that implicitly returns a
-promise and that can, in its body, `await` other promises in a way
-that _looks_ synchronous.
+The good news is that JavaScript allows you to write pseudo-synchronous code to describe asynchronous computation. An `async` function is a function that implicitly returns a promise and that can, in its body, `await` other promises in a way that _looks_ synchronous.
{{index "findInStorage function"}}
@@ -944,12 +611,7 @@ async function findInStorage(nest, name) {
{{index "async function", "return keyword", "exception handling"}}
-An `async` function is marked by the word `async` before the
-`function` keyword. Methods can also be made `async` by writing
-`async` before their name. When such a function or method is called,
-it returns a promise. As soon as the body returns something, that
-promise is resolved. If it throws an exception, the promise is
-rejected.
+An `async` function is marked by the word `async` before the `function` keyword. Methods can also be made `async` by writing `async` before their name. When such a function or method is called, it returns a promise. As soon as the body returns something, that promise is resolved. If it throws an exception, the promise is rejected.
{{if interactive
@@ -962,33 +624,19 @@ if}}
{{index "await keyword", ["control flow", asynchronous]}}
-Inside an `async` function, the word `await` can be put in front of an
-expression to wait for a promise to resolve and only then continue
-the execution of the function.
+Inside an `async` function, the word `await` can be put in front of an expression to wait for a promise to resolve and only then continue the execution of the function.
-Such a function no longer, like a regular JavaScript function, runs
-from start to completion in one go. Instead, it can be _frozen_ at any
-point that has an `await`, and can be resumed at a later time.
+Such a function no longer, like a regular JavaScript function, runs from start to completion in one go. Instead, it can be _frozen_ at any point that has an `await`, and can be resumed at a later time.
-For non-trivial asynchronous code, this notation is usually more
-convenient than directly using promises. Even if you need to do
-something that doesn't fit the synchronous model, such as perform
-multiple actions at the same time, it is easy to combine `await` with
-the direct use of promises.
+For non-trivial asynchronous code, this notation is usually more convenient than directly using promises. Even if you need to do something that doesn't fit the synchronous model, such as perform multiple actions at the same time, it is easy to combine `await` with the direct use of promises.
## Generators
{{index "async function"}}
-This ability of functions to be paused and then resumed again is not
-exclusive to `async` functions. JavaScript also has a feature called
-_((generator))_ functions. These are similar, but without the
-promises.
+This ability of functions to be paused and then resumed again is not exclusive to `async` functions. JavaScript also has a feature called _((generator))_ functions. These are similar, but without the promises.
-When you define a function with `function*` (placing an asterisk after
-the word `function`), it becomes a generator. When you call a
-generator, it returns an ((iterator)), which we already saw in
-[Chapter ?](object).
+When you define a function with `function*` (placing an asterisk after the word `function`), it becomes a generator. When you call a generator, it returns an ((iterator)), which we already saw in [Chapter ?](object).
```
function* powers(n) {
@@ -1008,17 +656,9 @@ for (let power of powers(3)) {
{{index "next method", "yield keyword"}}
-Initially, when you call `powers`, the function is frozen at its
-start. Every time you call `next` on the iterator, the function runs
-until it hits a `yield` expression, which pauses it and causes the
-yielded value to become the next value produced by the iterator. When
-the function returns (the one in the example never does), the iterator
-is done.
+Initially, when you call `powers`, the function is frozen at its start. Every time you call `next` on the iterator, the function runs until it hits a `yield` expression, which pauses it and causes the yielded value to become the next value produced by the iterator. When the function returns (the one in the example never does), the iterator is done.
-Writing iterators is often much easier when you use generator
-functions. The iterator for the `Group` class (from the exercise in
-[Chapter ?](object#group_iterator)) can be written with this
-generator:
+Writing iterators is often much easier when you use generator functions. The iterator for the `Group` class (from the exercise in [Chapter ?](object#group_iterator)) can be written with this generator:
{{index "Group class"}}
@@ -1039,47 +679,27 @@ class Group {
{{index [state, in iterator]}}
-There's no longer a need to create an object to hold the iteration
-state—generators automatically save their local state every time
-they yield.
+There's no longer a need to create an object to hold the iteration state—generators automatically save their local state every time they yield.
-Such `yield` expressions may occur only directly in the generator
-function itself and not in an inner function you define inside of it.
-The state a generator saves, when yielding, is only its _local_
-environment and the position where it yielded.
+Such `yield` expressions may occur only directly in the generator function itself and not in an inner function you define inside of it. The state a generator saves, when yielding, is only its _local_ environment and the position where it yielded.
{{index "await keyword"}}
-An `async` function is a special type of generator. It produces a
-promise when called, which is resolved when it returns (finishes) and
-rejected when it throws an exception. Whenever it yields (awaits) a
-promise, the result of that promise (value or thrown exception) is the
-result of the `await` expression.
+An `async` function is a special type of generator. It produces a promise when called, which is resolved when it returns (finishes) and rejected when it throws an exception. Whenever it yields (awaits) a promise, the result of that promise (value or thrown exception) is the result of the `await` expression.
## The event loop
{{index "asynchronous programming", scheduling, "event loop", timeline}}
-Asynchronous programs are executed piece by piece. Each piece may
-start some actions and schedule code to be executed when the action
-finishes or fails. In between these pieces, the program sits idle,
-waiting for the next action.
+Asynchronous programs are executed piece by piece. Each piece may start some actions and schedule code to be executed when the action finishes or fails. In between these pieces, the program sits idle, waiting for the next action.
{{index "setTimeout function"}}
-So callbacks are not directly called by the code that scheduled them.
-If I call `setTimeout` from within a function, that function will have
-returned by the time the callback function is called. And when the
-callback returns, control does not go back to the function that
-scheduled it.
+So callbacks are not directly called by the code that scheduled them. If I call `setTimeout` from within a function, that function will have returned by the time the callback function is called. And when the callback returns, control does not go back to the function that scheduled it.
{{index "Promise class", "catch keyword", "exception handling"}}
-Asynchronous behavior happens on its own empty function ((call
-stack)). This is one of the reasons that, without promises, managing
-exceptions across asynchronous code is hard. Since each callback
-starts with a mostly empty stack, your `catch` handlers won't be on
-the stack when they throw an exception.
+Asynchronous behavior happens on its own empty function ((call stack)). This is one of the reasons that, without promises, managing exceptions across asynchronous code is hard. Since each callback starts with a mostly empty stack, your `catch` handlers won't be on the stack when they throw an exception.
```
try {
@@ -1094,17 +714,9 @@ try {
{{index thread, queue}}
-No matter how closely together events—such as timeouts or incoming
-requests—happen, a JavaScript environment will run only one program at
-a time. You can think of this as it running a big loop _around_ your
-program, called the _event loop_. When there's nothing to be done,
-that loop is stopped. But as events come in, they are added to a queue,
-and their code is executed one after the other. Because no two things
-run at the same time, slow-running code might delay the handling of
-other events.
+No matter how closely together events—such as timeouts or incoming requests—happen, a JavaScript environment will run only one program at a time. You can think of this as it running a big loop _around_ your program, called the _event loop_. When there's nothing to be done, that loop is stopped. But as events come in, they are added to a queue, and their code is executed one after the other. Because no two things run at the same time, slow-running code might delay the handling of other events.
-This example sets a timeout but then dallies until after the
-timeout's intended point of time, causing the timeout to be late.
+This example sets a timeout but then dallies until after the timeout's intended point of time, causing the timeout to be late.
```
let start = Date.now();
@@ -1119,9 +731,7 @@ console.log("Wasted time until", Date.now() - start);
{{index "resolving (a promise)", "rejecting (a promise)", "Promise class"}}
-Promises always resolve or reject as a new event. Even if a promise is
-already resolved, waiting for it will cause your callback to run after
-the current script finishes, rather than right away.
+Promises always resolve or reject as a new event. Even if a promise is already resolved, waiting for it will cause your callback to run after the current script finishes, rather than right away.
```
Promise.resolve("Done").then(console.log);
@@ -1130,22 +740,15 @@ console.log("Me first!");
// → Done
```
-In later chapters we'll see various other types of events that run on
-the event loop.
+In later chapters we'll see various other types of events that run on the event loop.
## Asynchronous bugs
{{index "asynchronous programming", [state, transitions]}}
-When your program runs synchronously, in a single go, there are no
-state changes happening except those that the program itself
-makes. For asynchronous programs this is different—they may have
-_gaps_ in their execution during which other code can run.
+When your program runs synchronously, in a single go, there are no state changes happening except those that the program itself makes. For asynchronous programs this is different—they may have _gaps_ in their execution during which other code can run.
-Let's look at an example. One of the hobbies of our crows is to count
-the number of chicks that hatch throughout the village every year.
-Nests store this count in their storage bulbs. The following code tries to
-enumerate the counts from all the nests for a given year:
+Let's look at an example. One of the hobbies of our crows is to count the number of chicks that hatch throughout the village every year. Nests store this count in their storage bulbs. The following code tries to enumerate the counts from all the nests for a given year:
{{index "anyStorage function", "chicks function"}}
@@ -1168,18 +771,13 @@ async function chicks(nest, year) {
{{index "async function"}}
-The `async name =>` part shows that ((arrow function))s can also be
-made `async` by putting the word `async` in front of them.
+The `async name =>` part shows that ((arrow function))s can also be made `async` by putting the word `async` in front of them.
{{index "Promise.all function"}}
-The code doesn't immediately look suspicious...it maps the `async`
-arrow function over the set of nests, creating an array of promises,
-and then uses `Promise.all` to wait for all of these before returning
-the list they build up.
+The code doesn't immediately look suspicious...it maps the `async` arrow function over the set of nests, creating an array of promises, and then uses `Promise.all` to wait for all of these before returning the list they build up.
-But it is seriously broken. It'll always return only a single line of
-output, listing the nest that was slowest to respond.
+But it is seriously broken. It'll always return only a single line of output, listing the nest that was slowest to respond.
{{if interactive
@@ -1193,27 +791,15 @@ Can you work out why?
{{index "+= operator"}}
-The problem lies in the `+=` operator, which takes the _current_ value
-of `list` at the time where the statement starts executing and then,
-when the `await` finishes, sets the `list` binding to be that value
-plus the added string.
+The problem lies in the `+=` operator, which takes the _current_ value of `list` at the time where the statement starts executing and then, when the `await` finishes, sets the `list` binding to be that value plus the added string.
{{index "await keyword"}}
-But between the time where the statement starts executing and the time
-where it finishes there's an asynchronous gap. The `map` expression
-runs before anything has been added to the list, so each of the `+=`
-operators starts from an empty string and ends up, when its storage
-retrieval finishes, setting `list` to a single-line list—the result of
-adding its line to the empty string.
+But between the time where the statement starts executing and the time where it finishes there's an asynchronous gap. The `map` expression runs before anything has been added to the list, so each of the `+=` operators starts from an empty string and ends up, when its storage retrieval finishes, setting `list` to a single-line list—the result of adding its line to the empty string.
{{index "side effect"}}
-This could have easily been avoided by returning the lines from the
-mapped promises and calling `join` on the result of `Promise.all`,
-instead of building up the list by changing a binding. As usual,
-computing new values is less error-prone than changing existing
-values.
+This could have easily been avoided by returning the lines from the mapped promises and calling `join` on the result of `Promise.all`, instead of building up the list by changing a binding. As usual, computing new values is less error-prone than changing existing values.
{{index "chicks function"}}
@@ -1227,26 +813,13 @@ async function chicks(nest, year) {
}
```
-Mistakes like this are easy to make, especially when using `await`,
-and you should be aware of where the gaps in your code occur. An
-advantage of JavaScript's _explicit_ asynchronicity (whether through
-callbacks, promises, or `await`) is that spotting these gaps is
-relatively easy.
+Mistakes like this are easy to make, especially when using `await`, and you should be aware of where the gaps in your code occur. An advantage of JavaScript's _explicit_ asynchronicity (whether through callbacks, promises, or `await`) is that spotting these gaps is relatively easy.
## Summary
-Asynchronous programming makes it possible to express waiting for
-long-running actions without freezing the program during these
-actions. JavaScript environments typically implement this style of
-programming using callbacks, functions that are called when the
-actions complete. An event loop schedules such callbacks to be called
-when appropriate, one after the other, so that their execution does
-not overlap.
+Asynchronous programming makes it possible to express waiting for long-running actions without freezing the program during these actions. JavaScript environments typically implement this style of programming using callbacks, functions that are called when the actions complete. An event loop schedules such callbacks to be called when appropriate, one after the other, so that their execution does not overlap.
-Programming asynchronously is made easier by promises, objects that
-represent actions that might complete in the future, and `async`
-functions, which allow you to write an asynchronous program as if it
-were synchronous.
+Programming asynchronously is made easier by promises, objects that represent actions that might complete in the future, and `async` functions, which allow you to write an asynchronous program as if it were synchronous.
## Exercises
@@ -1254,31 +827,19 @@ were synchronous.
{{index "scalpel (exercise)"}}
-The village crows own an old scalpel that they occasionally use on
-special missions—say, to cut through screen doors or packaging. To be
-able to quickly track it down, every time the scalpel is moved to
-another nest, an entry is added to the storage of both the nest that
-had it and the nest that took it, under the name `"scalpel"`, with its
-new location as the value.
+The village crows own an old scalpel that they occasionally use on special missions—say, to cut through screen doors or packaging. To be able to quickly track it down, every time the scalpel is moved to another nest, an entry is added to the storage of both the nest that had it and the nest that took it, under the name `"scalpel"`, with its new location as the value.
-This means that finding the scalpel is a matter of following the
-breadcrumb trail of storage entries, until you find a nest where that
-points at the nest itself.
+This means that finding the scalpel is a matter of following the breadcrumb trail of storage entries, until you find a nest where that points at the nest itself.
{{index "anyStorage function", "async function"}}
-Write an `async` function `locateScalpel` that does this, starting at
-the nest on which it runs. You can use the `anyStorage` function
-defined earlier to access storage in arbitrary nests. The scalpel has
-been going around long enough that you may assume that every nest has
-a `"scalpel"` entry in its data storage.
+Write an `async` function `locateScalpel` that does this, starting at the nest on which it runs. You can use the `anyStorage` function defined earlier to access storage in arbitrary nests. The scalpel has been going around long enough that you may assume that every nest has a `"scalpel"` entry in its data storage.
Next, write the same function again without using `async` and `await`.
{{index "exception handling"}}
-Do request failures properly show up as rejections of the returned
-promise in both versions? How?
+Do request failures properly show up as rejections of the returned promise in both versions? How?
{{if interactive
@@ -1301,35 +862,19 @@ if}}
{{index "scalpel (exercise)"}}
-This can be done with a single loop that searches through the nests,
-moving forward to the next when it finds a value that doesn't match
-the current nest's name and returning the name when it finds a
-matching value. In the `async` function, a regular `for` or `while`
-loop can be used.
+This can be done with a single loop that searches through the nests, moving forward to the next when it finds a value that doesn't match the current nest's name and returning the name when it finds a matching value. In the `async` function, a regular `for` or `while` loop can be used.
{{index recursion}}
-To do the same in a plain function, you will have to build your loop
-using a recursive function. The easiest way to do this is to have that
-function return a promise by calling `then` on the promise that
-retrieves the storage value. Depending on whether that value matches
-the name of the current nest, the handler returns that value or a
-further promise created by calling the loop function again.
+To do the same in a plain function, you will have to build your loop using a recursive function. The easiest way to do this is to have that function return a promise by calling `then` on the promise that retrieves the storage value. Depending on whether that value matches the name of the current nest, the handler returns that value or a further promise created by calling the loop function again.
-Don't forget to start the loop by calling the recursive function once
-from the main function.
+Don't forget to start the loop by calling the recursive function once from the main function.
{{index "exception handling"}}
-In the `async` function, rejected promises are converted to exceptions
-by `await`. When an `async` function throws an exception, its promise
-is rejected. So that works.
+In the `async` function, rejected promises are converted to exceptions by `await`. When an `async` function throws an exception, its promise is rejected. So that works.
-If you implemented the non-`async` function as outlined earlier, the way
-`then` works also automatically causes a failure to end up in the
-returned promise. If a request fails, the handler passed to `then`
-isn't called, and the promise it returns is rejected with the same
-reason.
+If you implemented the non-`async` function as outlined earlier, the way `then` works also automatically causes a failure to end up in the returned promise. If a request fails, the handler passed to `then` isn't called, and the promise it returns is rejected with the same reason.
hint}}
@@ -1337,19 +882,11 @@ hint}}
{{index "Promise class", "Promise.all function", "building Promise.all (exercise)"}}
-Given an array of ((promise))s, `Promise.all` returns a promise that
-waits for all of the promises in the array to finish. It then
-succeeds, yielding an array of result values. If a promise
-in the array fails, the promise returned by `all` fails too, with the
-failure reason from the failing promise.
+Given an array of ((promise))s, `Promise.all` returns a promise that waits for all of the promises in the array to finish. It then succeeds, yielding an array of result values. If a promise in the array fails, the promise returned by `all` fails too, with the failure reason from the failing promise.
-Implement something like this yourself as a regular function
-called `Promise_all`.
+Implement something like this yourself as a regular function called `Promise_all`.
-Remember that after a promise has succeeded or failed, it can't
-succeed or fail again, and further calls to the functions that resolve
-it are ignored. This can simplify the way you handle failure of your
-promise.
+Remember that after a promise has succeeded or failed, it can't succeed or fail again, and further calls to the functions that resolve it are ignored. This can simplify the way you handle failure of your promise.
{{if interactive
@@ -1389,25 +926,12 @@ if}}
{{index "Promise.all function", "Promise class", "then method", "building Promise.all (exercise)"}}
-The function passed to the `Promise` constructor will have to call
-`then` on each of the promises in the given array. When one of them
-succeeds, two things need to happen. The resulting value needs to be
-stored in the correct position of a result array, and we must check
-whether this was the last pending ((promise)) and finish our own
-promise if it was.
+The function passed to the `Promise` constructor will have to call `then` on each of the promises in the given array. When one of them succeeds, two things need to happen. The resulting value needs to be stored in the correct position of a result array, and we must check whether this was the last pending ((promise)) and finish our own promise if it was.
{{index "counter variable"}}
-The latter can be done with a counter that is initialized to the
-length of the input array and from which we subtract 1 every time a
-promise succeeds. When it reaches 0, we are done. Make sure you take
-into account the situation where the input array is empty (and thus no
-promise will ever resolve).
-
-Handling failure requires some thought but turns out to be extremely
-simple. Just pass the `reject` function of the wrapping promise to
-each of the promises in the array as a `catch` handler or as a second
-argument to `then` so that a failure in one of them triggers the
-rejection of the whole wrapper promise.
+The latter can be done with a counter that is initialized to the length of the input array and from which we subtract 1 every time a promise succeeds. When it reaches 0, we are done. Make sure you take into account the situation where the input array is empty (and thus no promise will ever resolve).
+
+Handling failure requires some thought but turns out to be extremely simple. Just pass the `reject` function of the wrapping promise to each of the promises in the array as a `catch` handler or as a second argument to `then` so that a failure in one of them triggers the rejection of the whole wrapper promise.
hint}}
diff --git a/12_language.md b/12_language.md
index 4e4413398..de8ddd6f3 100644
--- a/12_language.md
+++ b/12_language.md
@@ -4,8 +4,7 @@
{{quote {author: "Hal Abelson and Gerald Sussman", title: "Structure and Interpretation of Computer Programs", chapter: true}
-The evaluator, which determines the meaning of expressions in a
-programming language, is just another program.
+The evaluator, which determines the meaning of expressions in a programming language, is just another program.
quote}}
@@ -13,21 +12,13 @@ quote}}
{{figure {url: "img/chapter_picture_12.jpg", alt: "Picture of an egg with smaller eggs inside", chapter: "framed"}}}
-Building your own ((programming language)) is surprisingly easy (as
-long as you do not aim too high) and very enlightening.
+Building your own ((programming language)) is surprisingly easy (as long as you do not aim too high) and very enlightening.
-The main thing I want to show in this chapter is that there is no
-((magic)) involved in building your own language. I've often felt that
-some human inventions were so immensely clever and complicated that
-I'd never be able to understand them. But with a little reading and
-experimenting, they often turn out to be quite mundane.
+The main thing I want to show in this chapter is that there is no ((magic)) involved in building your own language. I've often felt that some human inventions were so immensely clever and complicated that I'd never be able to understand them. But with a little reading and experimenting, they often turn out to be quite mundane.
{{index "Egg language", [abstraction, "in Egg"]}}
-We will build a programming language called Egg. It will be a tiny,
-simple language—but one that is powerful enough to express any
-computation you can think of. It will allow simple ((abstraction))
-based on ((function))s.
+We will build a programming language called Egg. It will be a tiny, simple language—but one that is powerful enough to express any computation you can think of. It will allow simple ((abstraction)) based on ((function))s.
{{id parsing}}
@@ -35,32 +26,19 @@ based on ((function))s.
{{index parsing, validation, [syntax, "of Egg"]}}
-The most immediately visible part of a programming language is its
-_syntax_, or notation. A _parser_ is a program that reads a piece
-of text and produces a data structure that reflects the structure of
-the program contained in that text. If the text does not form a valid
-program, the parser should point out the error.
+The most immediately visible part of a programming language is its _syntax_, or notation. A _parser_ is a program that reads a piece of text and produces a data structure that reflects the structure of the program contained in that text. If the text does not form a valid program, the parser should point out the error.
{{index "special form", [function, application]}}
-Our language will have a simple and uniform syntax. Everything in Egg
-is an ((expression)). An expression can be the name of a binding, a
-number, a string, or an _application_. Applications are used for
-function calls but also for constructs such as `if` or `while`.
+Our language will have a simple and uniform syntax. Everything in Egg is an ((expression)). An expression can be the name of a binding, a number, a string, or an _application_. Applications are used for function calls but also for constructs such as `if` or `while`.
{{index "double-quote character", parsing, [escaping, "in strings"], [whitespace, syntax]}}
-To keep the parser simple, strings in Egg do not support anything like
-backslash escapes. A string is simply a sequence of characters that
-are not double quotes, wrapped in double quotes. A number is a
-sequence of digits. Binding names can consist of any character that is
-not whitespace and that does not have a special meaning in the syntax.
+To keep the parser simple, strings in Egg do not support anything like backslash escapes. A string is simply a sequence of characters that are not double quotes, wrapped in double quotes. A number is a sequence of digits. Binding names can consist of any character that is not whitespace and that does not have a special meaning in the syntax.
{{index "comma character", [parentheses, arguments]}}
-Applications are written the way they are in JavaScript, by putting
-parentheses after an expression and having any number of
-((argument))s between those parentheses, separated by commas.
+Applications are written the way they are in JavaScript, by putting parentheses after an expression and having any number of ((argument))s between those parentheses, separated by commas.
```{lang: null}
do(define(x, 10),
@@ -71,29 +49,15 @@ do(define(x, 10),
{{index block, [syntax, "of Egg"]}}
-The ((uniformity)) of the ((Egg language)) means that things that are
-((operator))s in JavaScript (such as `>`) are normal bindings in this
-language, applied just like other ((function))s. And since the
-syntax has no concept of a block, we need a `do` construct to
-represent doing multiple things in sequence.
+The ((uniformity)) of the ((Egg language)) means that things that are ((operator))s in JavaScript (such as `>`) are normal bindings in this language, applied just like other ((function))s. And since the syntax has no concept of a block, we need a `do` construct to represent doing multiple things in sequence.
{{index "type property", parsing, ["data structure", tree]}}
-The data structure that the parser will use to describe a program
-consists of ((expression)) objects, each of which has a `type`
-property indicating the kind of expression it is and other properties
-to describe its content.
+The data structure that the parser will use to describe a program consists of ((expression)) objects, each of which has a `type` property indicating the kind of expression it is and other properties to describe its content.
{{index identifier}}
-Expressions of type `"value"` represent literal strings or numbers.
-Their `value` property contains the string or number value that they
-represent. Expressions of type `"word"` are used for identifiers
-(names). Such objects have a `name` property that holds the
-identifier's name as a string. Finally, `"apply"` expressions
-represent applications. They have an `operator` property that refers
-to the expression that is being applied, as well as an `args` property that
-holds an array of argument expressions.
+Expressions of type `"value"` represent literal strings or numbers. Their `value` property contains the string or number value that they represent. Expressions of type `"word"` are used for identifiers (names). Such objects have a `name` property that holds the identifier's name as a string. Finally, `"apply"` expressions represent applications. They have an `operator` property that refers to the expression that is being applied, as well as an `args` property that holds an array of argument expressions.
The `>(x, 5)` part of the previous program would be represented like this:
@@ -110,44 +74,25 @@ The `>(x, 5)` part of the previous program would be represented like this:
{{indexsee "abstract syntax tree", "syntax tree", ["data structure", tree]}}
-Such a data structure is called a _((syntax tree))_. If you
-imagine the objects as dots and the links between them as lines
-between those dots, it has a ((tree))like shape. The fact that
-expressions contain other expressions, which in turn might contain
-more expressions, is similar to the way tree branches split and split
-again.
+Such a data structure is called a _((syntax tree))_. If you imagine the objects as dots and the links between them as lines between those dots, it has a ((tree))like shape. The fact that expressions contain other expressions, which in turn might contain more expressions, is similar to the way tree branches split and split again.
{{figure {url: "img/syntax_tree.svg", alt: "The structure of a syntax tree",width: "5cm"}}}
{{index parsing}}
-Contrast this to the parser we wrote for the configuration file format
-in [Chapter ?](regexp#ini), which had a simple structure: it split the
-input into lines and handled those lines one at a time. There were
-only a few simple forms that a line was allowed to have.
+Contrast this to the parser we wrote for the configuration file format in [Chapter ?](regexp#ini), which had a simple structure: it split the input into lines and handled those lines one at a time. There were only a few simple forms that a line was allowed to have.
{{index recursion, [nesting, "of expressions"]}}
-Here we must find a different approach. Expressions are not separated
-into lines, and they have a recursive structure. Application
-expressions _contain_ other expressions.
+Here we must find a different approach. Expressions are not separated into lines, and they have a recursive structure. Application expressions _contain_ other expressions.
{{index elegance}}
-Fortunately, this problem can be solved very well by writing a parser
-function that is recursive in a way that reflects the recursive nature
-of the language.
+Fortunately, this problem can be solved very well by writing a parser function that is recursive in a way that reflects the recursive nature of the language.
{{index "parseExpression function", "syntax tree"}}
-We define a function `parseExpression`, which takes a string as input
-and returns an object containing the data structure for the expression
-at the start of the string, along with the part of the string left
-after parsing this expression. When parsing subexpressions (the
-argument to an application, for example), this function can be called
-again, yielding the argument expression as well as the text that
-remains. This text may in turn contain more arguments or may be the
-closing parenthesis that ends the list of arguments.
+We define a function `parseExpression`, which takes a string as input and returns an object containing the data structure for the expression at the start of the string, along with the part of the string left after parsing this expression. When parsing subexpressions (the argument to an application, for example), this function can be called again, yielding the argument expression as well as the text that remains. This text may in turn contain more arguments or may be the closing parenthesis that ends the list of arguments.
This is the first part of the parser:
@@ -177,30 +122,15 @@ function skipSpace(string) {
{{index "skipSpace function", [whitespace, syntax]}}
-Because Egg, like JavaScript, allows any amount of whitespace
-between its elements, we have to repeatedly cut the whitespace off the
-start of the program string. That is what the `skipSpace` function
-helps with.
+Because Egg, like JavaScript, allows any amount of whitespace between its elements, we have to repeatedly cut the whitespace off the start of the program string. That is what the `skipSpace` function helps with.
{{index "literal expression", "SyntaxError type"}}
-After skipping any leading space, `parseExpression` uses three
-((regular expression))s to spot the three atomic elements that Egg
-supports: strings, numbers, and words. The parser constructs a
-different kind of data structure depending on which one matches. If
-the input does not match one of these three forms, it is not a valid
-expression, and the parser throws an error. We use `SyntaxError`
-instead of `Error` as the exception constructor, which is another standard
-error type, because it is a little more specific—it is also the error
-type thrown when an attempt is made to run an invalid JavaScript
-program.
+After skipping any leading space, `parseExpression` uses three ((regular expression))s to spot the three atomic elements that Egg supports: strings, numbers, and words. The parser constructs a different kind of data structure depending on which one matches. If the input does not match one of these three forms, it is not a valid expression, and the parser throws an error. We use `SyntaxError` instead of `Error` as the exception constructor, which is another standard error type, because it is a little more specific—it is also the error type thrown when an attempt is made to run an invalid JavaScript program.
{{index "parseApply function"}}
-We then cut off the part that was matched from the program string and
-pass that, along with the object for the expression, to `parseApply`,
-which checks whether the expression is an application. If so, it
-parses a parenthesized list of arguments.
+We then cut off the part that was matched from the program string and pass that, along with the object for the expression, to `parseApply`, which checks whether the expression is an application. If so, it parses a parenthesized list of arguments.
```{includeCode: true}
function parseApply(expr, program) {
@@ -227,29 +157,17 @@ function parseApply(expr, program) {
{{index parsing}}
-If the next character in the program is not an opening parenthesis,
-this is not an application, and `parseApply` returns the expression it
-was given.
+If the next character in the program is not an opening parenthesis, this is not an application, and `parseApply` returns the expression it was given.
{{index recursion}}
-Otherwise, it skips the opening parenthesis and creates the ((syntax
-tree)) object for this application expression. It then recursively
-calls `parseExpression` to parse each argument until a closing
-parenthesis is found. The recursion is indirect, through `parseApply`
-and `parseExpression` calling each other.
+Otherwise, it skips the opening parenthesis and creates the ((syntax tree)) object for this application expression. It then recursively calls `parseExpression` to parse each argument until a closing parenthesis is found. The recursion is indirect, through `parseApply` and `parseExpression` calling each other.
-Because an application expression can itself be applied (such as in
-`multiplier(2)(1)`), `parseApply` must, after it has parsed an
-application, call itself again to check whether another pair of
-parentheses follows.
+Because an application expression can itself be applied (such as in `multiplier(2)(1)`), `parseApply` must, after it has parsed an application, call itself again to check whether another pair of parentheses follows.
{{index "syntax tree", "Egg language", "parse function"}}
-This is all we need to parse Egg. We wrap it in a convenient `parse`
-function that verifies that it has reached the end of the input string
-after parsing the expression (an Egg program is a single expression),
-and that gives us the program's data structure.
+This is all we need to parse Egg. We wrap it in a convenient `parse` function that verifies that it has reached the end of the input string after parsing the expression (an Egg program is a single expression), and that gives us the program's data structure.
```{includeCode: strip_log, test: join}
function parse(program) {
@@ -269,20 +187,13 @@ console.log(parse("+(a, 10)"));
{{index "error message"}}
-It works! It doesn't give us very helpful information when it fails
-and doesn't store the line and column on which each expression starts,
-which might be helpful when reporting errors later, but it's good
-enough for our purposes.
+It works! It doesn't give us very helpful information when it fails and doesn't store the line and column on which each expression starts, which might be helpful when reporting errors later, but it's good enough for our purposes.
## The evaluator
{{index "evaluate function", evaluation, interpretation, "syntax tree", "Egg language"}}
-What can we do with the syntax tree for a program? Run it, of course!
-And that is what the evaluator does. You give it a syntax tree and a
-scope object that associates names with values, and it will evaluate
-the expression that the tree represents and return the value that this
-produces.
+What can we do with the syntax tree for a program? Run it, of course! And that is what the evaluator does. You give it a syntax tree and a scope object that associates names with values, and it will evaluate the expression that the tree represents and return the value that this produces.
```{includeCode: true}
const specialForms = Object.create(null);
@@ -316,45 +227,27 @@ function evaluate(expr, scope) {
{{index "literal expression", scope}}
-The evaluator has code for each of the ((expression)) types. A literal
-value expression produces its value. (For example, the expression
-`100` just evaluates to the number 100.) For a binding, we must check
-whether it is actually defined in the scope and, if it is, fetch the
-binding's value.
+The evaluator has code for each of the ((expression)) types. A literal value expression produces its value. (For example, the expression `100` just evaluates to the number 100.) For a binding, we must check whether it is actually defined in the scope and, if it is, fetch the binding's value.
{{index [function, application]}}
-Applications are more involved. If they are a ((special form)), like
-`if`, we do not evaluate anything and pass the argument expressions,
-along with the scope, to the function that handles this form. If it is
-a normal call, we evaluate the operator, verify that it is a function,
-and call it with the evaluated arguments.
+Applications are more involved. If they are a ((special form)), like `if`, we do not evaluate anything and pass the argument expressions, along with the scope, to the function that handles this form. If it is a normal call, we evaluate the operator, verify that it is a function, and call it with the evaluated arguments.
-We use plain JavaScript function values to represent Egg's function
-values. We will come back to this [later](language#egg_fun), when the
-special form called `fun` is defined.
+We use plain JavaScript function values to represent Egg's function values. We will come back to this [later](language#egg_fun), when the special form called `fun` is defined.
{{index readability, "evaluate function", recursion, parsing}}
-The recursive structure of `evaluate` resembles the similar structure
-of the parser, and both mirror the structure of the language itself.
-It would also be possible to integrate the parser with the evaluator
-and evaluate during parsing, but splitting them up this way makes the
-program clearer.
+The recursive structure of `evaluate` resembles the similar structure of the parser, and both mirror the structure of the language itself. It would also be possible to integrate the parser with the evaluator and evaluate during parsing, but splitting them up this way makes the program clearer.
{{index "Egg language", interpretation}}
-This is really all that is needed to interpret Egg. It is that simple.
-But without defining a few special forms and adding some useful values
-to the ((environment)), you can't do much with this language yet.
+This is really all that is needed to interpret Egg. It is that simple. But without defining a few special forms and adding some useful values to the ((environment)), you can't do much with this language yet.
## Special forms
{{index "special form", "specialForms object"}}
-The `specialForms` object is used to define special syntax in Egg. It
-associates words with functions that evaluate such forms. It is
-currently empty. Let's add `if`.
+The `specialForms` object is used to define special syntax in Egg. It associates words with functions that evaluate such forms. It is currently empty. Let's add `if`.
```{includeCode: true}
specialForms.if = (args, scope) => {
@@ -370,26 +263,15 @@ specialForms.if = (args, scope) => {
{{index "conditional execution", "ternary operator", "?: operator", "conditional operator"}}
-Egg's `if` construct expects exactly three arguments. It will evaluate
-the first, and if the result isn't the value `false`, it will evaluate
-the second. Otherwise, the third gets evaluated. This `if` form is
-more similar to JavaScript's ternary `?:` operator than to
-JavaScript's `if`. It is an expression, not a statement, and it
-produces a value, namely, the result of the second or third argument.
+Egg's `if` construct expects exactly three arguments. It will evaluate the first, and if the result isn't the value `false`, it will evaluate the second. Otherwise, the third gets evaluated. This `if` form is more similar to JavaScript's ternary `?:` operator than to JavaScript's `if`. It is an expression, not a statement, and it produces a value, namely, the result of the second or third argument.
{{index Boolean}}
-Egg also differs from JavaScript in how it handles the condition value
-to `if`. It will not treat things like zero or the empty string as
-false, only the precise value `false`.
+Egg also differs from JavaScript in how it handles the condition value to `if`. It will not treat things like zero or the empty string as false, only the precise value `false`.
{{index "short-circuit evaluation"}}
-The reason we need to represent `if` as a special form, rather than a
-regular function, is that all arguments to functions are evaluated
-before the function is called, whereas `if` should evaluate only
-_either_ its second or its third argument, depending on the value of
-the first.
+The reason we need to represent `if` as a special form, rather than a regular function, is that all arguments to functions are evaluated before the function is called, whereas `if` should evaluate only _either_ its second or its third argument, depending on the value of the first.
The `while` form is similar.
@@ -408,9 +290,7 @@ specialForms.while = (args, scope) => {
};
```
-Another basic building block is `do`, which executes all its arguments
-from top to bottom. Its value is the value produced by the last
-argument.
+Another basic building block is `do`, which executes all its arguments from top to bottom. Its value is the value produced by the last argument.
```{includeCode: true}
specialForms.do = (args, scope) => {
@@ -424,12 +304,7 @@ specialForms.do = (args, scope) => {
{{index ["= operator", "in Egg"], [binding, "in Egg"]}}
-To be able to create bindings and give them new values, we also
-create a form called `define`. It expects a word as its first argument
-and an expression producing the value to assign to that word as its
-second argument. Since `define`, like everything, is an expression, it
-must return a value. We'll make it return the value that was assigned
-(just like JavaScript's `=` operator).
+To be able to create bindings and give them new values, we also create a form called `define`. It expects a word as its first argument and an expression producing the value to assign to that word as its second argument. Since `define`, like everything, is an expression, it must return a value. We'll make it return the value that was assigned (just like JavaScript's `=` operator).
```{includeCode: true}
specialForms.define = (args, scope) => {
@@ -446,15 +321,9 @@ specialForms.define = (args, scope) => {
{{index "Egg language", "evaluate function", [binding, "in Egg"]}}
-The ((scope)) accepted by `evaluate` is an object with properties
-whose names correspond to binding names and whose values correspond to
-the values those bindings are bound to. Let's define an object to
-represent the ((global scope)).
+The ((scope)) accepted by `evaluate` is an object with properties whose names correspond to binding names and whose values correspond to the values those bindings are bound to. Let's define an object to represent the ((global scope)).
-To be able to use the `if` construct we just defined, we must have
-access to ((Boolean)) values. Since there are only two Boolean values,
-we do not need special syntax for them. We simply bind two names to
-the values `true` and `false` and use them.
+To be able to use the `if` construct we just defined, we must have access to ((Boolean)) values. Since there are only two Boolean values, we do not need special syntax for them. We simply bind two names to the values `true` and `false` and use them.
```{includeCode: true}
const topScope = Object.create(null);
@@ -473,11 +342,7 @@ console.log(evaluate(prog, topScope));
{{index arithmetic, "Function constructor"}}
-To supply basic ((arithmetic)) and ((comparison)) ((operator))s, we
-will also add some function values to the ((scope)). In the interest
-of keeping the code short, we'll use `Function` to synthesize a bunch
-of operator functions in a loop, instead of defining them
-individually.
+To supply basic ((arithmetic)) and ((comparison)) ((operator))s, we will also add some function values to the ((scope)). In the interest of keeping the code short, we'll use `Function` to synthesize a bunch of operator functions in a loop, instead of defining them individually.
```{includeCode: true}
for (let op of ["+", "-", "*", "/", "==", "<", ">"]) {
@@ -485,8 +350,7 @@ for (let op of ["+", "-", "*", "/", "==", "<", ">"]) {
}
```
-A way to ((output)) values is also useful, so we'll wrap
-`console.log` in a function and call it `print`.
+A way to ((output)) values is also useful, so we'll wrap `console.log` in a function and call it `print`.
```{includeCode: true}
topScope.print = value => {
@@ -497,9 +361,7 @@ topScope.print = value => {
{{index parsing, "run function"}}
-That gives us enough elementary tools to write simple programs. The
-following function provides a convenient way to parse a program and
-run it in a fresh scope:
+That gives us enough elementary tools to write simple programs. The following function provides a convenient way to parse a program and run it in a fresh scope:
```{includeCode: true}
function run(program) {
@@ -509,9 +371,7 @@ function run(program) {
{{index "Object.create function", prototype}}
-We'll use object prototype chains to represent nested scopes so that
-the program can add bindings to its local scope without changing the
-top-level scope.
+We'll use object prototype chains to represent nested scopes so that the program can add bindings to its local scope without changing the top-level scope.
```
run(`
@@ -527,10 +387,7 @@ do(define(total, 0),
{{index "summing example", "Egg language"}}
-This is the program we've seen several times before, which computes
-the sum of the numbers 1 to 10, expressed in Egg. It is clearly uglier
-than the equivalent JavaScript program—but not bad for a language
-implemented in less than 150 ((lines of code)).
+This is the program we've seen several times before, which computes the sum of the numbers 1 to 10, expressed in Egg. It is clearly uglier than the equivalent JavaScript program—but not bad for a language implemented in less than 150 ((lines of code)).
{{id egg_fun}}
@@ -538,12 +395,9 @@ implemented in less than 150 ((lines of code)).
{{index function, "Egg language"}}
-A programming language without functions is a poor programming
-language indeed.
+A programming language without functions is a poor programming language indeed.
-Fortunately, it isn't hard to add a `fun` construct, which treats its
-last argument as the function's body and uses all arguments before
-that as the names of the function's parameters.
+Fortunately, it isn't hard to add a `fun` construct, which treats its last argument as the function's body and uses all arguments before that as the names of the function's parameters.
```{includeCode: true}
specialForms.fun = (args, scope) => {
@@ -573,10 +427,7 @@ specialForms.fun = (args, scope) => {
{{index "local scope"}}
-Functions in Egg get their own local scope. The function produced by
-the `fun` form creates this local scope and adds the argument bindings
-to it. It then evaluates the function body in this scope and returns
-the result.
+Functions in Egg get their own local scope. The function produced by the `fun` form creates this local scope and adds the argument bindings to it. It then evaluates the function body in this scope and returns the result.
```{startCode: true}
run(`
@@ -599,70 +450,35 @@ do(define(pow, fun(base, exp,
{{index interpretation, compilation}}
-What we have built is an interpreter. During evaluation, it acts
-directly on the representation of the program produced by the parser.
+What we have built is an interpreter. During evaluation, it acts directly on the representation of the program produced by the parser.
{{index efficiency, performance, [binding, definition], [memory, speed]}}
-_Compilation_ is the process of adding another step between the
-parsing and the running of a program, which transforms the program
-into something that can be evaluated more efficiently by doing as much
-work as possible in advance. For example, in well-designed languages
-it is obvious, for each use of a binding, which binding is being
-referred to, without actually running the program. This can be used to
-avoid looking up the binding by name every time it is accessed,
-instead directly fetching it from some predetermined memory
-location.
-
-Traditionally, ((compilation)) involves converting the program to
-((machine code)), the raw format that a computer's processor can
-execute. But any process that converts a program to a different
-representation can be thought of as compilation.
+_Compilation_ is the process of adding another step between the parsing and the running of a program, which transforms the program into something that can be evaluated more efficiently by doing as much work as possible in advance. For example, in well-designed languages it is obvious, for each use of a binding, which binding is being referred to, without actually running the program. This can be used to avoid looking up the binding by name every time it is accessed, instead directly fetching it from some predetermined memory location.
+
+Traditionally, ((compilation)) involves converting the program to ((machine code)), the raw format that a computer's processor can execute. But any process that converts a program to a different representation can be thought of as compilation.
{{index simplicity, "Function constructor", transpilation}}
-It would be possible to write an alternative ((evaluation)) strategy
-for Egg, one that first converts the program to a JavaScript program,
-uses `Function` to invoke the JavaScript compiler on it, and then runs
-the result. When done right, this would make Egg run very fast while
-still being quite simple to implement.
+It would be possible to write an alternative ((evaluation)) strategy for Egg, one that first converts the program to a JavaScript program, uses `Function` to invoke the JavaScript compiler on it, and then runs the result. When done right, this would make Egg run very fast while still being quite simple to implement.
-If you are interested in this topic and willing to spend some time on
-it, I encourage you to try to implement such a compiler as an
-exercise.
+If you are interested in this topic and willing to spend some time on it, I encourage you to try to implement such a compiler as an exercise.
## Cheating
{{index "Egg language"}}
-When we defined `if` and `while`, you probably noticed that they were
-more or less trivial wrappers around JavaScript's own `if` and
-`while`. Similarly, the values in Egg are just regular old JavaScript
-values.
+When we defined `if` and `while`, you probably noticed that they were more or less trivial wrappers around JavaScript's own `if` and `while`. Similarly, the values in Egg are just regular old JavaScript values.
-If you compare the implementation of Egg, built on top of JavaScript,
-with the amount of work and complexity required to build a programming
-language directly on the raw functionality provided by a machine, the
-difference is huge. Regardless, this example ideally gave you an
-impression of the way ((programming language))s work.
+If you compare the implementation of Egg, built on top of JavaScript, with the amount of work and complexity required to build a programming language directly on the raw functionality provided by a machine, the difference is huge. Regardless, this example ideally gave you an impression of the way ((programming language))s work.
-And when it comes to getting something done, cheating is more
-effective than doing everything yourself. Though the toy language in
-this chapter doesn't do anything that couldn't be done better in
-JavaScript, there _are_ situations where writing small languages helps
-get real work done.
+And when it comes to getting something done, cheating is more effective than doing everything yourself. Though the toy language in this chapter doesn't do anything that couldn't be done better in JavaScript, there _are_ situations where writing small languages helps get real work done.
-Such a language does not have to resemble a typical programming
-language. If JavaScript didn't come equipped with regular expressions,
-for example, you could write your own parser and evaluator for regular
-expressions.
+Such a language does not have to resemble a typical programming language. If JavaScript didn't come equipped with regular expressions, for example, you could write your own parser and evaluator for regular expressions.
{{index "artificial intelligence"}}
-Or imagine you are building a giant robotic ((dinosaur)) and need to
-program its ((behavior)). JavaScript might not be the most effective
-way to do this. You might instead opt for a language that looks like
-this:
+Or imagine you are building a giant robotic ((dinosaur)) and need to program its ((behavior)). JavaScript might not be the most effective way to do this. You might instead opt for a language that looks like this:
```{lang: null}
behavior walk
@@ -682,11 +498,7 @@ behavior attack
{{index expressivity}}
-This is what is usually called a _((domain-specific language))_, a
-language tailored to express a narrow domain of knowledge. Such a
-language can be more expressive than a general-purpose language
-because it is designed to describe exactly the things that need to be
-described in its domain, and nothing else.
+This is what is usually called a _((domain-specific language))_, a language tailored to express a narrow domain of knowledge. Such a language can be more expressive than a general-purpose language because it is designed to describe exactly the things that need to be described in its domain, and nothing else.
## Exercises
@@ -694,11 +506,7 @@ described in its domain, and nothing else.
{{index "Egg language", "arrays in egg (exercise)", [array, "in Egg"]}}
-Add support for arrays to Egg by adding the following three
-functions to the top scope: `array(...values)` to construct an array
-containing the argument values, `length(array)` to get an array's
-length, and `element(array, n)` to fetch the n^th^ element from an
-array.
+Add support for arrays to Egg by adding the following three functions to the top scope: `array(...values)` to construct an array containing the argument values, `length(array)` to get an array's length, and `element(array, n)` to fetch the n^th^ element from an array.
{{if interactive
@@ -730,14 +538,11 @@ if}}
{{index "arrays in egg (exercise)"}}
-The easiest way to do this is to represent Egg arrays with JavaScript
-arrays.
+The easiest way to do this is to represent Egg arrays with JavaScript arrays.
{{index "slice method"}}
-The values added to the top scope must be functions. By using a rest
-argument (with triple-dot notation), the definition of `array` can be
-_very_ simple.
+The values added to the top scope must be functions. By using a rest argument (with triple-dot notation), the definition of `array` can be _very_ simple.
hint}}
@@ -745,15 +550,9 @@ hint}}
{{index closure, [function, scope], "closure in egg (exercise)"}}
-The way we have defined `fun` allows functions in Egg to reference
-the surrounding scope, allowing the function's body to use local
-values that were visible at the time the function was defined, just
-like JavaScript functions do.
+The way we have defined `fun` allows functions in Egg to reference the surrounding scope, allowing the function's body to use local values that were visible at the time the function was defined, just like JavaScript functions do.
-The following program illustrates this: function `f` returns a
-function that adds its argument to `f`'s argument, meaning that it
-needs access to the local ((scope)) inside `f` to be able to use
-binding `a`.
+The following program illustrates this: function `f` returns a function that adds its argument to `f`'s argument, meaning that it needs access to the local ((scope)) inside `f` to be able to use binding `a`.
```
run(`
@@ -763,27 +562,17 @@ do(define(f, fun(a, fun(b, +(a, b)))),
// → 9
```
-Go back to the definition of the `fun` form and explain which
-mechanism causes this to work.
+Go back to the definition of the `fun` form and explain which mechanism causes this to work.
{{hint
{{index closure, "closure in egg (exercise)"}}
-Again, we are riding along on a JavaScript mechanism to get the
-equivalent feature in Egg. Special forms are passed the local scope in
-which they are evaluated so that they can evaluate their subforms in
-that scope. The function returned by `fun` has access to the `scope`
-argument given to its enclosing function and uses that to create the
-function's local ((scope)) when it is called.
+Again, we are riding along on a JavaScript mechanism to get the equivalent feature in Egg. Special forms are passed the local scope in which they are evaluated so that they can evaluate their subforms in that scope. The function returned by `fun` has access to the `scope` argument given to its enclosing function and uses that to create the function's local ((scope)) when it is called.
{{index compilation}}
-This means that the ((prototype)) of the local scope will be the scope
-in which the function was created, which makes it possible to access
-bindings in that scope from the function. This is all there is to
-implementing closure (though to compile it in a way that is actually
-efficient, you'd need to do some more work).
+This means that the ((prototype)) of the local scope will be the scope in which the function was created, which makes it possible to access bindings in that scope from the function. This is all there is to implementing closure (though to compile it in a way that is actually efficient, you'd need to do some more work).
hint}}
@@ -791,16 +580,11 @@ hint}}
{{index "hash character", "Egg language", "comments in egg (exercise)"}}
-It would be nice if we could write ((comment))s in Egg. For example,
-whenever we find a hash sign (`#`), we could treat the rest of the
-line as a comment and ignore it, similar to `//` in JavaScript.
+It would be nice if we could write ((comment))s in Egg. For example, whenever we find a hash sign (`#`), we could treat the rest of the line as a comment and ignore it, similar to `//` in JavaScript.
{{index "skipSpace function"}}
-We do not have to make any big changes to the parser to support this.
-We can simply change `skipSpace` to skip comments as if they are
-((whitespace)) so that all the points where `skipSpace` is called will
-now also skip comments. Make this change.
+We do not have to make any big changes to the parser to support this. We can simply change `skipSpace` to skip comments as if they are ((whitespace)) so that all the points where `skipSpace` is called will now also skip comments. Make this change.
{{if interactive
@@ -826,14 +610,9 @@ if}}
{{index "comments in egg (exercise)", [whitespace, syntax]}}
-Make sure your solution handles multiple comments in a row, with
-potentially whitespace between or after them.
+Make sure your solution handles multiple comments in a row, with potentially whitespace between or after them.
-A ((regular expression)) is probably the easiest way to solve this.
-Write something that matches "whitespace or a comment, zero or more
-times". Use the `exec` or `match` method and look at the length of the
-first element in the returned array (the whole match) to find out how
-many characters to slice off.
+A ((regular expression)) is probably the easiest way to solve this. Write something that matches "whitespace or a comment, zero or more times". Use the `exec` or `match` method and look at the length of the first element in the returned array (the whole match) to find out how many characters to slice off.
hint}}
@@ -841,32 +620,19 @@ hint}}
{{index [binding, definition], assignment, "fixing scope (exercise)"}}
-Currently, the only way to assign a binding a value is `define`.
-This construct acts as a way both to define new bindings and to give
-existing ones a new value.
+Currently, the only way to assign a binding a value is `define`. This construct acts as a way both to define new bindings and to give existing ones a new value.
{{index "local binding"}}
-This ((ambiguity)) causes a problem. When you try to give a nonlocal
-binding a new value, you will end up defining a local one with the
-same name instead. Some languages work like this by design, but I've
-always found it an awkward way to handle ((scope)).
+This ((ambiguity)) causes a problem. When you try to give a nonlocal binding a new value, you will end up defining a local one with the same name instead. Some languages work like this by design, but I've always found it an awkward way to handle ((scope)).
{{index "ReferenceError type"}}
-Add a special form `set`, similar to `define`, which gives a binding a
-new value, updating the binding in an outer scope if it doesn't
-already exist in the inner scope. If the binding is not defined at
-all, throw a `ReferenceError` (another standard error type).
+Add a special form `set`, similar to `define`, which gives a binding a new value, updating the binding in an outer scope if it doesn't already exist in the inner scope. If the binding is not defined at all, throw a `ReferenceError` (another standard error type).
{{index "hasOwnProperty method", prototype, "getPrototypeOf function"}}
-The technique of representing scopes as simple objects, which has made
-things convenient so far, will get in your way a little at this point.
-You might want to use the `Object.getPrototypeOf` function, which
-returns the prototype of an object. Also remember that scopes do not
-derive from `Object.prototype`, so if you want to call
-`hasOwnProperty` on them, you have to use this clumsy expression:
+The technique of representing scopes as simple objects, which has made things convenient so far, will get in your way a little at this point. You might want to use the `Object.getPrototypeOf` function, which returns the prototype of an object. Also remember that scopes do not derive from `Object.prototype`, so if you want to call `hasOwnProperty` on them, you have to use this clumsy expression:
```{test: no}
Object.prototype.hasOwnProperty.call(scope, name);
@@ -895,17 +661,10 @@ if}}
{{index [binding, "compilation of"], assignment, "getPrototypeOf function", "hasOwnProperty method", "fixing scope (exercise)"}}
-You will have to loop through one ((scope)) at a time, using
-`Object.getPrototypeOf` to go to the next outer scope. For each scope,
-use `hasOwnProperty` to find out whether the binding, indicated by the
-`name` property of the first argument to `set`, exists in that scope.
-If it does, set it to the result of evaluating the second argument to
-`set` and then return that value.
+You will have to loop through one ((scope)) at a time, using `Object.getPrototypeOf` to go to the next outer scope. For each scope, use `hasOwnProperty` to find out whether the binding, indicated by the `name` property of the first argument to `set`, exists in that scope. If it does, set it to the result of evaluating the second argument to `set` and then return that value.
{{index "global scope", "run-time error"}}
-If the outermost scope is reached (`Object.getPrototypeOf` returns
-null) and we haven't found the binding yet, it doesn't exist, and an
-error should be thrown.
+If the outermost scope is reached (`Object.getPrototypeOf` returns null) and we haven't found the binding yet, it doesn't exist, and an error should be thrown.
hint}}
diff --git a/13_browser.md b/13_browser.md
index 3ff233770..a24841150 100644
--- a/13_browser.md
+++ b/13_browser.md
@@ -2,10 +2,7 @@
{{quote {author: "Tim Berners-Lee", title: "The World Wide Web: A very short personal history", chapter: true}
-The dream behind the Web is of a common information space in which we
-communicate by sharing information. Its universality is essential: the
-fact that a hypertext link can point to anything, be it personal,
-local or global, be it draft or highly polished.
+The dream behind the Web is of a common information space in which we communicate by sharing information. Its universality is essential: the fact that a hypertext link can point to anything, be it personal, local or global, be it draft or highly polished.
quote}}
@@ -13,131 +10,69 @@ quote}}
{{figure {url: "img/chapter_picture_13.jpg", alt: "Picture of a telephone switchboard", chapter: "framed"}}}
-The next chapters of this book will talk about web browsers. Without
-web ((browser))s, there would be no JavaScript. Or even if there were,
-no one would ever have paid any attention to it.
+The next chapters of this book will talk about web browsers. Without web ((browser))s, there would be no JavaScript. Or even if there were, no one would ever have paid any attention to it.
{{index decentralization, compatibility}}
-Web technology has been decentralized from the start, not just
-technically but also in the way it evolved. Various browser vendors
-have added new functionality in ad hoc and sometimes poorly thought-out
-ways, which then, sometimes, ended up being adopted by others—and
-finally set down as in ((standards)).
+Web technology has been decentralized from the start, not just technically but also in the way it evolved. Various browser vendors have added new functionality in ad hoc and sometimes poorly thought-out ways, which then, sometimes, ended up being adopted by others—and finally set down as in ((standards)).
-This is both a blessing and a curse. On the one hand, it is empowering
-to not have a central party control a system but have it be improved
-by various parties working in loose ((collaboration)) (or occasionally
-open hostility). On the other hand, the haphazard way in which the Web
-was developed means that the resulting system is not exactly a shining
-example of internal ((consistency)). Some parts of it are downright
-confusing and poorly conceived.
+This is both a blessing and a curse. On the one hand, it is empowering to not have a central party control a system but have it be improved by various parties working in loose ((collaboration)) (or occasionally open hostility). On the other hand, the haphazard way in which the Web was developed means that the resulting system is not exactly a shining example of internal ((consistency)). Some parts of it are downright confusing and poorly conceived.
## Networks and the Internet
-Computer ((network))s have been around since the 1950s. If you put
-cables between two or more computers and allow them to send data back
-and forth through these cables, you can do all kinds of wonderful
-things.
+Computer ((network))s have been around since the 1950s. If you put cables between two or more computers and allow them to send data back and forth through these cables, you can do all kinds of wonderful things.
-And if connecting two machines in the same building allows us to do
-wonderful things, connecting machines all over the planet should be
-even better. The technology to start implementing this vision was
-developed in the 1980s, and the resulting network is called the
-_((Internet))_. It has lived up to its promise.
+And if connecting two machines in the same building allows us to do wonderful things, connecting machines all over the planet should be even better. The technology to start implementing this vision was developed in the 1980s, and the resulting network is called the _((Internet))_. It has lived up to its promise.
-A computer can use this network to shoot bits at another computer. For
-any effective ((communication)) to arise out of this bit-shooting, the
-computers on both ends must know what the bits are supposed to
-represent. The meaning of any given sequence of bits depends entirely
-on the kind of thing that it is trying to express and on the
-((encoding)) mechanism used.
+A computer can use this network to shoot bits at another computer. For any effective ((communication)) to arise out of this bit-shooting, the computers on both ends must know what the bits are supposed to represent. The meaning of any given sequence of bits depends entirely on the kind of thing that it is trying to express and on the ((encoding)) mechanism used.
{{index [network, protocol]}}
-A _network ((protocol))_ describes a style of communication over a
-((network)). There are protocols for sending email, for fetching email,
-for sharing files, and even for controlling computers that happen to be
-infected by malicious software.
+A _network ((protocol))_ describes a style of communication over a ((network)). There are protocols for sending email, for fetching email, for sharing files, and even for controlling computers that happen to be infected by malicious software.
{{indexsee "Hypertext Transfer Protocol", HTTP}}
-For example, the _Hypertext Transfer Protocol_ (((HTTP))) is
-a protocol for retrieving named ((resource))s (chunks of information,
-such as web pages or pictures). It specifies that the side making the
-request should start with a line like this, naming the resource and
-the version of the protocol that it is trying to use:
+For example, the _Hypertext Transfer Protocol_ (((HTTP))) is a protocol for retrieving named ((resource))s (chunks of information, such as web pages or pictures). It specifies that the side making the request should start with a line like this, naming the resource and the version of the protocol that it is trying to use:
```{lang: "text/plain"}
GET /index.html HTTP/1.1
```
-There are a lot more rules about the way the requester can include more
-information in the ((request)) and the way the other side, which
-returns the resource, packages up its content. We'll look at HTTP in a
-little more detail in [Chapter ?](http).
+There are a lot more rules about the way the requester can include more information in the ((request)) and the way the other side, which returns the resource, packages up its content. We'll look at HTTP in a little more detail in [Chapter ?](http).
{{index layering, stream, ordering}}
-Most protocols are built on top of other protocols. HTTP treats the
-network as a streamlike device into which you can put bits and have
-them arrive at the correct destination in the correct order. As we saw
-in [Chapter ?](async), ensuring those things is already a rather
-difficult problem.
+Most protocols are built on top of other protocols. HTTP treats the network as a streamlike device into which you can put bits and have them arrive at the correct destination in the correct order. As we saw in [Chapter ?](async), ensuring those things is already a rather difficult problem.
{{index TCP}}
{{indexsee "Transmission Control Protocol", TCP}}
-The _Transmission Control Protocol_ (TCP) is a ((protocol)) that
-addresses this problem. All Internet-connected devices "speak" it, and
-most communication on the ((Internet)) is built on top of it.
+The _Transmission Control Protocol_ (TCP) is a ((protocol)) that addresses this problem. All Internet-connected devices "speak" it, and most communication on the ((Internet)) is built on top of it.
{{index "listening (TCP)"}}
-A TCP ((connection)) works as follows: one computer must be waiting,
-or _listening_, for other computers to start talking to it. To be able
-to listen for different kinds of communication at the same time on a
-single machine, each listener has a number (called a _((port))_)
-associated with it. Most ((protocol))s specify which port should be
-used by default. For example, when we want to send an email using the
-((SMTP)) protocol, the machine through which we send it is expected to
-be listening on port 25.
-
-Another computer can then establish a ((connection)) by connecting to
-the target machine using the correct port number. If the target
-machine can be reached and is listening on that port, the connection
-is successfully created. The listening computer is called the
-_((server))_, and the connecting computer is called the _((client))_.
+A TCP ((connection)) works as follows: one computer must be waiting, or _listening_, for other computers to start talking to it. To be able to listen for different kinds of communication at the same time on a single machine, each listener has a number (called a _((port))_) associated with it. Most ((protocol))s specify which port should be used by default. For example, when we want to send an email using the ((SMTP)) protocol, the machine through which we send it is expected to be listening on port 25.
+
+Another computer can then establish a ((connection)) by connecting to the target machine using the correct port number. If the target machine can be reached and is listening on that port, the connection is successfully created. The listening computer is called the _((server))_, and the connecting computer is called the _((client))_.
{{index [abtraction, "of the network"]}}
-Such a connection acts as a two-way ((pipe)) through which bits can
-flow—the machines on both ends can put data into it. Once the bits are
-successfully transmitted, they can be read out again by the machine on
-the other side. This is a convenient model. You could say that ((TCP))
-provides an abstraction of the network.
+Such a connection acts as a two-way ((pipe)) through which bits can flow—the machines on both ends can put data into it. Once the bits are successfully transmitted, they can be read out again by the machine on the other side. This is a convenient model. You could say that ((TCP)) provides an abstraction of the network.
{{id web}}
## The Web
-The _((World Wide Web))_ (not to be confused with the ((Internet)) as
-a whole) is a set of ((protocol))s and formats that allow us to visit
-web pages in a browser. The "Web" part in the name refers to the fact
-that such pages can easily link to each other, thus connecting into a
-huge ((mesh)) that users can move through.
+The _((World Wide Web))_ (not to be confused with the ((Internet)) as a whole) is a set of ((protocol))s and formats that allow us to visit web pages in a browser. The "Web" part in the name refers to the fact that such pages can easily link to each other, thus connecting into a huge ((mesh)) that users can move through.
-To become part of the Web, all you need to do is connect a machine to
-the ((Internet)) and have it listen on port 80 with the ((HTTP))
-protocol so that other computers can ask it for documents.
+To become part of the Web, all you need to do is connect a machine to the ((Internet)) and have it listen on port 80 with the ((HTTP)) protocol so that other computers can ask it for documents.
{{index URL}}
{{indexsee "Uniform Resource Locator", URL}}
-Each ((document)) on the Web is named by a _Uniform Resource Locator_
-(URL), which looks something like this:
+Each ((document)) on the Web is named by a _Uniform Resource Locator_ (URL), which looks something like this:
```{lang: null}
http://eloquentjavascript.net/13_browser.html
@@ -147,30 +82,13 @@ Each ((document)) on the Web is named by a _Uniform Resource Locator_
{{index HTTPS}}
-The first part tells us that this URL uses the HTTP ((protocol)) (as
-opposed to, for example, encrypted HTTP, which would be _https://_).
-Then comes the part that identifies which ((server)) we are requesting
-the document from. Last is a path string that identifies the specific
-document (or _((resource))_) we are interested in.
-
-Machines connected to the Internet get an _((IP address))_, which is a
-number that can be used to send messages to that machine, and looks
-something like `149.210.142.219` or `2001:4860:4860::8888`. But lists
-of more or less random numbers are hard to remember and awkward to
-type, so you can instead register a _((domain)) name_ for a specific
-address or set of addresses. I registered _eloquentjavascript.net_ to
-point at the IP address of a machine I control and can thus use that
-domain name to serve web pages.
+The first part tells us that this URL uses the HTTP ((protocol)) (as opposed to, for example, encrypted HTTP, which would be _https://_). Then comes the part that identifies which ((server)) we are requesting the document from. Last is a path string that identifies the specific document (or _((resource))_) we are interested in.
+
+Machines connected to the Internet get an _((IP address))_, which is a number that can be used to send messages to that machine, and looks something like `149.210.142.219` or `2001:4860:4860::8888`. But lists of more or less random numbers are hard to remember and awkward to type, so you can instead register a _((domain)) name_ for a specific address or set of addresses. I registered _eloquentjavascript.net_ to point at the IP address of a machine I control and can thus use that domain name to serve web pages.
{{index browser}}
-If you type this URL into your browser's ((address bar)), the browser
-will try to retrieve and display the ((document)) at that URL. First,
-your browser has to find out what address _eloquentjavascript.net_
-refers to. Then, using the ((HTTP)) protocol, it will make a
-connection to the server at that address and ask for the resource
-_/13_browser.html_. If all goes well, the server sends back a
-document, which your browser then displays on your screen.
+If you type this URL into your browser's ((address bar)), the browser will try to retrieve and display the ((document)) at that URL. First, your browser has to find out what address _eloquentjavascript.net_ refers to. Then, using the ((HTTP)) protocol, it will make a connection to the server at that address and ask for the resource _/13_browser.html_. If all goes well, the server sends back a document, which your browser then displays on your screen.
## HTML
@@ -178,10 +96,7 @@ document, which your browser then displays on your screen.
{{indexsee "Hypertext Markup Language", HTML}}
-HTML, which stands for _Hypertext Markup Language_, is the document
-format used for web pages. An HTML document contains ((text)), as well
-as _((tag))s_ that give structure to the text, describing things such
-as links, paragraphs, and headings.
+HTML, which stands for _Hypertext Markup Language_, is the document format used for web pages. An HTML document contains ((text)), as well as _((tag))s_ that give structure to the text, describing things such as links, paragraphs, and headings.
A short HTML document might look like this:
@@ -211,67 +126,35 @@ if}}
{{index [HTML, notation]}}
-The tags, wrapped in ((angle brackets)) (`<` and `>`, the symbols for
-_less than_ and _greater than_), provide information about the
-((structure)) of the document. The other ((text)) is just plain text.
+The tags, wrapped in ((angle brackets)) (`<` and `>`, the symbols for _less than_ and _greater than_), provide information about the ((structure)) of the document. The other ((text)) is just plain text.
{{index doctype, version}}
-The document starts with ``, which tells the browser to
-interpret the page as _modern_ HTML, as opposed to various dialects
-that were in use in the past.
+The document starts with ``, which tells the browser to interpret the page as _modern_ HTML, as opposed to various dialects that were in use in the past.
{{index "head (HTML tag)", "body (HTML tag)", "title (HTML tag)", "h1 (HTML tag)", "p (HTML tag)"}}
-HTML documents have a head and a body. The head contains information
-_about_ the document, and the body contains the document itself. In
-this case, the head declares that the title of this document is "My
-home page" and that it uses the UTF-8 encoding, which is a way to
-encode Unicode text as binary data. The document's body contains a
-heading (`
`, meaning "heading 1"—`
` to `
` produce
-subheadings) and two ((paragraph))s (`
`).
+HTML documents have a head and a body. The head contains information _about_ the document, and the body contains the document itself. In this case, the head declares that the title of this document is "My home page" and that it uses the UTF-8 encoding, which is a way to encode Unicode text as binary data. The document's body contains a heading (`
`, meaning "heading 1"—`
` to `
` produce subheadings) and two ((paragraph))s (`
`).
{{index "href attribute", "a (HTML tag)"}}
-Tags come in several forms. An ((element)), such as the body, a
-paragraph, or a link, is started by an _((opening tag))_ like `