forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy path04_data.html
More file actions
794 lines (534 loc) · 115 KB
/
04_data.html
File metadata and controls
794 lines (534 loc) · 115 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
<!doctype html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Data Structures: Objects and Arrays :: Eloquent JavaScript</title>
<link rel=stylesheet href="js/node_modules/codemirror/lib/codemirror.css">
<script src="js/acorn_codemirror.js"></script>
<link rel=stylesheet href="css/ejs.css">
<script src="js/sandbox.js"></script>
<script src="js/ejs.js"></script><script>var chapNum = 4;var sandboxLoadFiles = ["code/journal.js","code/chapter/04_data.js"];</script></head>
<article>
<nav><a href="03_functions.html" title="previous chapter">◀</a> <a href="index.html" title="cover">◆</a> <a href="05_higher_order.html" title="next chapter">▶</a></nav>
<h1><span class=chap_num>Chapter 4</span>Data Structures: Objects and Arrays</h1>
<blockquote>
<p><a class="p_ident" id="p_3DGxnMhaad" href="#p_3DGxnMhaad" tabindex="-1" role="presentation"></a>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.</p>
<footer>Charles Babbage, <cite>Passages from the Life of a Philosopher (1864)</cite></footer>
</blockquote><figure class="chapter framed"><img src="img/chapter_picture_4.jpg" alt="Picture of a weresquirrel"></figure>
<p><a class="p_ident" id="p_j/UjCN3npi" href="#p_j/UjCN3npi" tabindex="-1" role="presentation"></a>Numbers, Booleans, and strings are the atoms that data structures are built from. Many types of information require more than one atom, though. <em>Objects</em> allow us to group values—including other objects—to build more complex structures.</p>
<p><a class="p_ident" id="p_F4YgzUjHcT" href="#p_F4YgzUjHcT" tabindex="-1" role="presentation"></a>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.</p>
<p><a class="p_ident" id="p_vL8agXHSiL" href="#p_vL8agXHSiL" tabindex="-1" role="presentation"></a>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.</p>
<h2><a class="h_ident" id="h_NvjtahQLlw" href="#h_NvjtahQLlw" tabindex="-1" role="presentation"></a>The weresquirrel</h2>
<p><a class="p_ident" id="p_0aih0sjFrb" href="#p_0aih0sjFrb" tabindex="-1" role="presentation"></a>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.</p>
<p><a class="p_ident" id="p_EIDMzKWaqr" href="#p_EIDMzKWaqr" tabindex="-1" role="presentation"></a>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 (<em>that</em> 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.</p>
<p><a class="p_ident" id="p_ciZTylV1yl" href="#p_ciZTylV1yl" tabindex="-1" role="presentation"></a>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.</p>
<p><a class="p_ident" id="p_Xj6eprhXkS" href="#p_Xj6eprhXkS" tabindex="-1" role="presentation"></a>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.</p>
<p><a class="p_ident" id="p_mcDf0Dxvcm" href="#p_mcDf0Dxvcm" tabindex="-1" role="presentation"></a>The first thing he needs is a data structure to store this information.</p>
<h2><a class="h_ident" id="h_HjL/otjEJn" href="#h_HjL/otjEJn" tabindex="-1" role="presentation"></a>Data sets</h2>
<p><a class="p_ident" id="p_HFLfyQFSDp" href="#p_HFLfyQFSDp" tabindex="-1" role="presentation"></a>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.</p>
<p><a class="p_ident" id="p_cnzv4pg+Wz" href="#p_cnzv4pg+Wz" tabindex="-1" role="presentation"></a>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 <code>"2 3 5 7 11"</code> as our representation. But this is awkward. You’d have to somehow extract the digits and convert them back to numbers to access them.</p>
<p><a class="p_ident" id="p_/aFILq7bDn" href="#p_/aFILq7bDn" tabindex="-1" role="presentation"></a>Fortunately, JavaScript provides a data type specifically for storing sequences of values. It is called an <em>array</em> and is written as a list of values between square brackets, separated by commas.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_05cIH1hy/D" href="#c_05cIH1hy/D" tabindex="-1" role="presentation"></a><span class="cm-keyword">let</span> <span class="cm-def">listOfNumbers</span> <span class="cm-operator">=</span> [<span class="cm-number">2</span>, <span class="cm-number">3</span>, <span class="cm-number">5</span>, <span class="cm-number">7</span>, <span class="cm-number">11</span>];
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">listOfNumbers</span>[<span class="cm-number">2</span>]);
<span class="cm-comment">// → 5</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">listOfNumbers</span>[<span class="cm-number">0</span>]);
<span class="cm-comment">// → 2</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">listOfNumbers</span>[<span class="cm-number">2</span> <span class="cm-operator">-</span> <span class="cm-number">1</span>]);
<span class="cm-comment">// → 3</span></pre>
<p><a class="p_ident" id="p_xu5bhsrvS2" href="#p_xu5bhsrvS2" tabindex="-1" role="presentation"></a>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 <em>index</em> given by the expression in the brackets.</p>
<p id="array_indexing"><a class="p_ident" id="p_1+NmIJreij" href="#p_1+NmIJreij" tabindex="-1" role="presentation"></a>The first index of an array is zero, not one. So the first element is retrieved with <code>listOfNumbers[0]</code>. 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.</p>
<h2 id="properties"><a class="h_ident" id="h_vGyI2y8HA6" href="#h_vGyI2y8HA6" tabindex="-1" role="presentation"></a>Properties</h2>
<p><a class="p_ident" id="p_GC4++VF2pM" href="#p_GC4++VF2pM" tabindex="-1" role="presentation"></a>We’ve seen a few suspicious-looking expressions like <code>myString.length</code> (to get the length of a string) and <code>Math.max</code> (the maximum function) in past chapters. These are expressions that access a <em>property</em> of some value. In the first case, we access the <code>length</code> property of the value in <code>myString</code>. In the second, we access the property named <code>max</code> in the <code>Math</code> object (which is a collection of mathematics-related constants and functions).</p>
<p><a class="p_ident" id="p_dTOk+Nu/lR" href="#p_dTOk+Nu/lR" tabindex="-1" role="presentation"></a>Almost all JavaScript values have properties. The exceptions are <code>null</code> and <code>undefined</code>. If you try to access a property on one of these nonvalues, you get an error.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_FNR95AymUx" href="#c_FNR95AymUx" tabindex="-1" role="presentation"></a><span class="cm-atom">null</span>.<span class="cm-property">length</span>;
<span class="cm-comment">// → TypeError: null has no properties</span></pre>
<p><a class="p_ident" id="p_wm1lZqKJ49" href="#p_wm1lZqKJ49" tabindex="-1" role="presentation"></a>The two main ways to access properties in JavaScript are with a dot and with square brackets. Both <code>value.x</code> and <code>value[x]</code> access a property on <code>value</code>—but not necessarily the same property. The difference is in how <code>x</code> 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 <em>evaluated</em> to get the property name. Whereas <code>value.x</code> fetches the property of <code>value</code> named “x”, <code>value[x]</code> tries to evaluate the expression <code>x</code> and uses the result, converted to a string, as the property name.</p>
<p><a class="p_ident" id="p_PeocsmCJ3P" href="#p_PeocsmCJ3P" tabindex="-1" role="presentation"></a>So if you know that the property you are interested in is called <em>color</em>, you say <code>value.color</code>. If you want to extract the property named by the value held in the binding <code>i</code>, you say <code>value[i]</code>. 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 <em>2</em> or <em>John Doe</em>, you must use square brackets: <code>value[2]</code> or <code>value["John Doe"]</code>.</p>
<p><a class="p_ident" id="p_v2+DwDjnmO" href="#p_v2+DwDjnmO" tabindex="-1" role="presentation"></a>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.</p>
<p><a class="p_ident" id="p_Bcq+Q3kiI4" href="#p_Bcq+Q3kiI4" tabindex="-1" role="presentation"></a>The <code>length</code> 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 <code>array.length</code> because that’s easier to write than <code>array["length"]</code>.</p>
<h2 id="methods"><a class="h_ident" id="h_fkrGgDyRWc" href="#h_fkrGgDyRWc" tabindex="-1" role="presentation"></a>Methods</h2>
<p><a class="p_ident" id="p_t1dHhJEzat" href="#p_t1dHhJEzat" tabindex="-1" role="presentation"></a>Both string and array objects contain, in addition to the <code>length</code> property, a number of properties that hold function values.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_prRDc5amqh" href="#c_prRDc5amqh" tabindex="-1" role="presentation"></a><span class="cm-keyword">let</span> <span class="cm-def">doh</span> <span class="cm-operator">=</span> <span class="cm-string">"Doh"</span>;
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-keyword">typeof</span> <span class="cm-variable">doh</span>.<span class="cm-property">toUpperCase</span>);
<span class="cm-comment">// → function</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">doh</span>.<span class="cm-property">toUpperCase</span>());
<span class="cm-comment">// → DOH</span></pre>
<p><a class="p_ident" id="p_TWVl3O+8/l" href="#p_TWVl3O+8/l" tabindex="-1" role="presentation"></a>Every string has a <code>toUpperCase</code> property. When called, it will return a copy of the string in which all letters have been converted to uppercase. There is also <code>toLowerCase</code>, going the other way.</p>
<p><a class="p_ident" id="p_ZYWrM09QFe" href="#p_ZYWrM09QFe" tabindex="-1" role="presentation"></a>Interestingly, even though the call to <code>toUpperCase</code> does not pass any arguments, the function somehow has access to the string <code>"Doh"</code>, the value whose property we called. How this works is described in <a href="06_object.html#obj_methods">Chapter 6</a>.</p>
<p><a class="p_ident" id="p_96KudJIN5i" href="#p_96KudJIN5i" tabindex="-1" role="presentation"></a>Properties that contain functions are generally called <em>methods</em> of the value they belong to, as in “<code>toUpperCase</code> is a method of a string”.</p>
<p id="array_methods"><a class="p_ident" id="p_aAS6mUhzmc" href="#p_aAS6mUhzmc" tabindex="-1" role="presentation"></a>This example demonstrates two methods you can use to manipulate arrays:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_RiFZUNk6gr" href="#c_RiFZUNk6gr" tabindex="-1" role="presentation"></a><span class="cm-keyword">let</span> <span class="cm-def">sequence</span> <span class="cm-operator">=</span> [<span class="cm-number">1</span>, <span class="cm-number">2</span>, <span class="cm-number">3</span>];
<span class="cm-variable">sequence</span>.<span class="cm-property">push</span>(<span class="cm-number">4</span>);
<span class="cm-variable">sequence</span>.<span class="cm-property">push</span>(<span class="cm-number">5</span>);
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">sequence</span>);
<span class="cm-comment">// → [1, 2, 3, 4, 5]</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">sequence</span>.<span class="cm-property">pop</span>());
<span class="cm-comment">// → 5</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">sequence</span>);
<span class="cm-comment">// → [1, 2, 3, 4]</span></pre>
<p><a class="p_ident" id="p_6iATZ6SSgb" href="#p_6iATZ6SSgb" tabindex="-1" role="presentation"></a>The <code>push</code> method adds values to the end of an array, and the <code>pop</code> method does the opposite, removing the last value in the array and returning it.</p>
<p><a class="p_ident" id="p_0p3gvnUXoK" href="#p_0p3gvnUXoK" tabindex="-1" role="presentation"></a>These somewhat silly names are the traditional terms for operations on a <em>stack</em>. 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 <a href="03_functions.html#stack">the previous chapter</a>, which is an instance of the same idea.</p>
<h2><a class="h_ident" id="h_cqg63Sxe3o" href="#h_cqg63Sxe3o" tabindex="-1" role="presentation"></a>Objects</h2>
<p><a class="p_ident" id="p_D8cm1kz0P8" href="#p_D8cm1kz0P8" tabindex="-1" role="presentation"></a>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.</p>
<p><a class="p_ident" id="p_amO+YCpNIz" href="#p_amO+YCpNIz" tabindex="-1" role="presentation"></a>Values of the type <em>object</em> are arbitrary collections of properties. One way to create an object is by using braces as an expression.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_Y37a9WsXpl" href="#c_Y37a9WsXpl" tabindex="-1" role="presentation"></a><span class="cm-keyword">let</span> <span class="cm-def">day1</span> <span class="cm-operator">=</span> {
<span class="cm-property">squirrel</span>: <span class="cm-atom">false</span>,
<span class="cm-property">events</span>: [<span class="cm-string">"work"</span>, <span class="cm-string">"touched tree"</span>, <span class="cm-string">"pizza"</span>, <span class="cm-string">"running"</span>]
};
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">day1</span>.<span class="cm-property">squirrel</span>);
<span class="cm-comment">// → false</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">day1</span>.<span class="cm-property">wolf</span>);
<span class="cm-comment">// → undefined</span>
<span class="cm-variable">day1</span>.<span class="cm-property">wolf</span> <span class="cm-operator">=</span> <span class="cm-atom">false</span>;
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">day1</span>.<span class="cm-property">wolf</span>);
<span class="cm-comment">// → false</span></pre>
<p><a class="p_ident" id="p_hPPBEWYY/i" href="#p_hPPBEWYY/i" tabindex="-1" role="presentation"></a>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.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_n8ErtKNPW/" href="#c_n8ErtKNPW/" tabindex="-1" role="presentation"></a><span class="cm-keyword">let</span> <span class="cm-def">descriptions</span> <span class="cm-operator">=</span> {
<span class="cm-property">work</span>: <span class="cm-string">"Went to work"</span>,
<span class="cm-string cm-property">"touched tree"</span>: <span class="cm-string">"Touched a tree"</span>
};</pre>
<p><a class="p_ident" id="p_nZ3mgfn27O" href="#p_nZ3mgfn27O" tabindex="-1" role="presentation"></a>This means that braces have <em>two</em> 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.</p>
<p><a class="p_ident" id="p_lBjH6GtvXt" href="#p_lBjH6GtvXt" tabindex="-1" role="presentation"></a>Reading a property that doesn’t exist will give you the value <code>undefined</code>.</p>
<p><a class="p_ident" id="p_m1hLPDyHXE" href="#p_m1hLPDyHXE" tabindex="-1" role="presentation"></a>It is possible to assign a value to a property expression with the <code>=</code> operator. This will replace the property’s value if it already existed or create a new property on the object if it didn’t.</p>
<p><a class="p_ident" id="p_2b9eQWe4l/" href="#p_2b9eQWe4l/" tabindex="-1" role="presentation"></a>To briefly return to our tentacle model of bindings—property bindings are similar. They <em>grasp</em> 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.</p>
<p><a class="p_ident" id="p_nQBjCOh9nC" href="#p_nQBjCOh9nC" tabindex="-1" role="presentation"></a>The <code>delete</code> 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.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_66M3B1wG98" href="#c_66M3B1wG98" tabindex="-1" role="presentation"></a><span class="cm-keyword">let</span> <span class="cm-def">anObject</span> <span class="cm-operator">=</span> {<span class="cm-property">left</span>: <span class="cm-number">1</span>, <span class="cm-property">right</span>: <span class="cm-number">2</span>};
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">anObject</span>.<span class="cm-property">left</span>);
<span class="cm-comment">// → 1</span>
<span class="cm-keyword">delete</span> <span class="cm-variable">anObject</span>.<span class="cm-property">left</span>;
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">anObject</span>.<span class="cm-property">left</span>);
<span class="cm-comment">// → undefined</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"left"</span> <span class="cm-keyword">in</span> <span class="cm-variable">anObject</span>);
<span class="cm-comment">// → false</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"right"</span> <span class="cm-keyword">in</span> <span class="cm-variable">anObject</span>);
<span class="cm-comment">// → true</span></pre>
<p><a class="p_ident" id="p_vVEymXRSvR" href="#p_vVEymXRSvR" tabindex="-1" role="presentation"></a>The binary <code>in</code> 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 <code>undefined</code> and actually deleting it is that, in the first case, the object still <em>has</em> the property (it just doesn’t have a very interesting value), whereas in the second case the property is no longer present and <code>in</code> will return <code>false</code>.</p>
<p><a class="p_ident" id="p_SvMW6lxfp+" href="#p_SvMW6lxfp+" tabindex="-1" role="presentation"></a>To find out what properties an object has, you can use the <code>Object.keys</code> function. You give it an object, and it returns an array of strings—the object’s property names.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_0oaalmpqn6" href="#c_0oaalmpqn6" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">Object</span>.<span class="cm-property">keys</span>({<span class="cm-property">x</span>: <span class="cm-number">0</span>, <span class="cm-property">y</span>: <span class="cm-number">0</span>, <span class="cm-property">z</span>: <span class="cm-number">2</span>}));
<span class="cm-comment">// → ["x", "y", "z"]</span></pre>
<p><a class="p_ident" id="p_z4/OPZzTTK" href="#p_z4/OPZzTTK" tabindex="-1" role="presentation"></a>There’s an <code>Object.assign</code> function that copies all properties from one object into another.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_ngXKayzwiT" href="#c_ngXKayzwiT" tabindex="-1" role="presentation"></a><span class="cm-keyword">let</span> <span class="cm-def">objectA</span> <span class="cm-operator">=</span> {<span class="cm-property">a</span>: <span class="cm-number">1</span>, <span class="cm-property">b</span>: <span class="cm-number">2</span>};
<span class="cm-variable">Object</span>.<span class="cm-property">assign</span>(<span class="cm-variable">objectA</span>, {<span class="cm-property">b</span>: <span class="cm-number">3</span>, <span class="cm-property">c</span>: <span class="cm-number">4</span>});
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">objectA</span>);
<span class="cm-comment">// → {a: 1, b: 3, c: 4}</span></pre>
<p><a class="p_ident" id="p_Rl8msr9DUz" href="#p_Rl8msr9DUz" tabindex="-1" role="presentation"></a>Arrays, then, are just a kind of object specialized for storing sequences of things. If you evaluate <code>typeof []</code>, it produces <code>"object"</code>. You can see them as long, flat octopuses with all their tentacles in a neat row, labeled with numbers.</p>
<p><a class="p_ident" id="p_d1H6/6O79A" href="#p_d1H6/6O79A" tabindex="-1" role="presentation"></a>We will represent the journal that Jacques keeps as an array of objects.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_H7Np/tieSQ" href="#c_H7Np/tieSQ" tabindex="-1" role="presentation"></a><span class="cm-keyword">let</span> <span class="cm-def">journal</span> <span class="cm-operator">=</span> [
{<span class="cm-property">events</span>: [<span class="cm-string">"work"</span>, <span class="cm-string">"touched tree"</span>, <span class="cm-string">"pizza"</span>,
<span class="cm-string">"running"</span>, <span class="cm-string">"television"</span>],
<span class="cm-property">squirrel</span>: <span class="cm-atom">false</span>},
{<span class="cm-property">events</span>: [<span class="cm-string">"work"</span>, <span class="cm-string">"ice cream"</span>, <span class="cm-string">"cauliflower"</span>,
<span class="cm-string">"lasagna"</span>, <span class="cm-string">"touched tree"</span>, <span class="cm-string">"brushed teeth"</span>],
<span class="cm-property">squirrel</span>: <span class="cm-atom">false</span>},
{<span class="cm-property">events</span>: [<span class="cm-string">"weekend"</span>, <span class="cm-string">"cycling"</span>, <span class="cm-string">"break"</span>, <span class="cm-string">"peanuts"</span>,
<span class="cm-string">"beer"</span>],
<span class="cm-property">squirrel</span>: <span class="cm-atom">true</span>},
<span class="cm-comment">/* and so on... */</span>
];</pre>
<h2><a class="h_ident" id="h_C3n45IkMhg" href="#h_C3n45IkMhg" tabindex="-1" role="presentation"></a>Mutability</h2>
<p><a class="p_ident" id="p_HZ50qDRWmj" href="#p_HZ50qDRWmj" tabindex="-1" role="presentation"></a>We will get to actual programming <em>real</em> soon now. First there’s one more piece of theory to understand.</p>
<p><a class="p_ident" id="p_ZAtU8veKBN" href="#p_ZAtU8veKBN" tabindex="-1" role="presentation"></a>We saw that object values can be modified. The types of values discussed in earlier chapters, such as numbers, strings, and Booleans, are all <em>immutable</em>—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 <code>"cat"</code>, it is not possible for other code to change a character in your string to make it spell <code>"rat"</code>.</p>
<p><a class="p_ident" id="p_0geJong3Bv" href="#p_0geJong3Bv" tabindex="-1" role="presentation"></a>Objects work differently. You <em>can</em> change their properties, causing a single object value to have different content at different times.</p>
<p><a class="p_ident" id="p_fVZ1xXAqW5" href="#p_fVZ1xXAqW5" tabindex="-1" role="presentation"></a>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:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_I1Dv6D46/p" href="#c_I1Dv6D46/p" tabindex="-1" role="presentation"></a><span class="cm-keyword">let</span> <span class="cm-def">object1</span> <span class="cm-operator">=</span> {<span class="cm-property">value</span>: <span class="cm-number">10</span>};
<span class="cm-keyword">let</span> <span class="cm-def">object2</span> <span class="cm-operator">=</span> <span class="cm-variable">object1</span>;
<span class="cm-keyword">let</span> <span class="cm-def">object3</span> <span class="cm-operator">=</span> {<span class="cm-property">value</span>: <span class="cm-number">10</span>};
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">object1</span> <span class="cm-operator">==</span> <span class="cm-variable">object2</span>);
<span class="cm-comment">// → true</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">object1</span> <span class="cm-operator">==</span> <span class="cm-variable">object3</span>);
<span class="cm-comment">// → false</span>
<span class="cm-variable">object1</span>.<span class="cm-property">value</span> <span class="cm-operator">=</span> <span class="cm-number">15</span>;
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">object2</span>.<span class="cm-property">value</span>);
<span class="cm-comment">// → 15</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">object3</span>.<span class="cm-property">value</span>);
<span class="cm-comment">// → 10</span></pre>
<p><a class="p_ident" id="p_LKrvBk0ldY" href="#p_LKrvBk0ldY" tabindex="-1" role="presentation"></a>The <code>object1</code> and <code>object2</code> bindings grasp the <em>same</em> object, which is why changing <code>object1</code> also changes the value of <code>object2</code>. They are said to have the same <em>identity</em>. The binding <code>object3</code> points to a different object, which initially contains the same properties as <code>object1</code> but lives a separate life.</p>
<p><a class="p_ident" id="p_eic4GJbroA" href="#p_eic4GJbroA" tabindex="-1" role="presentation"></a>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 <code>let</code> binding to keep track of a changing number by changing the value the binding points at. Similarly, though a <code>const</code> binding to an object can itself not be changed and will continue to point at the same object, the <em>contents</em> of that object might change.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_eOXMRndYxO" href="#c_eOXMRndYxO" tabindex="-1" role="presentation"></a><span class="cm-keyword">const</span> <span class="cm-def">score</span> <span class="cm-operator">=</span> {<span class="cm-property">visitors</span>: <span class="cm-number">0</span>, <span class="cm-property">home</span>: <span class="cm-number">0</span>};
<span class="cm-comment">// This is okay</span>
<span class="cm-variable">score</span>.<span class="cm-property">visitors</span> <span class="cm-operator">=</span> <span class="cm-number">1</span>;
<span class="cm-comment">// This isn't allowed</span>
<span class="cm-variable">score</span> <span class="cm-operator">=</span> {<span class="cm-property">visitors</span>: <span class="cm-number">1</span>, <span class="cm-property">home</span>: <span class="cm-number">1</span>};</pre>
<p><a class="p_ident" id="p_wD7jhXt+Tr" href="#p_wD7jhXt+Tr" tabindex="-1" role="presentation"></a>When you compare objects with JavaScript’s <code>==</code> operator, it compares by identity: it will produce <code>true</code> only if both objects are precisely the same value. Comparing different objects will return <code>false</code>, 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 <a href="04_data.html#exercise_deep_compare">exercises</a> at the end of this chapter).</p>
<h2><a class="h_ident" id="h_qHGOoBxOeE" href="#h_qHGOoBxOeE" tabindex="-1" role="presentation"></a>The lycanthrope’s log</h2>
<p><a class="p_ident" id="p_z1vPsL0dwv" href="#p_z1vPsL0dwv" tabindex="-1" role="presentation"></a>So, Jacques starts up his JavaScript interpreter and sets up the environment he needs to keep his journal.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_CI+dtzXW/x" href="#c_CI+dtzXW/x" tabindex="-1" role="presentation"></a><span class="cm-keyword">let</span> <span class="cm-def">journal</span> <span class="cm-operator">=</span> [];
<span class="cm-keyword">function</span> <span class="cm-def">addEntry</span>(<span class="cm-def">events</span>, <span class="cm-def">squirrel</span>) {
<span class="cm-variable">journal</span>.<span class="cm-property">push</span>({<span class="cm-property">events</span>, <span class="cm-property">squirrel</span>});
}</pre>
<p><a class="p_ident" id="p_ljMiZolRIM" href="#p_ljMiZolRIM" tabindex="-1" role="presentation"></a>Note that the object added to the journal looks a little odd. Instead of declaring properties like <code>events: events</code>, 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.</p>
<p><a class="p_ident" id="p_cm0psWaVgC" href="#p_cm0psWaVgC" tabindex="-1" role="presentation"></a>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.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_S+F+R2oIfR" href="#c_S+F+R2oIfR" tabindex="-1" role="presentation"></a><span class="cm-variable">addEntry</span>([<span class="cm-string">"work"</span>, <span class="cm-string">"touched tree"</span>, <span class="cm-string">"pizza"</span>, <span class="cm-string">"running"</span>,
<span class="cm-string">"television"</span>], <span class="cm-atom">false</span>);
<span class="cm-variable">addEntry</span>([<span class="cm-string">"work"</span>, <span class="cm-string">"ice cream"</span>, <span class="cm-string">"cauliflower"</span>, <span class="cm-string">"lasagna"</span>,
<span class="cm-string">"touched tree"</span>, <span class="cm-string">"brushed teeth"</span>], <span class="cm-atom">false</span>);
<span class="cm-variable">addEntry</span>([<span class="cm-string">"weekend"</span>, <span class="cm-string">"cycling"</span>, <span class="cm-string">"break"</span>, <span class="cm-string">"peanuts"</span>,
<span class="cm-string">"beer"</span>], <span class="cm-atom">true</span>);</pre>
<p><a class="p_ident" id="p_7VcOxe4CEu" href="#p_7VcOxe4CEu" tabindex="-1" role="presentation"></a>Once he has enough data points, he intends to use statistics to find out which of these events may be related to the squirrelifications.</p>
<p><a class="p_ident" id="p_EedDVNQ30H" href="#p_EedDVNQ30H" tabindex="-1" role="presentation"></a><em>Correlation</em> 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 <em>measurements</em>, 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.</p>
<p><a class="p_ident" id="p_mq//xARuKm" href="#p_mq//xARuKm" tabindex="-1" role="presentation"></a>To compute the measure of correlation between two Boolean variables, we can use the <em>phi coefficient</em> (<em>ϕ</em>). 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.</p>
<p><a class="p_ident" id="p_enPDgop6ZQ" href="#p_enPDgop6ZQ" tabindex="-1" role="presentation"></a>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:</p><figure><img src="img/pizza-squirrel.svg" alt="Eating pizza versus turning into a squirrel"></figure>
<p><a class="p_ident" id="p_34XzN30BBH" href="#p_34XzN30BBH" tabindex="-1" role="presentation"></a>If we call that table <em>n</em>, we can compute <em>ϕ</em> using the following formula:</p><div>
<table style="border-collapse: collapse; margin-left: 1em;"><tr>
<td style="vertical-align: middle"><em>ϕ</em> =</td>
<td style="padding-left: .5em">
<div style="border-bottom: 1px solid black; padding: 0 7px;"><em>n</em><sub>11</sub><em>n</em><sub>00</sub> −
<em>n</em><sub>10</sub><em>n</em><sub>01</sub></div>
<div style="padding: 0 7px;">√<span style="border-top: 1px solid black; position: relative; top: 2px;">
<span style="position: relative; top: -4px"><em>n</em><sub>1•</sub><em>n</em><sub>0•</sub><em>n</em><sub>•1</sub><em>n</em><sub>•0</sub></span>
</span></div>
</td>
</tr></table>
</div>
<p><a class="p_ident" id="p_BlqmmOB0tg" href="#p_BlqmmOB0tg" tabindex="-1" role="presentation"></a>(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.)</p>
<p><a class="p_ident" id="p_6U87ck4G90" href="#p_6U87ck4G90" tabindex="-1" role="presentation"></a>The notation <em>n</em><sub>01</sub> 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, <em>n</em><sub>01</sub> is 9.</p>
<p><a class="p_ident" id="p_pweIXp0GRF" href="#p_pweIXp0GRF" tabindex="-1" role="presentation"></a>The value <em>n</em><sub>1•</sub> refers to the sum of all measurements where the first variable is true, which is 5 in the example table. Likewise, <em>n</em><sub>•0</sub> refers to the sum of the measurements where the second variable is false.</p>
<p><a class="p_ident" id="p_ACMn7uvFzz" href="#p_ACMn7uvFzz" tabindex="-1" role="presentation"></a>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 <em>ϕ</em> ≈ 0.069, which is tiny. Eating pizza does not appear to have influence on the transformations.</p>
<h2><a class="h_ident" id="h_YwedOm6SqZ" href="#h_YwedOm6SqZ" tabindex="-1" role="presentation"></a>Computing correlation</h2>
<p><a class="p_ident" id="p_jn2nhCXEpR" href="#p_jn2nhCXEpR" tabindex="-1" role="presentation"></a>We can represent a two-by-two table in JavaScript with a four-element array (<code>[76, 9, 4, 1]</code>). We could also use other representations, such as an array containing two two-element arrays (<code>[[76, 9], [4, 1]]</code>) or an object with property names like <code>"11"</code> and <code>"01"</code>, 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 <code>10</code> 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 <code>10</code> is 2 in decimal notation, we will store this number at index 2 of the array.</p>
<p id="phi_function"><a class="p_ident" id="p_h+u9TgFTTH" href="#p_h+u9TgFTTH" tabindex="-1" role="presentation"></a>This is the function that computes the <em>ϕ</em> coefficient from such an array:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_AnoNjFldkv" href="#c_AnoNjFldkv" tabindex="-1" role="presentation"></a><span class="cm-keyword">function</span> <span class="cm-def">phi</span>(<span class="cm-def">table</span>) {
<span class="cm-keyword">return</span> (<span class="cm-variable-2">table</span>[<span class="cm-number">3</span>] <span class="cm-operator">*</span> <span class="cm-variable-2">table</span>[<span class="cm-number">0</span>] <span class="cm-operator">-</span> <span class="cm-variable-2">table</span>[<span class="cm-number">2</span>] <span class="cm-operator">*</span> <span class="cm-variable-2">table</span>[<span class="cm-number">1</span>]) <span class="cm-operator">/</span>
<span class="cm-variable">Math</span>.<span class="cm-property">sqrt</span>((<span class="cm-variable-2">table</span>[<span class="cm-number">2</span>] <span class="cm-operator">+</span> <span class="cm-variable-2">table</span>[<span class="cm-number">3</span>]) <span class="cm-operator">*</span>
(<span class="cm-variable-2">table</span>[<span class="cm-number">0</span>] <span class="cm-operator">+</span> <span class="cm-variable-2">table</span>[<span class="cm-number">1</span>]) <span class="cm-operator">*</span>
(<span class="cm-variable-2">table</span>[<span class="cm-number">1</span>] <span class="cm-operator">+</span> <span class="cm-variable-2">table</span>[<span class="cm-number">3</span>]) <span class="cm-operator">*</span>
(<span class="cm-variable-2">table</span>[<span class="cm-number">0</span>] <span class="cm-operator">+</span> <span class="cm-variable-2">table</span>[<span class="cm-number">2</span>]));
}
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">phi</span>([<span class="cm-number">76</span>, <span class="cm-number">9</span>, <span class="cm-number">4</span>, <span class="cm-number">1</span>]));
<span class="cm-comment">// → 0.068599434</span></pre>
<p><a class="p_ident" id="p_DPLO2QZk5F" href="#p_DPLO2QZk5F" tabindex="-1" role="presentation"></a>This is a direct translation of the <em>ϕ</em> formula into JavaScript. <code>Math.sqrt</code> is the square root function, as provided by the <code>Math</code> object in a standard JavaScript environment. We have to add two fields from the table to get fields like n<sub>1•</sub> because the sums of rows or columns are not stored directly in our data structure.</p>
<p><a class="p_ident" id="p_GhEP5hEDnb" href="#p_GhEP5hEDnb" tabindex="-1" role="presentation"></a>Jacques kept his journal for three months. The resulting data set is available in the <a href="https://eloquentjavascript.net/code#4">coding sandbox</a> for this chapter, where it is stored in the <code>JOURNAL</code> binding and in a downloadable <a href="https://eloquentjavascript.net/code/journal.js">file</a>.</p>
<p><a class="p_ident" id="p_sM+4QT8FKs" href="#p_sM+4QT8FKs" tabindex="-1" role="presentation"></a>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.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_rfea+FwMb5" href="#c_rfea+FwMb5" tabindex="-1" role="presentation"></a><span class="cm-keyword">function</span> <span class="cm-def">tableFor</span>(<span class="cm-def">event</span>, <span class="cm-def">journal</span>) {
<span class="cm-keyword">let</span> <span class="cm-def">table</span> <span class="cm-operator">=</span> [<span class="cm-number">0</span>, <span class="cm-number">0</span>, <span class="cm-number">0</span>, <span class="cm-number">0</span>];
<span class="cm-keyword">for</span> (<span class="cm-keyword">let</span> <span class="cm-def">i</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>; <span class="cm-variable-2">i</span> <span class="cm-operator"><</span> <span class="cm-variable-2">journal</span>.<span class="cm-property">length</span>; <span class="cm-variable-2">i</span><span class="cm-operator">++</span>) {
<span class="cm-keyword">let</span> <span class="cm-def">entry</span> <span class="cm-operator">=</span> <span class="cm-variable-2">journal</span>[<span class="cm-variable-2">i</span>], <span class="cm-def">index</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>;
<span class="cm-keyword">if</span> (<span class="cm-variable-2">entry</span>.<span class="cm-property">events</span>.<span class="cm-property">includes</span>(<span class="cm-variable-2">event</span>)) <span class="cm-variable-2">index</span> <span class="cm-operator">+=</span> <span class="cm-number">1</span>;
<span class="cm-keyword">if</span> (<span class="cm-variable-2">entry</span>.<span class="cm-property">squirrel</span>) <span class="cm-variable-2">index</span> <span class="cm-operator">+=</span> <span class="cm-number">2</span>;
<span class="cm-variable-2">table</span>[<span class="cm-variable-2">index</span>] <span class="cm-operator">+=</span> <span class="cm-number">1</span>;
}
<span class="cm-keyword">return</span> <span class="cm-variable-2">table</span>;
}
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">tableFor</span>(<span class="cm-string">"pizza"</span>, <span class="cm-variable">JOURNAL</span>));
<span class="cm-comment">// → [76, 9, 4, 1]</span></pre>
<p><a class="p_ident" id="p_1/7IsMpwdF" href="#p_1/7IsMpwdF" tabindex="-1" role="presentation"></a>Arrays have an <code>includes</code> 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.</p>
<p><a class="p_ident" id="p_2jmDtun7lQ" href="#p_2jmDtun7lQ" tabindex="-1" role="presentation"></a>The body of the loop in <code>tableFor</code> 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.</p>
<p><a class="p_ident" id="p_f0iI+VuF1R" href="#p_f0iI+VuF1R" tabindex="-1" role="presentation"></a>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.</p>
<h2 id="for_of_loop"><a class="h_ident" id="h_4WwZLib71C" href="#h_4WwZLib71C" tabindex="-1" role="presentation"></a>Array loops</h2>
<p><a class="p_ident" id="p_NcUX4h3Azc" href="#p_NcUX4h3Azc" tabindex="-1" role="presentation"></a>In the <code>tableFor</code> function, there’s a loop like this:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_pE7VRrRQir" href="#c_pE7VRrRQir" tabindex="-1" role="presentation"></a><span class="cm-keyword">for</span> (<span class="cm-keyword">let</span> <span class="cm-def">i</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>; <span class="cm-variable">i</span> <span class="cm-operator"><</span> <span class="cm-variable">JOURNAL</span>.<span class="cm-property">length</span>; <span class="cm-variable">i</span><span class="cm-operator">++</span>) {
<span class="cm-keyword">let</span> <span class="cm-def">entry</span> <span class="cm-operator">=</span> <span class="cm-variable">JOURNAL</span>[<span class="cm-variable">i</span>];
<span class="cm-comment">// Do something with entry</span>
}</pre>
<p><a class="p_ident" id="p_bofXG4HkzH" href="#p_bofXG4HkzH" tabindex="-1" role="presentation"></a>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.</p>
<p><a class="p_ident" id="p_Xl/M0+NR/e" href="#p_Xl/M0+NR/e" tabindex="-1" role="presentation"></a>There is a simpler way to write such loops in modern JavaScript.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_OXsCQPvDE1" href="#c_OXsCQPvDE1" tabindex="-1" role="presentation"></a><span class="cm-keyword">for</span> (<span class="cm-keyword">let</span> <span class="cm-def">entry</span> <span class="cm-keyword">of</span> <span class="cm-variable">JOURNAL</span>) {
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string-2">`${</span><span class="cm-variable">entry</span>.<span class="cm-property">events</span>.<span class="cm-property">length</span><span class="cm-string-2">}</span> <span class="cm-string-2">events.`</span>);
}</pre>
<p><a class="p_ident" id="p_LDkHv2luaA" href="#p_LDkHv2luaA" tabindex="-1" role="presentation"></a>When a <code>for</code> loop looks like this, with the word <code>of</code> after a variable definition, it will loop over the elements of the value given after <code>of</code>. This works not only for arrays but also for strings and some other data structures. We’ll discuss <em>how</em> it works in <a href="06_object.html">Chapter 6</a>.</p>
<h2 id="analysis"><a class="h_ident" id="h_Lg5n7mjqw/" href="#h_Lg5n7mjqw/" tabindex="-1" role="presentation"></a>The final analysis</h2>
<p><a class="p_ident" id="p_LI+01yIQON" href="#p_LI+01yIQON" tabindex="-1" role="presentation"></a>We need to compute a correlation for every type of event that occurs in the data set. To do that, we first need to <em>find</em> every type of event.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_P6cqJZBL1M" href="#c_P6cqJZBL1M" tabindex="-1" role="presentation"></a><span class="cm-keyword">function</span> <span class="cm-def">journalEvents</span>(<span class="cm-def">journal</span>) {
<span class="cm-keyword">let</span> <span class="cm-def">events</span> <span class="cm-operator">=</span> [];
<span class="cm-keyword">for</span> (<span class="cm-keyword">let</span> <span class="cm-def">entry</span> <span class="cm-keyword">of</span> <span class="cm-variable-2">journal</span>) {
<span class="cm-keyword">for</span> (<span class="cm-keyword">let</span> <span class="cm-def">event</span> <span class="cm-keyword">of</span> <span class="cm-variable-2">entry</span>.<span class="cm-property">events</span>) {
<span class="cm-keyword">if</span> (<span class="cm-operator">!</span><span class="cm-variable-2">events</span>.<span class="cm-property">includes</span>(<span class="cm-variable-2">event</span>)) {
<span class="cm-variable-2">events</span>.<span class="cm-property">push</span>(<span class="cm-variable-2">event</span>);
}
}
}
<span class="cm-keyword">return</span> <span class="cm-variable-2">events</span>;
}
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">journalEvents</span>(<span class="cm-variable">JOURNAL</span>));
<span class="cm-comment">// → ["carrot", "exercise", "weekend", "bread", …]</span></pre>
<p><a class="p_ident" id="p_vBsW+TJrFo" href="#p_vBsW+TJrFo" tabindex="-1" role="presentation"></a>By going over all the events and adding those that aren’t already in there to the <code>events</code> array, the function collects every type of event.</p>
<p><a class="p_ident" id="p_HohHy+JZoP" href="#p_HohHy+JZoP" tabindex="-1" role="presentation"></a>Using that, we can see all the correlations.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_7ws9oWaneM" href="#c_7ws9oWaneM" tabindex="-1" role="presentation"></a><span class="cm-keyword">for</span> (<span class="cm-keyword">let</span> <span class="cm-def">event</span> <span class="cm-keyword">of</span> <span class="cm-variable">journalEvents</span>(<span class="cm-variable">JOURNAL</span>)) {
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">event</span> <span class="cm-operator">+</span> <span class="cm-string">":"</span>, <span class="cm-variable">phi</span>(<span class="cm-variable">tableFor</span>(<span class="cm-variable">event</span>, <span class="cm-variable">JOURNAL</span>)));
}
<span class="cm-comment">// → carrot: 0.0140970969</span>
<span class="cm-comment">// → exercise: 0.0685994341</span>
<span class="cm-comment">// → weekend: 0.1371988681</span>
<span class="cm-comment">// → bread: -0.0757554019</span>
<span class="cm-comment">// → pudding: -0.0648203724</span>
<span class="cm-comment">// and so on...</span></pre>
<p><a class="p_ident" id="p_TiI6dIjE18" href="#p_TiI6dIjE18" tabindex="-1" role="presentation"></a>Most correlations seem to lie close to zero. Eating carrots, bread, or pudding apparently does not trigger squirrel-lycanthropy. It <em>does</em> 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.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_hBXzmb7hPU" href="#c_hBXzmb7hPU" tabindex="-1" role="presentation"></a><span class="cm-keyword">for</span> (<span class="cm-keyword">let</span> <span class="cm-def">event</span> <span class="cm-keyword">of</span> <span class="cm-variable">journalEvents</span>(<span class="cm-variable">JOURNAL</span>)) {
<span class="cm-keyword">let</span> <span class="cm-def">correlation</span> <span class="cm-operator">=</span> <span class="cm-variable">phi</span>(<span class="cm-variable">tableFor</span>(<span class="cm-variable">event</span>, <span class="cm-variable">JOURNAL</span>));
<span class="cm-keyword">if</span> (<span class="cm-variable-2">correlation</span> <span class="cm-operator">></span> <span class="cm-number">0.1</span> <span class="cm-operator">|</span><span class="cm-operator">|</span> <span class="cm-variable-2">correlation</span> <span class="cm-operator"><</span> <span class="cm-operator">-</span><span class="cm-number">0.1</span>) {
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">event</span> <span class="cm-operator">+</span> <span class="cm-string">":"</span>, <span class="cm-variable-2">correlation</span>);
}
}
<span class="cm-comment">// → weekend: 0.1371988681</span>
<span class="cm-comment">// → brushed teeth: -0.3805211953</span>
<span class="cm-comment">// → candy: 0.1296407447</span>
<span class="cm-comment">// → work: -0.1371988681</span>
<span class="cm-comment">// → spaghetti: 0.2425356250</span>
<span class="cm-comment">// → reading: 0.1106828054</span>
<span class="cm-comment">// → peanuts: 0.5902679812</span></pre>
<p><a class="p_ident" id="p_SmM3fqump2" href="#p_SmM3fqump2" tabindex="-1" role="presentation"></a>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.</p>
<p><a class="p_ident" id="p_CGdrhu89cM" href="#p_CGdrhu89cM" tabindex="-1" role="presentation"></a>Interesting. Let’s try something.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_x7WUJStSIp" href="#c_x7WUJStSIp" tabindex="-1" role="presentation"></a><span class="cm-keyword">for</span> (<span class="cm-keyword">let</span> <span class="cm-def">entry</span> <span class="cm-keyword">of</span> <span class="cm-variable">JOURNAL</span>) {
<span class="cm-keyword">if</span> (<span class="cm-variable">entry</span>.<span class="cm-property">events</span>.<span class="cm-property">includes</span>(<span class="cm-string">"peanuts"</span>) <span class="cm-operator">&</span><span class="cm-operator">&</span>
<span class="cm-operator">!</span><span class="cm-variable">entry</span>.<span class="cm-property">events</span>.<span class="cm-property">includes</span>(<span class="cm-string">"brushed teeth"</span>)) {
<span class="cm-variable">entry</span>.<span class="cm-property">events</span>.<span class="cm-property">push</span>(<span class="cm-string">"peanut teeth"</span>);
}
}
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">phi</span>(<span class="cm-variable">tableFor</span>(<span class="cm-string">"peanut teeth"</span>, <span class="cm-variable">JOURNAL</span>)));
<span class="cm-comment">// → 1</span></pre>
<p><a class="p_ident" id="p_Ji3VLlNJjI" href="#p_Ji3VLlNJjI" tabindex="-1" role="presentation"></a>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.</p>
<p><a class="p_ident" id="p_CLBAQ41EVq" href="#p_CLBAQ41EVq" tabindex="-1" role="presentation"></a>Knowing this, Jacques stops eating peanuts altogether and finds that his transformations don’t come back.</p>
<p><a class="p_ident" id="p_IMX7LE4P7A" href="#p_IMX7LE4P7A" tabindex="-1" role="presentation"></a>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 <em>The Incredible Squirrelman</em>, stuffing his mouth with peanut butter before every show.</p>
<p><a class="p_ident" id="p_SK7dEwTJMB" href="#p_SK7dEwTJMB" tabindex="-1" role="presentation"></a>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.</p>
<h2><a class="h_ident" id="h_GFaxee4PuU" href="#h_GFaxee4PuU" tabindex="-1" role="presentation"></a>Further arrayology</h2>
<p><a class="p_ident" id="p_Wik6gRMuIP" href="#p_Wik6gRMuIP" tabindex="-1" role="presentation"></a>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.</p>
<p><a class="p_ident" id="p_Px7nduaW01" href="#p_Px7nduaW01" tabindex="-1" role="presentation"></a>We saw <code>push</code> and <code>pop</code>, which add and remove elements at the end of an array, <a href="04_data.html#array_methods">earlier</a> in this chapter. The corresponding methods for adding and removing things at the start of an array are called <code>unshift</code> and <code>shift</code>.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_Vq1IBpy+hP" href="#c_Vq1IBpy+hP" tabindex="-1" role="presentation"></a><span class="cm-keyword">let</span> <span class="cm-def">todoList</span> <span class="cm-operator">=</span> [];
<span class="cm-keyword">function</span> <span class="cm-def">remember</span>(<span class="cm-def">task</span>) {
<span class="cm-variable">todoList</span>.<span class="cm-property">push</span>(<span class="cm-variable-2">task</span>);
}
<span class="cm-keyword">function</span> <span class="cm-def">getTask</span>() {
<span class="cm-keyword">return</span> <span class="cm-variable">todoList</span>.<span class="cm-property">shift</span>();
}
<span class="cm-keyword">function</span> <span class="cm-def">rememberUrgently</span>(<span class="cm-def">task</span>) {
<span class="cm-variable">todoList</span>.<span class="cm-property">unshift</span>(<span class="cm-variable-2">task</span>);
}</pre>
<p><a class="p_ident" id="p_Z35J/zKDAQ" href="#p_Z35J/zKDAQ" tabindex="-1" role="presentation"></a>That program manages a queue of tasks. You add tasks to the end of the queue by calling <code>remember("groceries")</code>, and when you’re ready to do something, you call <code>getTask()</code> to get (and remove) the front item from the queue. The <code>rememberUrgently</code> function also adds a task but adds it to the front instead of the back of the queue.</p>
<p><a class="p_ident" id="p_7VffwcInkI" href="#p_7VffwcInkI" tabindex="-1" role="presentation"></a>To search for a specific value, arrays provide an <code>indexOf</code> 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 <code>lastIndexOf</code>.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_N+G0EtTfto" href="#c_N+G0EtTfto" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>([<span class="cm-number">1</span>, <span class="cm-number">2</span>, <span class="cm-number">3</span>, <span class="cm-number">2</span>, <span class="cm-number">1</span>].<span class="cm-property">indexOf</span>(<span class="cm-number">2</span>));
<span class="cm-comment">// → 1</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>([<span class="cm-number">1</span>, <span class="cm-number">2</span>, <span class="cm-number">3</span>, <span class="cm-number">2</span>, <span class="cm-number">1</span>].<span class="cm-property">lastIndexOf</span>(<span class="cm-number">2</span>));
<span class="cm-comment">// → 3</span></pre>
<p><a class="p_ident" id="p_zErdHcwkcD" href="#p_zErdHcwkcD" tabindex="-1" role="presentation"></a>Both <code>indexOf</code> and <code>lastIndexOf</code> take an optional second argument that indicates where to start searching.</p>
<p><a class="p_ident" id="p_xl0kBHXnu2" href="#p_xl0kBHXnu2" tabindex="-1" role="presentation"></a>Another fundamental array method is <code>slice</code>, 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.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_zCBzPnMpIk" href="#c_zCBzPnMpIk" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>([<span class="cm-number">0</span>, <span class="cm-number">1</span>, <span class="cm-number">2</span>, <span class="cm-number">3</span>, <span class="cm-number">4</span>].<span class="cm-property">slice</span>(<span class="cm-number">2</span>, <span class="cm-number">4</span>));
<span class="cm-comment">// → [2, 3]</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>([<span class="cm-number">0</span>, <span class="cm-number">1</span>, <span class="cm-number">2</span>, <span class="cm-number">3</span>, <span class="cm-number">4</span>].<span class="cm-property">slice</span>(<span class="cm-number">2</span>));
<span class="cm-comment">// → [2, 3, 4]</span></pre>
<p><a class="p_ident" id="p_Y6nY8puZtN" href="#p_Y6nY8puZtN" tabindex="-1" role="presentation"></a>When the end index is not given, <code>slice</code> will take all of the elements after the start index. You can also omit the start index to copy the entire array.</p>
<p><a class="p_ident" id="p_QNFIcCtVLd" href="#p_QNFIcCtVLd" tabindex="-1" role="presentation"></a>The <code>concat</code> method can be used to glue arrays together to create a new array, similar to what the <code>+</code> operator does for strings.</p>
<p><a class="p_ident" id="p_x8OwNmbLzo" href="#p_x8OwNmbLzo" tabindex="-1" role="presentation"></a>The following example shows both <code>concat</code> and <code>slice</code> 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.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_q+NBMNgFFy" href="#c_q+NBMNgFFy" tabindex="-1" role="presentation"></a><span class="cm-keyword">function</span> <span class="cm-def">remove</span>(<span class="cm-def">array</span>, <span class="cm-def">index</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">array</span>.<span class="cm-property">slice</span>(<span class="cm-number">0</span>, <span class="cm-variable-2">index</span>)
.<span class="cm-property">concat</span>(<span class="cm-variable-2">array</span>.<span class="cm-property">slice</span>(<span class="cm-variable-2">index</span> <span class="cm-operator">+</span> <span class="cm-number">1</span>));
}
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">remove</span>([<span class="cm-string">"a"</span>, <span class="cm-string">"b"</span>, <span class="cm-string">"c"</span>, <span class="cm-string">"d"</span>, <span class="cm-string">"e"</span>], <span class="cm-number">2</span>));
<span class="cm-comment">// → ["a", "b", "d", "e"]</span></pre>
<p><a class="p_ident" id="p_RxH5uQN5Uq" href="#p_RxH5uQN5Uq" tabindex="-1" role="presentation"></a>If you pass <code>concat</code> an argument that is not an array, that value will be added to the new array as if it were a one-element array.</p>
<h2><a class="h_ident" id="h_mT4YQfwHp6" href="#h_mT4YQfwHp6" tabindex="-1" role="presentation"></a>Strings and their properties</h2>
<p><a class="p_ident" id="p_sp+O+Km+2n" href="#p_sp+O+Km+2n" tabindex="-1" role="presentation"></a>We can read properties like <code>length</code> and <code>toUpperCase</code> from string values. But if you try to add a new property, it doesn’t stick.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_xvzL9wErq7" href="#c_xvzL9wErq7" tabindex="-1" role="presentation"></a><span class="cm-keyword">let</span> <span class="cm-def">kim</span> <span class="cm-operator">=</span> <span class="cm-string">"Kim"</span>;
<span class="cm-variable">kim</span>.<span class="cm-property">age</span> <span class="cm-operator">=</span> <span class="cm-number">88</span>;
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">kim</span>.<span class="cm-property">age</span>);
<span class="cm-comment">// → undefined</span></pre>
<p><a class="p_ident" id="p_B+oSPYAIbV" href="#p_B+oSPYAIbV" tabindex="-1" role="presentation"></a>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.</p>
<p><a class="p_ident" id="p_8L2ib2beYN" href="#p_8L2ib2beYN" tabindex="-1" role="presentation"></a>But these types do have built-in properties. Every string value has a number of methods. Some very useful ones are <code>slice</code> and <code>indexOf</code>, which resemble the array methods of the same name.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_/Tmq1doYeG" href="#c_/Tmq1doYeG" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"coconuts"</span>.<span class="cm-property">slice</span>(<span class="cm-number">4</span>, <span class="cm-number">7</span>));
<span class="cm-comment">// → nut</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"coconut"</span>.<span class="cm-property">indexOf</span>(<span class="cm-string">"u"</span>));
<span class="cm-comment">// → 5</span></pre>
<p><a class="p_ident" id="p_RUd6q+Q4dc" href="#p_RUd6q+Q4dc" tabindex="-1" role="presentation"></a>One difference is that a string’s <code>indexOf</code> can search for a string containing more than one character, whereas the corresponding array method looks only for a single element.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_xM5/GBnZVG" href="#c_xM5/GBnZVG" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"one two three"</span>.<span class="cm-property">indexOf</span>(<span class="cm-string">"ee"</span>));
<span class="cm-comment">// → 11</span></pre>
<p><a class="p_ident" id="p_USclxilOGS" href="#p_USclxilOGS" tabindex="-1" role="presentation"></a>The <code>trim</code> method removes whitespace (spaces, newlines, tabs, and similar characters) from the start and end of a string.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_0AfLRWyjq0" href="#c_0AfLRWyjq0" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">" okay \n "</span>.<span class="cm-property">trim</span>());
<span class="cm-comment">// → okay</span></pre>
<p><a class="p_ident" id="p_pSkK9k9R0g" href="#p_pSkK9k9R0g" tabindex="-1" role="presentation"></a>The <code>zeroPad</code> function from the <a href="03_functions.html">previous chapter</a> also exists as a method. It is called <code>padStart</code> and takes the desired length and padding character as arguments.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_SJbD9MiYu+" href="#c_SJbD9MiYu+" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">String</span>(<span class="cm-number">6</span>).<span class="cm-property">padStart</span>(<span class="cm-number">3</span>, <span class="cm-string">"0"</span>));
<span class="cm-comment">// → 006</span></pre>
<p id="split"><a class="p_ident" id="p_/nMvmESoIj" href="#p_/nMvmESoIj" tabindex="-1" role="presentation"></a>You can split a string on every occurrence of another string with <code>split</code> and join it again with <code>join</code>.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_/rV2Ed5e8V" href="#c_/rV2Ed5e8V" tabindex="-1" role="presentation"></a><span class="cm-keyword">let</span> <span class="cm-def">sentence</span> <span class="cm-operator">=</span> <span class="cm-string">"Secretarybirds specialize in stomping"</span>;
<span class="cm-keyword">let</span> <span class="cm-def">words</span> <span class="cm-operator">=</span> <span class="cm-variable">sentence</span>.<span class="cm-property">split</span>(<span class="cm-string">" "</span>);
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">words</span>);
<span class="cm-comment">// → ["Secretarybirds", "specialize", "in", "stomping"]</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">words</span>.<span class="cm-property">join</span>(<span class="cm-string">". "</span>));
<span class="cm-comment">// → Secretarybirds. specialize. in. stomping</span></pre>
<p><a class="p_ident" id="p_EKC26dOCjK" href="#p_EKC26dOCjK" tabindex="-1" role="presentation"></a>A string can be repeated with the <code>repeat</code> method, which creates a new string containing multiple copies of the original string, glued together.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_70WotkNADb" href="#c_70WotkNADb" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"LA"</span>.<span class="cm-property">repeat</span>(<span class="cm-number">3</span>));
<span class="cm-comment">// → LALALA</span></pre>
<p><a class="p_ident" id="p_JoGJxr+Ofe" href="#p_JoGJxr+Ofe" tabindex="-1" role="presentation"></a>We have already seen the string type’s <code>length</code> property. Accessing the individual characters in a string looks like accessing array elements (with a caveat that we’ll discuss in <a href="05_higher_order.html#code_units">Chapter 5</a>).</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_Aeop9AuKAb" href="#c_Aeop9AuKAb" tabindex="-1" role="presentation"></a><span class="cm-keyword">let</span> <span class="cm-def">string</span> <span class="cm-operator">=</span> <span class="cm-string">"abc"</span>;
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">string</span>.<span class="cm-property">length</span>);
<span class="cm-comment">// → 3</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">string</span>[<span class="cm-number">1</span>]);
<span class="cm-comment">// → b</span></pre>
<h2 id="rest_parameters"><a class="h_ident" id="h_hX9DkIBp9y" href="#h_hX9DkIBp9y" tabindex="-1" role="presentation"></a>Rest parameters</h2>
<p><a class="p_ident" id="p_4Vr2QMYcHp" href="#p_4Vr2QMYcHp" tabindex="-1" role="presentation"></a>It can be useful for a function to accept any number of arguments. For example, <code>Math.max</code> computes the maximum of <em>all</em> the arguments it is given.</p>
<p><a class="p_ident" id="p_eWuSc6aG2b" href="#p_eWuSc6aG2b" tabindex="-1" role="presentation"></a>To write such a function, you put three dots before the function’s last parameter, like this:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_UXPbyGFVIB" href="#c_UXPbyGFVIB" tabindex="-1" role="presentation"></a><span class="cm-keyword">function</span> <span class="cm-def">max</span>(<span class="cm-meta">...</span><span class="cm-def">numbers</span>) {
<span class="cm-keyword">let</span> <span class="cm-def">result</span> <span class="cm-operator">=</span> <span class="cm-operator">-</span><span class="cm-atom">Infinity</span>;
<span class="cm-keyword">for</span> (<span class="cm-keyword">let</span> <span class="cm-def">number</span> <span class="cm-keyword">of</span> <span class="cm-variable-2">numbers</span>) {
<span class="cm-keyword">if</span> (<span class="cm-variable-2">number</span> <span class="cm-operator">></span> <span class="cm-variable-2">result</span>) <span class="cm-variable-2">result</span> <span class="cm-operator">=</span> <span class="cm-variable-2">number</span>;
}
<span class="cm-keyword">return</span> <span class="cm-variable-2">result</span>;
}
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">max</span>(<span class="cm-number">4</span>, <span class="cm-number">1</span>, <span class="cm-number">9</span>, <span class="cm-operator">-</span><span class="cm-number">2</span>));
<span class="cm-comment">// → 9</span></pre>
<p><a class="p_ident" id="p_rGoFNpUuEy" href="#p_rGoFNpUuEy" tabindex="-1" role="presentation"></a>When such a function is called, the <em>rest parameter</em> 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 <code>max</code>, it is the only parameter, it will hold all arguments.</p>
<p><a class="p_ident" id="p_ZVL6nOj2oy" href="#p_ZVL6nOj2oy" tabindex="-1" role="presentation"></a>You can use a similar three-dot notation to <em>call</em> a function with an array of arguments.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_h9hmTe3vix" href="#c_h9hmTe3vix" tabindex="-1" role="presentation"></a><span class="cm-keyword">let</span> <span class="cm-def">numbers</span> <span class="cm-operator">=</span> [<span class="cm-number">5</span>, <span class="cm-number">1</span>, <span class="cm-number">7</span>];
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">max</span>(<span class="cm-meta">...</span><span class="cm-variable">numbers</span>));
<span class="cm-comment">// → 7</span></pre>
<p><a class="p_ident" id="p_Q6Tzyy9eaj" href="#p_Q6Tzyy9eaj" tabindex="-1" role="presentation"></a>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 <code>max(9, .<wbr>.<wbr>.<wbr>numbers, 2)</code>.</p>
<p><a class="p_ident" id="p_/SfVO/tjcB" href="#p_/SfVO/tjcB" tabindex="-1" role="presentation"></a>Square bracket array notation similarly allows the triple-dot operator to spread another array into the new array.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_4t+LJt3Kyo" href="#c_4t+LJt3Kyo" tabindex="-1" role="presentation"></a><span class="cm-keyword">let</span> <span class="cm-def">words</span> <span class="cm-operator">=</span> [<span class="cm-string">"never"</span>, <span class="cm-string">"fully"</span>];
<span class="cm-variable">console</span>.<span class="cm-property">log</span>([<span class="cm-string">"will"</span>, <span class="cm-meta">...</span><span class="cm-variable">words</span>, <span class="cm-string">"understand"</span>]);
<span class="cm-comment">// → ["will", "never", "fully", "understand"]</span></pre>
<h2><a class="h_ident" id="h_C51DnYk8WZ" href="#h_C51DnYk8WZ" tabindex="-1" role="presentation"></a>The Math object</h2>
<p><a class="p_ident" id="p_h3aa0itA5J" href="#p_h3aa0itA5J" tabindex="-1" role="presentation"></a>As we’ve seen, <code>Math</code> is a grab bag of number-related utility functions, such as <code>Math.max</code> (maximum), <code>Math.min</code> (minimum), and <code>Math.sqrt</code> (square root).</p>
<p id="namespace_pollution"><a class="p_ident" id="p_Sae3fXYP2/" href="#p_Sae3fXYP2/" tabindex="-1" role="presentation"></a>The <code>Math</code> object is used as a container to group a bunch of related functionality. There is only one <code>Math</code> object, and it is almost never useful as a value. Rather, it provides a <em>namespace</em> so that all these functions and values do not have to be global bindings.</p>
<p><a class="p_ident" id="p_fGEMziAXhp" href="#p_fGEMziAXhp" tabindex="-1" role="presentation"></a>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 <code>max</code> in one of your programs. Since JavaScript’s built-in <code>max</code> function is tucked safely inside the <code>Math</code> object, we don’t have to worry about overwriting it.</p>
<p><a class="p_ident" id="p_6OHrUF+WEc" href="#p_6OHrUF+WEc" tabindex="-1" role="presentation"></a>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 <code>let</code> or <code>const</code> but—perversely—not for standard bindings nor for bindings declared with <code>var</code> or <code>function</code>.</p>
<p><a class="p_ident" id="p_zWXQRNgLI/" href="#p_zWXQRNgLI/" tabindex="-1" role="presentation"></a>Back to the <code>Math</code> object. If you need to do trigonometry, <code>Math</code> can help. It contains <code>cos</code> (cosine), <code>sin</code> (sine), and <code>tan</code> (tangent), as well as their inverse functions, <code>acos</code>, <code>asin</code>, and <code>atan</code>, respectively. The number π (pi)—or at least the closest approximation that fits in a JavaScript number—is available as <code>Math.PI</code>. There is an old programming tradition of writing the names of constant values in all caps.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_54zxf+2nsU" href="#c_54zxf+2nsU" tabindex="-1" role="presentation"></a><span class="cm-keyword">function</span> <span class="cm-def">randomPointOnCircle</span>(<span class="cm-def">radius</span>) {
<span class="cm-keyword">let</span> <span class="cm-def">angle</span> <span class="cm-operator">=</span> <span class="cm-variable">Math</span>.<span class="cm-property">random</span>() <span class="cm-operator">*</span> <span class="cm-number">2</span> <span class="cm-operator">*</span> <span class="cm-variable">Math</span>.<span class="cm-property">PI</span>;
<span class="cm-keyword">return</span> {<span class="cm-property">x</span>: <span class="cm-variable-2">radius</span> <span class="cm-operator">*</span> <span class="cm-variable">Math</span>.<span class="cm-property">cos</span>(<span class="cm-variable-2">angle</span>),
<span class="cm-property">y</span>: <span class="cm-variable-2">radius</span> <span class="cm-operator">*</span> <span class="cm-variable">Math</span>.<span class="cm-property">sin</span>(<span class="cm-variable-2">angle</span>)};
}
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">randomPointOnCircle</span>(<span class="cm-number">2</span>));
<span class="cm-comment">// → {x: 0.3667, y: 1.966}</span></pre>
<p><a class="p_ident" id="p_KN16iaNdwJ" href="#p_KN16iaNdwJ" tabindex="-1" role="presentation"></a>If sines and cosines are not something you are familiar with, don’t worry. When they are used in this book, in <a href="14_dom.html#sin_cos">Chapter 14</a>, I’ll explain them.</p>
<p><a class="p_ident" id="p_a6xMq73yCc" href="#p_a6xMq73yCc" tabindex="-1" role="presentation"></a>The previous example used <code>Math.random</code>. This is a function that returns a new pseudorandom number between zero (inclusive) and one (exclusive) every time you call it.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_+gqW4B1qk1" href="#c_+gqW4B1qk1" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">Math</span>.<span class="cm-property">random</span>());
<span class="cm-comment">// → 0.36993729369714856</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">Math</span>.<span class="cm-property">random</span>());
<span class="cm-comment">// → 0.727367032552138</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">Math</span>.<span class="cm-property">random</span>());
<span class="cm-comment">// → 0.40180766698904335</span></pre>
<p><a class="p_ident" id="p_wukRTlH+QE" href="#p_wukRTlH+QE" tabindex="-1" role="presentation"></a>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 <em>seems</em> random.</p>
<p><a class="p_ident" id="p_2guGKjrtTY" href="#p_2guGKjrtTY" tabindex="-1" role="presentation"></a>If we want a whole random number instead of a fractional one, we can use <code>Math.floor</code> (which rounds down to the nearest whole number) on the result of <code>Math.random</code>.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_LlfOX4tbSH" href="#c_LlfOX4tbSH" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">Math</span>.<span class="cm-property">floor</span>(<span class="cm-variable">Math</span>.<span class="cm-property">random</span>() <span class="cm-operator">*</span> <span class="cm-number">10</span>));
<span class="cm-comment">// → 2</span></pre>
<p><a class="p_ident" id="p_qcgl/8YUFj" href="#p_qcgl/8YUFj" tabindex="-1" role="presentation"></a>Multiplying the random number by 10 gives us a number greater than or equal to 0 and below 10. Since <code>Math.floor</code> rounds down, this expression will produce, with equal chance, any number from 0 through 9.</p>
<p><a class="p_ident" id="p_4Vo+PhEiYY" href="#p_4Vo+PhEiYY" tabindex="-1" role="presentation"></a>There are also the functions <code>Math.ceil</code> (for “ceiling”, which rounds up to a whole number), <code>Math.round</code> (to the nearest whole number), and <code>Math.abs</code>, which takes the absolute value of a number, meaning it negates negative values but leaves positive ones as they are.</p>
<h2><a class="h_ident" id="h_B372u36cp6" href="#h_B372u36cp6" tabindex="-1" role="presentation"></a>Destructuring</h2>
<p><a class="p_ident" id="p_YaENzwA635" href="#p_YaENzwA635" tabindex="-1" role="presentation"></a>Let’s go back to the <code>phi</code> function for a moment.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_8p90ivE8ZI" href="#c_8p90ivE8ZI" tabindex="-1" role="presentation"></a><span class="cm-keyword">function</span> <span class="cm-def">phi</span>(<span class="cm-def">table</span>) {
<span class="cm-keyword">return</span> (<span class="cm-variable-2">table</span>[<span class="cm-number">3</span>] <span class="cm-operator">*</span> <span class="cm-variable-2">table</span>[<span class="cm-number">0</span>] <span class="cm-operator">-</span> <span class="cm-variable-2">table</span>[<span class="cm-number">2</span>] <span class="cm-operator">*</span> <span class="cm-variable-2">table</span>[<span class="cm-number">1</span>]) <span class="cm-operator">/</span>
<span class="cm-variable">Math</span>.<span class="cm-property">sqrt</span>((<span class="cm-variable-2">table</span>[<span class="cm-number">2</span>] <span class="cm-operator">+</span> <span class="cm-variable-2">table</span>[<span class="cm-number">3</span>]) <span class="cm-operator">*</span>
(<span class="cm-variable-2">table</span>[<span class="cm-number">0</span>] <span class="cm-operator">+</span> <span class="cm-variable-2">table</span>[<span class="cm-number">1</span>]) <span class="cm-operator">*</span>
(<span class="cm-variable-2">table</span>[<span class="cm-number">1</span>] <span class="cm-operator">+</span> <span class="cm-variable-2">table</span>[<span class="cm-number">3</span>]) <span class="cm-operator">*</span>
(<span class="cm-variable-2">table</span>[<span class="cm-number">0</span>] <span class="cm-operator">+</span> <span class="cm-variable-2">table</span>[<span class="cm-number">2</span>]));
}</pre>
<p><a class="p_ident" id="p_KYh2WplVnQ" href="#p_KYh2WplVnQ" tabindex="-1" role="presentation"></a>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 <em>elements</em> of the array, that is, <code>let n00 = table[0]</code> and so on. Fortunately, there is a succinct way to do this in JavaScript.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_z2cboTL/zX" href="#c_z2cboTL/zX" tabindex="-1" role="presentation"></a><span class="cm-keyword">function</span> <span class="cm-def">phi</span>([<span class="cm-def">n00</span>, <span class="cm-def">n01</span>, <span class="cm-def">n10</span>, <span class="cm-def">n11</span>]) {
<span class="cm-keyword">return</span> (<span class="cm-variable-2">n11</span> <span class="cm-operator">*</span> <span class="cm-variable-2">n00</span> <span class="cm-operator">-</span> <span class="cm-variable-2">n10</span> <span class="cm-operator">*</span> <span class="cm-variable-2">n01</span>) <span class="cm-operator">/</span>
<span class="cm-variable">Math</span>.<span class="cm-property">sqrt</span>((<span class="cm-variable-2">n10</span> <span class="cm-operator">+</span> <span class="cm-variable-2">n11</span>) <span class="cm-operator">*</span> (<span class="cm-variable-2">n00</span> <span class="cm-operator">+</span> <span class="cm-variable-2">n01</span>) <span class="cm-operator">*</span>
(<span class="cm-variable-2">n01</span> <span class="cm-operator">+</span> <span class="cm-variable-2">n11</span>) <span class="cm-operator">*</span> (<span class="cm-variable-2">n00</span> <span class="cm-operator">+</span> <span class="cm-variable-2">n10</span>));
}</pre>
<p><a class="p_ident" id="p_kBO/cFWeM1" href="#p_kBO/cFWeM1" tabindex="-1" role="presentation"></a>This also works for bindings created with <code>let</code>, <code>var</code>, or <code>const</code>. 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.</p>
<p><a class="p_ident" id="p_Zr6hFslmUP" href="#p_Zr6hFslmUP" tabindex="-1" role="presentation"></a>A similar trick works for objects, using braces instead of square brackets.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_ZXEdn9Xbfc" href="#c_ZXEdn9Xbfc" tabindex="-1" role="presentation"></a><span class="cm-keyword">let</span> {<span class="cm-def">name</span>} <span class="cm-operator">=</span> {<span class="cm-property">name</span>: <span class="cm-string">"Faraji"</span>, <span class="cm-property">age</span>: <span class="cm-number">23</span>};
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">name</span>);
<span class="cm-comment">// → Faraji</span></pre>
<p><a class="p_ident" id="p_1RhWeB9//B" href="#p_1RhWeB9//B" tabindex="-1" role="presentation"></a>Note that if you try to destructure <code>null</code> or <code>undefined</code>, you get an error, much as you would if you directly try to access a property of those values.</p>
<h2><a class="h_ident" id="h_AxpOdvCznQ" href="#h_AxpOdvCznQ" tabindex="-1" role="presentation"></a>JSON</h2>
<p><a class="p_ident" id="p_7o8VSa4Rvc" href="#p_7o8VSa4Rvc" tabindex="-1" role="presentation"></a>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 <em>addresses</em>—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.</p>
<p><a class="p_ident" id="p_aF+08iJEQw" href="#p_aF+08iJEQw" tabindex="-1" role="presentation"></a>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 <em>could</em> 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.</p>
<p><a class="p_ident" id="p_ZM103Qyv6l" href="#p_ZM103Qyv6l" tabindex="-1" role="presentation"></a>What we can do is <em>serialize</em> the data. That means it is converted into a flat description. A popular serialization format is called <em>JSON</em> (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.</p>
<p><a class="p_ident" id="p_IMEKAvSfAI" href="#p_IMEKAvSfAI" tabindex="-1" role="presentation"></a>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.</p>
<p><a class="p_ident" id="p_9DCLKzKNiz" href="#p_9DCLKzKNiz" tabindex="-1" role="presentation"></a>A journal entry might look like this when represented as JSON data:</p>
<pre class="snippet cm-s-default" data-language="application/json" ><a class="c_ident" id="c_A3jdCqz1Q6" href="#c_A3jdCqz1Q6" tabindex="-1" role="presentation"></a>{
<span class="cm-string cm-property">"squirrel"</span>: <span class="cm-atom">false</span>,
<span class="cm-string cm-property">"events"</span>: [<span class="cm-string">"work"</span>, <span class="cm-string">"touched tree"</span>, <span class="cm-string">"pizza"</span>, <span class="cm-string">"running"</span>]
}</pre>
<p><a class="p_ident" id="p_1IU60Zh2Af" href="#p_1IU60Zh2Af" tabindex="-1" role="presentation"></a>JavaScript gives us the functions <code>JSON.stringify</code> and <code>JSON.parse</code> 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.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_HYCgCsK7z1" href="#c_HYCgCsK7z1" tabindex="-1" role="presentation"></a><span class="cm-keyword">let</span> <span class="cm-def">string</span> <span class="cm-operator">=</span> <span class="cm-variable">JSON</span>.<span class="cm-property">stringify</span>({<span class="cm-property">squirrel</span>: <span class="cm-atom">false</span>,
<span class="cm-property">events</span>: [<span class="cm-string">"weekend"</span>]});
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">string</span>);
<span class="cm-comment">// → {"squirrel":false,"events":["weekend"]}</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">JSON</span>.<span class="cm-property">parse</span>(<span class="cm-variable">string</span>).<span class="cm-property">events</span>);
<span class="cm-comment">// → ["weekend"]</span></pre>
<h2><a class="h_ident" id="h_ErccPg/l98" href="#h_ErccPg/l98" tabindex="-1" role="presentation"></a>Summary</h2>
<p><a class="p_ident" id="p_78ZfHX5x1B" href="#p_78ZfHX5x1B" tabindex="-1" role="presentation"></a>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.</p>
<p><a class="p_ident" id="p_ayhyxvWlMH" href="#p_ayhyxvWlMH" tabindex="-1" role="presentation"></a>Most values in JavaScript have properties, the exceptions being <code>null</code> and <code>undefined</code>. Properties are accessed using <code>value.prop</code> or <code>value["prop"]</code>. 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.</p>
<p><a class="p_ident" id="p_1lcitbawCQ" href="#p_1lcitbawCQ" tabindex="-1" role="presentation"></a>There <em>are</em> some named properties in arrays, such as <code>length</code> and a number of methods. Methods are functions that live in properties and (usually) act on the value they are a property of.</p>
<p><a class="p_ident" id="p_KWzs1al6OP" href="#p_KWzs1al6OP" tabindex="-1" role="presentation"></a>You can iterate over arrays using a special kind of <code>for</code> loop—<code>for (let element of array)</code>.</p>
<h2><a class="h_ident" id="h_TcUD2vzyMe" href="#h_TcUD2vzyMe" tabindex="-1" role="presentation"></a>Exercises</h2>
<h3><a class="i_ident" id="i_8ZspxiCEC/" href="#i_8ZspxiCEC/" tabindex="-1" role="presentation"></a>The sum of a range</h3>
<p><a class="p_ident" id="p_fpyyiv/hm1" href="#p_fpyyiv/hm1" tabindex="-1" role="presentation"></a>The <a href="00_intro.html">introduction</a> of this book alluded to the following as a nice way to compute the sum of a range of numbers:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_KTbQMmMCli" href="#c_KTbQMmMCli" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">sum</span>(<span class="cm-variable">range</span>(<span class="cm-number">1</span>, <span class="cm-number">10</span>)));</pre>
<p><a class="p_ident" id="p_uTMnVb6I1m" href="#p_uTMnVb6I1m" tabindex="-1" role="presentation"></a>Write a <code>range</code> function that takes two arguments, <code>start</code> and <code>end</code>, and returns an array containing all the numbers from <code>start</code> up to (and including) <code>end</code>.</p>
<p><a class="p_ident" id="p_0GiJNcBSop" href="#p_0GiJNcBSop" tabindex="-1" role="presentation"></a>Next, write a <code>sum</code> 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.</p>
<p><a class="p_ident" id="p_1Uvf7bfQT8" href="#p_1Uvf7bfQT8" tabindex="-1" role="presentation"></a>As a bonus assignment, modify your <code>range</code> 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 <code>range(1, 10, 2)</code> should return <code>[1, 3, 5, 7, 9]</code>. Make sure it also works with negative step values so that <code>range(5, 2, -1)</code> produces <code>[5, 4, 3, 2]</code>.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_gV3XCKJAqj" href="#c_gV3XCKJAqj" tabindex="-1" role="presentation"></a><span class="cm-comment">// Your code here.</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">range</span>(<span class="cm-number">1</span>, <span class="cm-number">10</span>));
<span class="cm-comment">// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">range</span>(<span class="cm-number">5</span>, <span class="cm-number">2</span>, <span class="cm-operator">-</span><span class="cm-number">1</span>));
<span class="cm-comment">// → [5, 4, 3, 2]</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">sum</span>(<span class="cm-variable">range</span>(<span class="cm-number">1</span>, <span class="cm-number">10</span>)));
<span class="cm-comment">// → 55</span></pre>
<div class="solution"><div class="solution-text">
<p><a class="p_ident" id="p_AzWVqPrlre" href="#p_AzWVqPrlre" tabindex="-1" role="presentation"></a>Building up an array is most easily done by first initializing a binding to <code>[]</code> (a fresh, empty array) and repeatedly calling its <code>push</code> method to add a value. Don’t forget to return the array at the end of the function.</p>
<p><a class="p_ident" id="p_eu6MUPwjEb" href="#p_eu6MUPwjEb" tabindex="-1" role="presentation"></a>Since the end boundary is inclusive, you’ll need to use the <code><=</code> operator rather than <code><</code> to check for the end of your loop.</p>
<p><a class="p_ident" id="p_kvr5NnqBEW" href="#p_kvr5NnqBEW" tabindex="-1" role="presentation"></a>The step parameter can be an optional parameter that defaults (using the <code>=</code> operator) to 1.</p>
<p><a class="p_ident" id="p_zih2wFkrk5" href="#p_zih2wFkrk5" tabindex="-1" role="presentation"></a>Having <code>range</code> 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 <code>>=</code> rather than <code><=</code> when counting downward.</p>
<p><a class="p_ident" id="p_d7Vi2uDSps" href="#p_d7Vi2uDSps" tabindex="-1" role="presentation"></a>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, <code>range(5, 2)</code> 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.</p>
</div></div>
<h3><a class="i_ident" id="i_6xTmjj4Rf5" href="#i_6xTmjj4Rf5" tabindex="-1" role="presentation"></a>Reversing an array</h3>
<p><a class="p_ident" id="p_+SVCOC/qcN" href="#p_+SVCOC/qcN" tabindex="-1" role="presentation"></a>Arrays have a <code>reverse</code> method that changes the array by inverting the order in which its elements appear. For this exercise, write two functions, <code>reverseArray</code> and <code>reverseArrayInPlace</code>. The first, <code>reverseArray</code>, takes an array as argument and produces a <em>new</em> array that has the same elements in the inverse order. The second, <code>reverseArrayInPlace</code>, does what the <code>reverse</code> method does: it <em>modifies</em> the array given as argument by reversing its elements. Neither may use the standard <code>reverse</code> method.</p>
<p><a class="p_ident" id="p_SpaDJmGkSI" href="#p_SpaDJmGkSI" tabindex="-1" role="presentation"></a>Thinking back to the notes about side effects and pure functions in the <a href="03_functions.html#pure">previous chapter</a>, which variant do you expect to be useful in more situations? Which one runs faster?</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_sghv5avX0H" href="#c_sghv5avX0H" tabindex="-1" role="presentation"></a><span class="cm-comment">// Your code here.</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">reverseArray</span>([<span class="cm-string">"A"</span>, <span class="cm-string">"B"</span>, <span class="cm-string">"C"</span>]));
<span class="cm-comment">// → ["C", "B", "A"];</span>
<span class="cm-keyword">let</span> <span class="cm-def">arrayValue</span> <span class="cm-operator">=</span> [<span class="cm-number">1</span>, <span class="cm-number">2</span>, <span class="cm-number">3</span>, <span class="cm-number">4</span>, <span class="cm-number">5</span>];
<span class="cm-variable">reverseArrayInPlace</span>(<span class="cm-variable">arrayValue</span>);
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">arrayValue</span>);
<span class="cm-comment">// → [5, 4, 3, 2, 1]</span></pre>
<div class="solution"><div class="solution-text">
<p><a class="p_ident" id="p_bJlW8Cyw1e" href="#p_bJlW8Cyw1e" tabindex="-1" role="presentation"></a>There are two obvious ways to implement <code>reverseArray</code>. The first is to simply go over the input array from front to back and use the <code>unshift</code> 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 <code>push</code> method. Iterating over an array backwards requires a (somewhat awkward) <code>for</code> specification, like <code>(let i = array.<wbr>length - 1; i >= 0; i--)</code>.</p>
<p><a class="p_ident" id="p_Y08sN3Yej5" href="#p_Y08sN3Yej5" tabindex="-1" role="presentation"></a>Reversing the array in place is harder. You have to be careful not to overwrite elements that you will later need. Using <code>reverseArray</code> or otherwise copying the whole array (<code>array.slice(0)</code> is a good way to copy an array) works but is cheating.</p>
<p><a class="p_ident" id="p_hzYSkS4zzl" href="#p_hzYSkS4zzl" tabindex="-1" role="presentation"></a>The trick is to <em>swap</em> 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 <code>Math.floor</code> 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 <code>i</code> with the one at position <code>array.<wbr>length - 1 - i</code>. 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.</p>
</div></div>
<h3 id="list"><a class="i_ident" id="i_nSTX34CM1M" href="#i_nSTX34CM1M" tabindex="-1" role="presentation"></a>A list</h3>
<p><a class="p_ident" id="p_7AnSuS26HF" href="#p_7AnSuS26HF" tabindex="-1" role="presentation"></a>Objects, as generic blobs of values, can be used to build all sorts of data structures. A common data structure is the <em>list</em> (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.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_kYAco70aHD" href="#c_kYAco70aHD" tabindex="-1" role="presentation"></a><span class="cm-keyword">let</span> <span class="cm-def">list</span> <span class="cm-operator">=</span> {
<span class="cm-property">value</span>: <span class="cm-number">1</span>,
<span class="cm-property">rest</span>: {
<span class="cm-property">value</span>: <span class="cm-number">2</span>,
<span class="cm-property">rest</span>: {
<span class="cm-property">value</span>: <span class="cm-number">3</span>,
<span class="cm-property">rest</span>: <span class="cm-atom">null</span>
}
}
};</pre>
<p><a class="p_ident" id="p_2un5u6U14Q" href="#p_2un5u6U14Q" tabindex="-1" role="presentation"></a>The resulting objects form a chain, like this:</p><figure><img src="img/linked-list.svg" alt="A linked list"></figure>
<p><a class="p_ident" id="p_NaI0fhp38z" href="#p_NaI0fhp38z" tabindex="-1" role="presentation"></a>A nice thing about lists is that they can share parts of their structure. For example, if I create two new values <code>{value: 0, rest: list}</code> and <code>{value: -1, rest: list}</code> (with <code>list</code> 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.</p>
<p><a class="p_ident" id="p_iPlgVCeZGh" href="#p_iPlgVCeZGh" tabindex="-1" role="presentation"></a>Write a function <code>arrayToList</code> that builds up a list structure like the one shown when given <code>[1, 2, 3]</code> as argument. Also write a <code>listToArray</code> function that produces an array from a list. Then add a helper function <code>prepend</code>, which takes an element and a list and creates a new list that adds the element to the front of the input list, and <code>nth</code>, 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 <code>undefined</code> when there is no such element.</p>
<p><a class="p_ident" id="p_8YcepSmcdv" href="#p_8YcepSmcdv" tabindex="-1" role="presentation"></a>If you haven’t already, also write a recursive version of <code>nth</code>.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_rufmukl+AQ" href="#c_rufmukl+AQ" tabindex="-1" role="presentation"></a><span class="cm-comment">// Your code here.</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">arrayToList</span>([<span class="cm-number">10</span>, <span class="cm-number">20</span>]));
<span class="cm-comment">// → {value: 10, rest: {value: 20, rest: null}}</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">listToArray</span>(<span class="cm-variable">arrayToList</span>([<span class="cm-number">10</span>, <span class="cm-number">20</span>, <span class="cm-number">30</span>])));
<span class="cm-comment">// → [10, 20, 30]</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">prepend</span>(<span class="cm-number">10</span>, <span class="cm-variable">prepend</span>(<span class="cm-number">20</span>, <span class="cm-atom">null</span>)));
<span class="cm-comment">// → {value: 10, rest: {value: 20, rest: null}}</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">nth</span>(<span class="cm-variable">arrayToList</span>([<span class="cm-number">10</span>, <span class="cm-number">20</span>, <span class="cm-number">30</span>]), <span class="cm-number">1</span>));
<span class="cm-comment">// → 20</span></pre>
<div class="solution"><div class="solution-text">
<p><a class="p_ident" id="p_gUGYq9Tjlx" href="#p_gUGYq9Tjlx" tabindex="-1" role="presentation"></a>Building up a list is easier when done back to front. So <code>arrayToList</code> 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 <code>list = {value: X, rest: list}</code> to add an element.</p>
<p><a class="p_ident" id="p_+rJULr60CD" href="#p_+rJULr60CD" tabindex="-1" role="presentation"></a>To run over a list (in <code>listToArray</code> and <code>nth</code>), a <code>for</code> loop specification like this can be used:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_HLrOQGihFR" href="#c_HLrOQGihFR" tabindex="-1" role="presentation"></a><span class="cm-keyword">for</span> (<span class="cm-keyword">let</span> <span class="cm-def">node</span> <span class="cm-operator">=</span> <span class="cm-variable">list</span>; <span class="cm-variable">node</span>; <span class="cm-variable">node</span> <span class="cm-operator">=</span> <span class="cm-variable">node</span>.<span class="cm-property">rest</span>) {}</pre>
<p><a class="p_ident" id="p_LnwEAnSmsp" href="#p_LnwEAnSmsp" tabindex="-1" role="presentation"></a>Can you see how that works? Every iteration of the loop, <code>node</code> points to the current sublist, and the body can read its <code>value</code> property to get the current element. At the end of an iteration, <code>node</code> moves to the next sublist. When that is null, we have reached the end of the list, and the loop is finished.</p>
<p><a class="p_ident" id="p_ASUOjWBRh5" href="#p_ASUOjWBRh5" tabindex="-1" role="presentation"></a>The recursive version of <code>nth</code> 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 <code>value</code> property of the node it is looking at. To get the zeroth element of a list, you simply take the <code>value</code> property of its head node. To get element <em>N</em> + 1, you take the <em>N</em>th element of the list that’s in this list’s <code>rest</code> property.</p>
</div></div>
<h3 id="exercise_deep_compare"><a class="i_ident" id="i_IJBU+aXOIC" href="#i_IJBU+aXOIC" tabindex="-1" role="presentation"></a>Deep comparison</h3>
<p><a class="p_ident" id="p_xTwbRlqHNJ" href="#p_xTwbRlqHNJ" tabindex="-1" role="presentation"></a>The <code>==</code> operator compares objects by identity. But sometimes you’d prefer to compare the values of their actual properties.</p>
<p><a class="p_ident" id="p_DwdnLiD0pC" href="#p_DwdnLiD0pC" tabindex="-1" role="presentation"></a>Write a function <code>deepEqual</code> 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 <code>deepEqual</code>.</p>
<p><a class="p_ident" id="p_Znb46HKrMg" href="#p_Znb46HKrMg" tabindex="-1" role="presentation"></a>To find out whether values should be compared directly (use the <code>===</code> operator for that) or have their properties compared, you can use the <code>typeof</code> operator. If it produces <code>"object"</code> for both values, you should do a deep comparison. But you have to take one silly exception into account: because of a historical accident, <code>typeof null</code> also produces <code>"object"</code>.</p>
<p><a class="p_ident" id="p_n9AoXEbeFg" href="#p_n9AoXEbeFg" tabindex="-1" role="presentation"></a>The <code>Object.keys</code> function will be useful when you need to go over the properties of objects to compare them.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_kWPN5i/Y3x" href="#c_kWPN5i/Y3x" tabindex="-1" role="presentation"></a><span class="cm-comment">// Your code here.</span>
<span class="cm-keyword">let</span> <span class="cm-def">obj</span> <span class="cm-operator">=</span> {<span class="cm-property">here</span>: {<span class="cm-property">is</span>: <span class="cm-string">"an"</span>}, <span class="cm-property">object</span>: <span class="cm-number">2</span>};
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">deepEqual</span>(<span class="cm-variable">obj</span>, <span class="cm-variable">obj</span>));
<span class="cm-comment">// → true</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">deepEqual</span>(<span class="cm-variable">obj</span>, {<span class="cm-property">here</span>: <span class="cm-number">1</span>, <span class="cm-property">object</span>: <span class="cm-number">2</span>}));
<span class="cm-comment">// → false</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">deepEqual</span>(<span class="cm-variable">obj</span>, {<span class="cm-property">here</span>: {<span class="cm-property">is</span>: <span class="cm-string">"an"</span>}, <span class="cm-property">object</span>: <span class="cm-number">2</span>}));
<span class="cm-comment">// → true</span></pre>
<div class="solution"><div class="solution-text">
<p><a class="p_ident" id="p_t3z+oosxP9" href="#p_t3z+oosxP9" tabindex="-1" role="presentation"></a>Your test for whether you are dealing with a real object will look something like <code>typeof x == "object" && x != null</code>. Be careful to compare properties only when <em>both</em> arguments are objects. In all other cases you can just immediately return the result of applying <code>===</code>.</p>
<p><a class="p_ident" id="p_csfrgdVrEd" href="#p_csfrgdVrEd" tabindex="-1" role="presentation"></a>Use <code>Object.keys</code> 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.</p>
<p><a class="p_ident" id="p_ECXa1sWg6+" href="#p_ECXa1sWg6+" tabindex="-1" role="presentation"></a>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.</p>
</div></div><nav><a href="03_functions.html" title="previous chapter">◀</a> <a href="index.html" title="cover">◆</a> <a href="05_higher_order.html" title="next chapter">▶</a></nav>
</article>