1
0
mirror of https://github.com/apachecn/eloquent-js-3e-zh.git synced 2025-05-23 20:02:20 +00:00
eloquent-js-3e-zh/diff-en/2ech4-3ech4.diff
wizardforcel 48c8d93b4a diff
2018-04-28 14:32:58 +08:00

1030 lines
82 KiB
Diff
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

diff --git a/2ech4.md b/3ech4.md
index 351db88..a3967fd 100644
--- a/2ech4.md
+++ b/3ech4.md
@@ -4,110 +4,111 @@
>
> <footer>Charles Babbage, <cite>Passages from the Life of a Philosopher (1864)</cite></footer>
-Numbers, Booleans, and strings are the bricks that data structures are built from. But you can't make much of a house out of a single brick. _Objects_ allow us to group values—including other objects—together and thus 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—together to build more complex structures.
-The programs we have built so far have been seriously hampered by the fact that they were operating only on simple data types. This chapter will add a basic understanding of data structures to your toolkit. By the end of it, you'll know enough to start writing some 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 variables 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.
## The weresquirrel
Every now and then, usually between eight and ten in the evening, 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 tends to 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.
+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.
-![The weresquirrel](img/weresquirrel.png)
+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.
-That takes care of the cat and oak problems. But Jacques still suffers from his condition. 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 touched trees. So he stopped touching trees entirely and even avoided going near them. But the problem persisted.
+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 intends to start keeping a daily log of everything he did that day and whether he changed form. With this data he hopes to narrow down the conditions that trigger the transformations.
-
-The first thing he does is design a data structure to store this information.
+The first thing he needs is a data structure to store this information.
## Data sets
-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, as a simple example, that we want to represent a collection of 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.
-We could get creative with strings—after all, strings can be 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.
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.
```
-var listOfNumbers = [2, 3, 5, 7, 11];
+let listOfNumbers = [2, 3, 5, 7, 11];
console.log(listOfNumbers[2]);
// → 5
+console.log(listOfNumbers[0]);
+// → 2
console.log(listOfNumbers[2 - 1]);
// → 3
```
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 first index of an array is zero, not one. So the first element can be read with `listOfNumbers[0]`. If you don't have a programming background, this convention might take some getting used to. But zero-based counting has a long tradition in technology, and as long as this convention is followed consistently (which it is, in JavaScript), it works well.
+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.
## Properties
-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 examples. 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 values 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).
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.
```
null.length;
-// → TypeError: Cannot read property 'length' of null
+// → TypeError: null has no properties
```
-The two most common 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 part after the dot must be a valid variable name, and it directly names 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 as the property name.
+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 only works 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"]`.
-So if you know that the property you are interested in is called “length”, you say `value.length`. If you want to extract the property named by the value held in the variable `i`, you say `value[i]`. And because property names can be any string, if you want to access a property named “2” or “John Doe”, you must use square brackets: `value[2]` or `value["John Doe"]`. This is the case even though you know the precise name of the property in advance, because neither “2” nor “John Doe” is a valid variable name and so cannot be accessed through dot notation.
+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 elements in an array are stored in properties. Because the names of these properties are numbers and we often need to get their name from a variable, we have to use the bracket syntax to access them. The `length` property of an array tells us how many elements it contains. This property name is a valid variable name, and we know its name in advance, so to find the length of an array, you typically write `array.length` because that is 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"]`.
## Methods
-Both string and array objects contain, in addition to the `length` property, a number of properties that refer to function values.
+Both string and array objects contain, in addition to the `length` property, a number of properties that hold function values.
```
-var doh = "Doh";
+let doh = "Doh";
console.log(typeof doh.toUpperCase);
// → function
console.log(doh.toUpperCase());
// → DOH
```
-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`. You can guess what that does.
+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.
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 6](06_object.html#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”.
-This example demonstrates some methods that array objects have:
+This example demonstrates two methods you can use to manipulate arrays:
```
-var mack = [];
-mack.push("Mack");
-mack.push("the", "Knife");
-console.log(mack);
-// → ["Mack", "the", "Knife"]
-console.log(mack.join(" "));
-// → Mack the Knife
-console.log(mack.pop());
-// → Knife
-console.log(mack);
-// → ["Mack", "the"]
+let sequence = [1, 2, 3];
+sequence.push(4);
+sequence.push(5);
+console.log(sequence);
+// → [1, 2, 3, 4, 5]
+console.log(sequence.pop());
+// → 5
+console.log(sequence);
+// → [1, 2, 3, 4]
```
-The `push` method can be used to add values to the end of an array. The `pop` method does the opposite: it removes the value at the end of the array and returns it. An array of strings can be flattened to a single string with the `join` method. The argument given to `join` determines the text that is glued between the array's elements.
+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.
+
+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](03_functions.html#stack), which is an instance of the same idea.
## Objects
-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. Ideally, we would like to group these values together into a single value and then put these 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.
-Values of the type _object_ are arbitrary collections of properties, and we can add or remove these properties as we please. One way to create an object is by using a curly brace notation.
+Values of the type _object_ are arbitrary collections of properties. One way to create an object is by using curly braces as an expression.
```
-var day1 = {
+let day1 = {
squirrel: false,
- events: ["work", "touched tree", "pizza", "running",
- "television"]
+ events: ["work", "touched tree", "pizza", "running"]
};
console.log(day1.squirrel);
// → false
@@ -118,29 +119,27 @@ console.log(day1.wolf);
// → false
```
-Inside the curly braces, we can give a list of properties separated by commas. Each property is written as a name, followed by a colon, followed by an expression that provides a value for the property. Spaces and line breaks are not significant. When an object spans multiple lines, indenting it like in the previous example improves readability. Properties whose names are not valid variable 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.
```
-var descriptions = {
+let descriptions = {
work: "Went to work",
"touched tree": "Touched a tree"
};
```
-This means that curly 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 almost never useful to start a statement with a curly-brace object, and in typical programs, there is no ambiguity between these two uses.
+This means that curly 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 a curly-brace object, so the ambiguity between these two is not much of a problem.
-Reading a property that doesn't exist will produce the value `undefined`, which happens the first time we try to read the `wolf` property in the previous example.
+Reading a property that doesn't exist will give you the value `undefined`.
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.
-To briefly return to our tentacle model of variable bindings—property bindings are similar. They _grasp_ values, but other variables 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 inscribed on it.
-
-![Artist's representation of an object](img/octopus-object.jpg)
+To briefly return to our tentacle model of bindings—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.
-The `delete` operator cuts off a tentacle from such an octopus. It is a unary operator that, when applied to a property access expression, 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.
```
-var anObject = {left: 1, right: 2};
+let anObject = {left: 1, right: 2};
console.log(anObject.left);
// → 1
delete anObject.left;
@@ -152,24 +151,38 @@ console.log("right" in anObject);
// → true
```
-The binary `in` operator, when applied to a string and an object, returns a Boolean value that indicates whether that object has that property. 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`.
-Arrays, then, are just a kind of object specialized for storing sequences of things. If you evaluate `typeof [1, 2]`, this produces `"object"`. You can see them as long, flat octopuses with all their arms in a neat row, labeled with numbers.
+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.
+
+```
+let objectA = {a: 1, b: 2};
+Object.assign(objectA, {b: 3, c: 4});
+console.log(objectA);
+// → {a: 1, b: 3, c: 4}
+```
-![Artist's representation of an array](img/octopus-array.jpg)
+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.
-So we can represent Jacques' journal as an array of objects.
+We will represent Jacques' journal as an array of objects.
```
-var journal = [
+let journal = [
{events: ["work", "touched tree", "pizza",
"running", "television"],
squirrel: false},
{events: ["work", "ice cream", "cauliflower",
"lasagna", "touched tree", "brushed teeth"],
squirrel: false},
- {events: ["weekend", "cycling", "break",
- "peanuts", "beer"],
+ {events: ["weekend", "cycling", "break", "peanuts",
+ "beer"],
squirrel: true},
/* and so on... */
];
@@ -177,18 +190,18 @@ var journal = [
## Mutability
-We will get to actual programming _real_ soon now. But first, there's one last piece of theory to understand.
+We will get to actual programming _real_ soon now. First there's one more piece of theory to understand.
-We've seen 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 an existing value 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 reference to a string that contains `"cat"`, it is not possible for other code to change a character in _that_ 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"`.
-With objects, on the other hand, the content of a value _can_ be modified by changing its properties.
+Objects work differently. You _can_ change their properties, causing a single object value to have different content at different times.
-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. But 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:
```
-var object1 = {value: 10};
-var object2 = object1;
-var object3 = {value: 10};
+let object1 = {value: 10};
+let object2 = object1;
+let object3 = {value: 10};
console.log(object1 == object2);
// → true
@@ -202,26 +215,35 @@ console.log(object3.value);
// → 10
```
-The `object1` and `object2` variables grasp the _same_ object, which is why changing `object1` also changes the value of `object2`. The variable `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.
+
+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.
+
+```
+const score = {visitors: 0, home: 0};
+// This is okay
+score.visitors = 1;
+// This isn't allowed
+score = {visitors: 1, home: 1};
+```
-JavaScript's `==` operator, when comparing objects, will return `true` only if both objects are precisely the same value. Comparing different objects will return `false`, even if they have identical contents. There is no “deep” comparison operation built into JavaScript, which looks at object's contents, but it is possible to write it yourself (which will be one of the [exercises](04_data.html#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](04_data.html#exercise_deep_compare) at the end of this chapter).
## The lycanthrope's log
So Jacques starts up his JavaScript interpreter and sets up the environment he needs to keep his journal.
```
-var journal = [];
+let journal = [];
-function addEntry(events, didITurnIntoASquirrel) {
- journal.push({
- events: events,
- squirrel: didITurnIntoASquirrel
- });
+function addEntry(events, squirrel) {
+ journal.push({events, squirrel});
}
```
-And then, every evening at ten—or sometimes the next morning, after climbing down from the top shelf of his bookcase—he records the day.
+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 a short-hand that means the same thing—if a property name in curly brace notation isn't followed by a value, its value is taken from the binding with the same name.
+
+So then, every evening at ten—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",
@@ -232,27 +254,31 @@ addEntry(["weekend", "cycling", "break", "peanuts",
"beer"], true);
```
-Once he has enough data points, he intends to compute the correlation between his squirrelification and each of the day's events and ideally learn something useful from those correlations.
+Once he has enough data points, he intends to use statistics to find out which of these events may be related to the squirrelifications.
-_Correlation_ is a measure of dependence between variables (“variables” in the statistical sense, not the JavaScript sense). It is usually expressed as a coefficient that ranges from -1 to 1\. Zero correlation means the variables are not related, whereas 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.
-For binary (Boolean) variables, the _phi_ coefficient (_ϕ_) provides a good measure of correlation and is relatively easy to compute. To compute _ϕ_, we need a table _n_ that contains the number of times the various combinations of the two variables were observed. For example, we could take the event of eating pizza and put that in a table like this:
+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 amount 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.
-![Eating pizza versus turning into a squirrel](img/pizza-squirrel.svg)
+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:
-_ϕ_ can be computed using the following formula, where _n_ refers to the table:
+<figure>![Eating pizza versus turning into a squirrel](img/pizza-squirrel.svg)</figure>
-| _ϕ_ = | n&lt;sub&gt;11&lt;/sub&gt;n&lt;sub&gt;00&lt;/sub&gt; - n&lt;sub&gt;10&lt;/sub&gt;n&lt;sub&gt;01&lt;/sub&gt;√ n&lt;sub&gt;1•&lt;/sub&gt;n&lt;sub&gt;0•&lt;/sub&gt;n&lt;sub&gt;•1&lt;/sub&gt;n&lt;sub&gt;•0&lt;/sub&gt; |
+If we call that table _n_, we can compute _ϕ_ using the following formula:
-The notation _n_&lt;sub&gt;01&lt;/sub&gt; indicates the number of measurements where the first variable (squirrelness) is false (0) and the second variable (pizza) is true (1). In this example, _n_&lt;sub&gt;01&lt;/sub&gt; is 9.
+| _ϕ_ = | _n_&lt;sub&gt;11&lt;/sub&gt;_n_&lt;sub&gt;00&lt;/sub&gt; _n_&lt;sub&gt;10&lt;/sub&gt;_n_&lt;sub&gt;01&lt;/sub&gt;√ _n_&lt;sub&gt;1•&lt;/sub&gt;_n_&lt;sub&gt;0•&lt;/sub&gt;_n_&lt;sub&gt;•1&lt;/sub&gt;_n_&lt;sub&gt;•0&lt;/sub&gt; |
+
+(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—just this one formula for now. And even with this one, all we do is turn it into JavaScript.)
+
+The notation _n_&lt;sub&gt;01&lt;/sub&gt; 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_&lt;sub&gt;01&lt;/sub&gt; is 9.
The value _n_&lt;sub&gt;1•&lt;/sub&gt; refers to the sum of all measurements where the first variable is true, which is 5 in the example table. Likewise, _n_&lt;sub&gt;•0&lt;/sub&gt; refers to the sum of the measurements where the second variable is false.
-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\. 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×764×9 = 40, and the part below it (the divisor) would be the square root of 5×85×10×80, or √340000\. This comes out to _ϕ_ ≈ 0.069, which is tiny. Eating pizza does not appear to have influence on the transformations.
## Computing correlation
-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, 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 numbers, 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.
This is the function that computes the _ϕ_ coefficient from such an array:
@@ -269,22 +295,18 @@ console.log(phi([76, 9, 4, 1]));
// → 0.068599434
```
-This is simply 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 sum two fields from the table to get fields like n&lt;sub&gt;1•&lt;/sub&gt; 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&lt;sub&gt;1•&lt;/sub&gt; because the sums of rows or columns are not stored directly in our data structure.
-Jacques kept his journal for three months. The resulting data set is available in the coding sandbox for this chapter, where it is stored in the `JOURNAL` variable, and in a downloadable [file](http://eloquentjavascript.net/2nd_edition/code/jacques_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, where it is stored in the `JOURNAL` binding, and in a downloadable [file](https://eloquentjavascript.net/code/journal.js).
-To extract a two-by-two table for a specific event from this journal, we must loop over all the entries and tally up 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.
```
-function hasEvent(event, entry) {
- return entry.events.indexOf(event) != -1;
-}
-
function tableFor(event, journal) {
- var table = [0, 0, 0, 0];
- for (var i = 0; i < journal.length; i++) {
- var entry = journal[i], index = 0;
- if (hasEvent(event, entry)) index += 1;
+ let table = [0, 0, 0, 0];
+ for (let i = 0; i < journal.length; i++) {
+ let entry = journal[i], index = 0;
+ if (entry.events.includes(event)) index += 1;
if (entry.squirrel) index += 2;
table[index] += 1;
}
@@ -295,74 +317,64 @@ console.log(tableFor("pizza", JOURNAL));
// → [76, 9, 4, 1]
```
-The `hasEvent` function tests whether an entry contains a given event. Arrays have an `indexOf` method that tries to find a given value (in this case, the event name) in the array and returns the index at which it was found or -1 if it wasn't found. So if the call to `indexOf` doesn't return -1, then we know the event was found in the entry.
-
-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 number in the array that corresponds to this box on the table.
+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.
-We now have the tools we need to compute individual correlations. The only step remaining is to find a correlation for every type of event that was recorded and see whether anything stands out. But how should we store these correlations once we compute them?
+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.
-## Objects as maps
+We now have the tools we need to compute individual correlations. The only step remaining is to find a correlation for every type of event that was recorded and see whether anything stands out.
-One possible way is to store all the correlations in an array, using objects with `name` and `value` properties. But that makes looking up the correlation for a given event somewhat cumbersome: you'd have to loop over the whole array to find the object with the right `name`. We could wrap this lookup process in a function, but we would still be writing more code, and the computer would be doing more work than necessary.
+## Array loops
-A better way is to use object properties named after the event types. We can use the square bracket access notation to create and read the properties and can use the `in` operator to test whether a given property exists.
+In the `tableFor` function, there's a loop like this:
```
-var map = {};
-function storePhi(event, phi) {
- map[event] = phi;
+for (let i = 0; i < JOURNAL.length; i++) {
+ let entry = JOURNAL[i];
+ // Do something with entry
}
-
-storePhi("pizza", 0.069);
-storePhi("touched tree", -0.081);
-console.log("pizza" in map);
-// → true
-console.log(map["touched tree"]);
-// → -0.081
```
-A _map_ is a way to go from values in one domain (in this case, event names) to corresponding values in another domain (in this case, _ϕ_ coefficients).
-
-There are a few potential problems with using objects like this, which we will discuss in [Chapter 6](06_object.html#prototypes), but for the time being, we won't worry about those.
+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.
-What if we want to find all the events for which we have stored a coefficient? The properties don't form a predictable series, like they would in an array, so we cannot use a normal `for` loop. JavaScript provides a loop construct specifically for going over the properties of an object. It looks a little like a normal `for` loop but distinguishes itself by the use of the word `in`.
+There is a simpler way to write such loops in modern JavaScript.
```
-for (var event in map)
- console.log("The correlation for '" + event +
- "' is " + map[event]);
-// → The correlation for 'pizza' is 0.069
-// → The correlation for 'touched tree' is -0.081
+for (let entry of JOURNAL) {
+ console.log(`${entry.events.length} events.`);
+}
```
+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 6](06_object.html).
+
## The final analysis
-To find all the types of events that are present in the data set, we simply process each entry in turn and then loop over the events in that entry. We keep an object `phis` that has correlation coefficients for all the event types we have seen so far. Whenever we run across a type that isn't in the `phis` object yet, we compute its correlation and add it to the object.
+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.
```
-function gatherCorrelations(journal) {
- var phis = {};
- for (var entry = 0; entry < journal.length; entry++) {
- var events = journal[entry].events;
- for (var i = 0; i < events.length; i++) {
- var event = events[i];
- if (!(event in phis))
- phis[event] = phi(tableFor(event, journal));
+function journalEvents(journal) {
+ let events = [];
+ for (let entry of journal) {
+ for (let event of entry.events) {
+ if (!events.includes(event)) {
+ events.push(event);
+ }
}
}
- return phis;
+ return events;
}
-var correlations = gatherCorrelations(JOURNAL);
-console.log(correlations.pizza);
-// → 0.068599434
+console.log(journalEvents(JOURNAL));
+// → ["carrot", "exercise", "weekend", "bread", …]
```
-Let's see what came out.
+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 correlations.
```
-for (var event in correlations)
- console.log(event + ": " + correlations[event]);
+for (let event of journalEvents(JOURNAL)) {
+ console.log(event + ":", phi(tableFor(event, JOURNAL)));
+}
// → carrot: 0.0140970969
// → exercise: 0.0685994341
// → weekend: 0.1371988681
@@ -371,13 +383,14 @@ for (var event in correlations)
// 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, however. 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.
```
-for (var event in correlations) {
- var correlation = correlations[event];
- if (correlation > 0.1 || correlation < -0.1)
- console.log(event + ": " + correlation);
+for (let event of journalEvents(JOURNAL)) {
+ let correlation = phi(tableFor(event, JOURNAL));
+ if (correlation > 0.1 || correlation < -0.1) {
+ console.log(event + ":", correlation);
+ }
}
// → weekend: 0.1371988681
// → brushed teeth: -0.3805211953
@@ -388,49 +401,51 @@ for (var event in correlations) {
// → peanuts: 0.5902679812
```
-A-ha! There are two factors whose correlation is 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.
+A-ha! 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.
```
-for (var i = 0; i < JOURNAL.length; i++) {
- var entry = JOURNAL[i];
- if (hasEvent("peanuts", entry) &&
- !hasEvent("brushed teeth", entry))
+for (let entry of JOURNAL) {
+ if (entry.events.includes("peanuts") &&
+ !entry.events.includes("brushed teeth")) {
entry.events.push("peanut teeth");
+ }
}
console.log(phi(tableFor("peanut teeth", JOURNAL)));
// → 1
```
-Well, that's unmistakable! 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 simply stops eating peanuts altogether and finds that this completely puts an end to his transformations.
+Knowing this, Jacques stops eating peanuts altogether and finds that his transformations don't come back.
-All is well with Jacques for a while. But a few years later, he loses his job and is eventually forced to take employment with a circus, where he performs as _The Incredible Squirrelman_ by 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.
+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.
## Further arrayology
-Before finishing up this chapter, I want to introduce you to a few more object-related concepts. We'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.
We saw `push` and `pop`, which add and remove elements at the end of an array, [earlier](04_data.html#array_methods) in this chapter. The corresponding methods for adding and removing things at the start of an array are called `unshift` and `shift`.
```
-var todoList = [];
-function rememberTo(task) {
+let todoList = [];
+function remember(task) {
todoList.push(task);
}
-function whatIsNext() {
+function getTask() {
return todoList.shift();
}
-function urgentlyRememberTo(task) {
+function rememberUrgently(task) {
todoList.unshift(task);
}
```
-The previous program manages lists of tasks. You add tasks to the end of the list by calling `rememberTo("eat")`, and when you're ready to do something, you call `whatIsNext()` to get (and remove) the front item from the list. The `urgentlyRememberTo` function also adds a task but adds it to the front instead of the back of the list.
+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.
-The `indexOf` method has a sibling called `lastIndexOf`, which starts searching for the given element at the end of the array instead of the front.
+To search for a specific value, arrays provide an `indexOf` method. It 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));
@@ -439,9 +454,9 @@ 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 from.
+Both `indexOf` and `lastIndexOf` take an optional second argument that indicates where to start searching.
-Another fundamental method is `slice`, which takes a start index and an end index and returns an array that has only the elements between those indices. 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));
@@ -450,9 +465,11 @@ console.log([0, 1, 2, 3, 4].slice(2));
// → [2, 3, 4]
```
-When the end index is not given, `slice` will take all of the elements after the start index. Strings also have a `slice` method, which has a similar effect.
+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.
+
+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, 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) {
@@ -463,20 +480,22 @@ 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.
+
## Strings and their 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.
```
-var myString = "Fido";
-myString.myProperty = "value";
-console.log(myString.myProperty);
+let kim = "Kim";
+kim.age = 88;
+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. The 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 before, such values are immutable and cannot be changed.
-But these types do have some built-in properties. Every string value has a number of methods. The most useful ones are probably `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));
@@ -485,7 +504,7 @@ console.log("coconut".indexOf("u"));
// → 5
```
-One difference is that a string's `indexOf` can take 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"));
@@ -499,78 +518,94 @@ console.log(" okay \n ".trim());
// → okay
```
-We have already seen the string type's `length` property. Accessing the individual characters in a string can be done with the `charAt` method but also by simply reading numeric properties, like you'd do for an array.
+The `zeroPad` function from the [previous chapter](03_functions.html) also exists as a method. It is called `padStart` and takes the desired length and padding character as arguments.
```
-var string = "abc";
-console.log(string.length);
-// → 3
-console.log(string.charAt(0));
-// → a
-console.log(string[1]);
-// → b
+console.log(String(6).padStart(3, "0"));
+// → 006
```
-## The arguments object
+You can split a string on every occurrence of another string with `split`, and join it together again with `join`.
+
+```
+let sentence = "Secretarybirds specialize in stomping";
+let words = sentence.split(" ");
+console.log(words);
+// → ["Secretarybirds", "specialize", "in", "stomping"]
+console.log(words.join(". "));
+// → Secretarybirds. specialize. in. stomping
+```
+
+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));
+// → LALALA
+```
-Whenever a function is called, a special variable named `arguments` is added to the environment in which the function body runs. This variable refers to an object that holds all of the arguments passed to the function. Remember that in JavaScript you are allowed to pass more (or fewer) arguments to a function than the number of parameters the function itself declares.
+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 5](05_higher_order.html#code_units)).
```
-function noArguments() {}
-noArguments(1, 2, 3); // This is okay
-function threeArguments(a, b, c) {}
-threeArguments(); // And so is this
+let string = "abc";
+console.log(string.length);
+// → 3
+console.log(string[1]);
+// → b
```
-The `arguments` object has a `length` property that tells us the number of arguments that were really passed to the function. It also has a property for each argument, named 0, 1, 2, and so on.
+## Rest parameters
+
+It can be useful for a function to accept any number of arguments. For example, `Math.max` computes the maximum of _all_ the arguments it is given.
-If that sounds a lot like an array to you, you're right, it _is_ a lot like an array. But this object, unfortunately, does not have any array methods (like `slice` or `indexOf`), so it is a little harder to use than a real array.
+To write such a function, you put three dots before the function's last parameter, like this:
```
-function argumentCounter() {
- console.log("You gave me", arguments.length, "arguments.");
+function max(...numbers) {
+ let result = -Infinity;
+ for (let number of numbers) {
+ if (number > result) result = number;
+ }
+ return result;
}
-argumentCounter("Straw man", "Tautology", "Ad hominem");
-// → You gave me 3 arguments.
+console.log(max(4, 1, 9, -2));
+// → 9
```
-Some functions can take any number of arguments, like `console.log`. These typically loop over the values in their `arguments` object. They can be used to create very pleasant interfaces. For example, remember how we created the entries to Jacques' journal.
+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.
+
+You can use a similar three-dot notation to _call_ a function with an array of arguments.
```
-addEntry(["work", "touched tree", "pizza", "running",
- "television"], false);
+let numbers = [5, 1, 7];
+console.log(max(...numbers));
+// → 7
```
-Since he is going to be calling this function a lot, we could create an alternative that is easier to call.
+This “spreads” 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, .&lt;wbr&gt;.&lt;wbr&gt;.&lt;wbr&gt;numbers, 2)`.
+
+Square bracket array notation similarly allows the triple-dot operator to spread another array into the new array:
```
-function addEntry(squirrel) {
- var entry = {events: [], squirrel: squirrel};
- for (var i = 1; i < arguments.length; i++)
- entry.events.push(arguments[i]);
- journal.push(entry);
-}
-addEntry(true, "work", "touched tree", "pizza",
- "running", "television");
+let words = ["never", "fully"];
+console.log(["will", ...words, "understand"]);
+// → ["will", "never", "fully", "understand"]
```
-This version reads its first argument (`squirrel`) in the normal way and then goes over the rest of the arguments (the loop starts at index 1, skipping the first) to gather them into an array.
-
## The Math object
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).
-The `Math` object is used simply 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 variables.
+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.
-Having too many global variables “pollutes” the namespace. The more names that have been taken, the more likely you are to accidentally overwrite the value of some variable. For example, it's not unlikely that you'll 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.
-Many languages will stop you, or at least warn you, when you are defining a variable with a name that is already taken. JavaScript does neither, so be careful.
+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`.
-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.
```
function randomPointOnCircle(radius) {
- var angle = Math.random() * 2 * Math.PI;
+ let angle = Math.random() * 2 * Math.PI;
return {x: radius * Math.cos(angle),
y: radius * Math.sin(angle)};
}
@@ -578,9 +613,9 @@ console.log(randomPointOnCircle(2));
// → {x: 0.3667, y: 1.966}
```
-If sines and cosines are not something you are very familiar with, don't worry. When they are used in this book, in [Chapter 13](13_dom.html#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 14](14_dom.html#sin_cos), I'll explain them.
-The previous example uses `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.
```
console.log(Math.random());
@@ -591,7 +626,7 @@ console.log(Math.random());
// → 0.40180766698904335
```
-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 this, the machine keeps a number (or a bunch of numbers) in its internal state. Then, every time a random number is requested, it performs some complicated deterministic computations on this internal state and returns part of the result of those computations. The machine also uses the outcome to change its own internal state so that the next “random” number produced will be different.
+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.
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`.
@@ -600,37 +635,91 @@ console.log(Math.floor(Math.random() * 10));
// → 2
```
-Multiplying the random number by 10 gives us a number greater than or equal to zero, 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 zero and below 10\. Since `Math.floor` rounds down, this expression will produce, with equal chance, any number from 0 through 9.
-There are also the functions `Math.ceil` (for “ceiling”, which rounds up to a whole number) and `Math.round` (to the nearest whole number).
+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.
-## The global object
+## Destructuring
-The global scope, the space in which global variables live, can also be approached as an object in JavaScript. Each global variable is present as a property of this object. In browsers, the global scope object is stored in the `window` variable.
+Let's go back to the `phi` function for a moment:
```
-var myVar = 10;
-console.log("myVar" in window);
-// → true
-console.log(window.myVar);
-// → 10
+function phi(table) {
+ return (table[3] * table[0] - table[2] * table[1]) /
+ Math.sqrt((table[2] + table[3]) *
+ (table[0] + table[1]) *
+ (table[1] + table[3]) *
+ (table[0] + table[2]));
+}
+```
+
+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]) {
+ return (n11 * n00 - n10 * n01) /
+ Math.sqrt((n10 + n11) * (n00 + n01) *
+ (n01 + n11) * (n00 + n10));
+}
+```
+
+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.
+
+A similar trick works for objects, using braces instead of square brackets.
+
+```
+let {name} = {name: "Faraji", age: 23};
+console.log(name);
+// → Faraji
+```
+
+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
+
+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 _addresses_—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.
+
+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.
+
+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:
+
+```
+{
+ "squirrel": false,
+ "events": ["work", "touched tree", "pizza", "running"]
+}
+```
+
+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,
+ events: ["weekend"]});
+console.log(string);
+// → {"squirrel":false,"events":["weekend"]}
+console.log(JSON.parse(string).events);
+// → ["weekend"]
```
## 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 trying to wrap 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.propName` or `value["propName"]`. 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 numbers 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.
-Objects can also serve as maps, associating values with names. The `in` operator can be used to find out whether an object contains a property with a given name. The same keyword can also be used in a `for` loop (`for (var name in object)`) to loop over an object's properties.
+You can iterate over arrays using a special kind of `for` loop—`for (let element of array)`.
## Exercises
### The sum of a range
-The [introduction](00_intro.html#intro) of this book alluded to the following as a nice way to compute the sum of a range of numbers:
+The [introduction](00_intro.html) of this book alluded to the following as a nice way to compute the sum of a range of numbers:
```
console.log(sum(range(1, 10)));
@@ -638,9 +727,9 @@ console.log(sum(range(1, 10)));
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 previous 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.
-As a bonus assignment, modify your `range` function to take an optional third argument that indicates the “step” value used to build up the array. If no step is given, the array 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]`.
```
// Your code here.
@@ -653,45 +742,45 @@ console.log(sum(range(1, 10)));
// → 55
```
-Building up an array is most easily done by first initializing a variable 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.
-Since the end boundary is inclusive, you'll need to use the `&lt;=` operator rather than simply `&lt;` to check for the end of your loop.
+Since the end boundary is inclusive, you'll need to use the `&lt;=` operator rather than `&lt;` to check for the end of your loop.
-To check whether the optional step argument was given, either check `arguments.length` or compare the value of the argument to `undefined`. If it wasn't given, simply set it to its default value (1) at the top of the function.
+The step parameter can be an optional parameter that defaults (using the `=` operator) to 1.
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 `&gt;=` rather than `&lt;=` 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 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.
### Reversing an array
-Arrays have a method `reverse`, which 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 in order to reverse its elements. Neither may use the standard `reverse` method.
+Arrays have a `reverse` method which 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.
-Thinking back to the notes about side effects and pure functions in the [previous chapter](03_functions.html#pure), which variant do you expect to be useful in more situations? Which one is more efficient?
+Thinking back to the notes about side effects and pure functions in the [previous chapter](03_functions.html#pure), which variant do you expect to be useful in more situations? Which one runs faster?
```
// Your code here.
console.log(reverseArray(["A", "B", "C"]));
// → ["C", "B", "A"];
-var arrayValue = [1, 2, 3, 4, 5];
+let arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
// → [5, 4, 3, 2, 1]
```
-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 backward and use the `push` method. Iterating over an array backward requires a (somewhat awkward) `for` specification like `(var i = array.length - 1; i &gt;= 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.&lt;wbr&gt;length - 1; i &gt;= 0; i--)`.
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 length) and swapping the element at position `i` with the one at position `array.length - 1 - i`. You can use a local variable to briefly hold on to one of the elements, overwrite that one with its mirror image, and then put the value from the local variable in the place where the mirror image used to be.
+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.&lt;wbr&gt;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.
### A list
-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 the 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.
```
-var list = {
+let list = {
value: 1,
rest: {
value: 2,
@@ -705,11 +794,11 @@ var list = {
The resulting objects form a chain, like this:
-![A linked list](img/linked-list.svg)
+<figure>![A linked list](img/linked-list.svg)</figure>
-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 variable defined earlier), they are both independent lists, but they share the structure that makes up their last three elements. In addition, the original list is also still a valid three-element list.
+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 data structure like the previous one when given `[1, 2, 3]` as argument, and write a `listToArray` function that produces an array from a list. Also write the helper functions `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, or `undefined` when there is no such element.
+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.
If you haven't already, also write a recursive version of `nth`.
@@ -726,12 +815,12 @@ console.log(nth(arrayToList([10, 20, 30]), 1));
// → 20
```
-Building up a list is best done back to front. So `arrayToList` could iterate over the array backward (see previous exercise) and, for each element, add an object to the list. You can use a local variable to hold the part of the list that was built so far and use a pattern 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 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.
To run over a list (in `listToArray` and `nth`), a `for` loop specification like this can be used:
```
-for (var node = list; node; node = node.rest) {}
+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.
@@ -740,16 +829,18 @@ The recursive version of `nth` will, similarly, look at an ever smaller part of
### Deep comparison
-The `==` operator compares objects by identity. But sometimes, you would 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 whose values are also equal when compared with a recursive call to `deepEqual`.
+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 to compare two things by identity (use the `===` operator for that) or by looking at their properties, 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: by a historical accident, `typeof null` also produces `"object"`.
+The `Object.keys` function will be useful when you need to go over the properties of objects to compare them.
```
// Your code here.
-var obj = {here: {is: "an"}, object: 2};
+let obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
@@ -760,6 +851,6 @@ console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
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 `===`.
-Use a `for`/`in` loop 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. The first test can be done by counting the properties in both objects and returning false if the numbers of properties are different. If they're the same, then go over the properties of one object, and for each of them, verify that the other object also has the property. The values of the properties are compared by a recursive call to `deepEqual`.
+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 in order 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.
-Returning the correct value from the function is best done by immediately returning false when a mismatch is noticed and returning true at the end of the function.
\ No newline at end of file
+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.