forked from pandark/eloquent-javascript-translation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
print.html
5495 lines (5247 loc) · 786 KB
/
print.html
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
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/book.css"/>
<link rel="stylesheet" type="text/css" href="css/highlight.css"/>
<link rel="stylesheet" type="text/css" href="css/console.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Version imprimable -- JavaScript Éloquent</title>
</head>
<body>
<div class="content">
<h1><span class="number">Chapitre 1 : </span>Introduction</h1>
<div class="block">
<p>When personal computers were first introduced, most of them came equipped with a simple programming language, usually a variant of <a name="key1"></a>BASIC. Interacting with the computer was closely integrated with this language, and thus every computer-user, whether he wanted to or not, would get a taste of it. Now that computers have become plentiful and cheap, typical users don't get much further than clicking things with a mouse. For most people, this works very well. But for those of
us with a natural inclination towards technological tinkering, the removal of programming from every-day computer use presents something of a barrier.</p>
<p>Fortunately, as an effect of developments in the World Wide Web, it so happens that every computer equipped with a modern web-browser also has an environment for programming JavaScript. In today's spirit of not bothering the user with technical details, it is kept well hidden, but a web-page can make it accessible, and use it as a platform for learning to program.</p>
<p>That is what this (hyper-)book tries to do.</p>
</div><hr/><div class="block">
<blockquote>I do not enlighten those who are not eager to learn, nor arouse those who are not anxious to give an explanation themselves. If I have presented one corner of the square and they cannot come back to me with the other three, I should not go over the points again.
<br/><br/>
― Confucius</blockquote>
<p>Besides explaining JavaScript, this book tries to be an introduction to the basic principles of programming. Programming, it turns out, is hard. The fundamental rules are, most of the time, simple and clear. But programs, while built on top of these basic rules, tend to become complex enough to introduce their own rules, their own complexity. Because of this, programming is rarely simple or predictable. As Donald Knuth, who is something of a founding father of the field, says, it is an <em>art</em>.</p>
<p>To get something out of this book, more than just passive reading is required. Try to stay sharp, make an effort to solve the exercises, and only continue on when you are reasonably sure you understand the material that came before.</p>
</div><hr/><div class="block">
<blockquote>The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs.
<br/><br/>
― Joseph Weizenbaum, <em>Computer Power and Human Reason</em></blockquote>
<p>A program is many things. It is a piece of text typed by a programmer, it is the directing force that makes the computer do what it does, it is data in the computer's memory, yet it controls the actions performed on this same memory. Analogies that try to compare programs to objects we are familiar with tend to fall short, but a superficially fitting one is that of a machine. The gears of a mechanical watch fit together ingeniously, and if the watchmaker was any good, it will accurately show the time for many years. The elements of a program fit together in a similar way, and if the programmer knows what he is doing, the program will run without crashing.</p>
<p>A computer is a machine built to act as a host for these immaterial machines. Computers themselves can only do stupidly straightforward things. The reason they are so useful is that they do these things at an incredibly high speed. A program can, by ingeniously combining many of these simple actions, do very complicated things.</p>
<p>To some of us, writing computer programs is a fascinating game. A program is a building of thought. It is costless to build, weightless, growing easily under our typing hands. If we get carried away, its size and complexity will grow out of control, confusing even the one who created it. This is the main problem of programming. It is why so much of today's software tends to crash, fail, screw up.</p>
<p>When a program works, it is beautiful. The art of programming is the skill of controlling complexity. The great program is subdued, made simple in its complexity.</p>
</div><hr/><div class="block">
<p>Today, many programmers believe that this complexity is best managed by using only a small set of well-understood techniques in their programs. They have composed strict rules about the form programs should have, and the more zealous among them will denounce those who break these rules as <em>bad</em> programmers.</p>
<p>What hostility to the richness of programming! To try to reduce it to something straightforward and predictable, to place a taboo on all the weird and beautiful programs. The landscape of programming techniques is enormous, fascinating in its diversity, still largely unexplored. It is certainly littered with traps and snares, luring the inexperienced programmer into all kinds of horrible mistakes, but that only means you should proceed with caution, keep your wits about you. As you learn, there will always be new challenges, new territory to explore. The programmer who refuses to keep exploring will surely stagnate, forget his joy, lose the will to program (and become a manager).</p>
<p>As far as I am concerned, the definite criterion for a program is whether it is correct. Efficiency, clarity, and size are also important, but how to balance these against each other is always a matter of judgement, a judgement that each programmer must make for himself. Rules of thumb are useful, but one should never be afraid to break them.</p>
</div><hr/><div class="block">
<p>In the beginning, at the birth of computing, there were no programming languages. Programs looked something like this:</p>
<pre class="preformatted">00110001 00000000 00000000
00110001 00000001 00000001
00110011 00000001 00000010
01010001 00001011 00000010
00100010 00000010 00001000
01000011 00000001 00000000
01000001 00000001 00000001
00010000 00000010 00000000
01100010 00000000 00000000</pre>
<p>That is a program to add the numbers from one to ten together, and print out the result (1 + 2 + ... + 10 = 55). It could run on a very simple kind of computer. To program early computers, it was necessary to set large arrays of switches in the right position, or punch holes in strips of cardboard and feed them to the computer. You can imagine how this was a tedious, error-prone procedure. Even the writing of simple programs required much cleverness and discipline, complex ones were nearly inconceivable.</p>
<p>Of course, manually entering these arcane patterns of bits (which is what the 1s and 0s above are generally called) did give the programmer a profound sense of being a mighty wizard. And that has to be worth something, in terms of job satisfaction.</p>
<p>Each line of the program contains a single instruction. It could be written in English like this:</p>
<ol><li>
Store the number 0 in memory location 0
</li><li>
Store the number 1 in memory location 1
</li><li>
Store the value of memory location 1 in memory location 2
</li><li>
Subtract the number 11 from the value in memory location 2
</li><li>
If the value in memory location 2 is the number 0, continue with instruction 9
</li><li>
Add the value of memory location 1 to memory location 0
</li><li>
Add the number 1 to the value of memory location 1
</li><li>
Continue with instruction 3
</li><li>
Output the value of memory location 0
</li></ol>
<p>While that is more readable than the binary soup, it is still rather unpleasant. It might help to use names instead of numbers for the instructions and memory locations:</p>
<pre class="preformatted"> Set 'total' to 0
Set 'count' to 1
[loop]
Set 'compare' to 'count'
Subtract 11 from 'compare'
If 'compare' is zero, continue at [end]
Add 'count' to 'total'
Add 1 to 'count'
Continue at [loop]
[end]
Output 'total'</pre>
<p>At this point it is not too hard to see how the program works. Can you? The first two lines give two memory locations their starting values: <code>total</code> will be used to build up the result of the program, and <code>count</code> keeps track of the number that we are currently looking at. The lines using <code>compare</code> are probably the weirdest ones. What the program wants to do is see if <code>count</code> is equal to 11, in order to decide whether it can stop yet. Because the machine is so primitive, it can only test whether a number is zero, and make a decision (jump) based on that. So it uses the memory location labelled <code>compare</code> to compute the value of <code>count - 11</code>, and makes a decision based on that value. The next two lines add the value of <code>count</code> to the result, and increment <code>count</code> by one every time the program has decided that it is not 11 yet.</p>
<p>Here is the same program in JavaScript:</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">total</span> = <span class="atom">0</span>, <span class="variable">count</span> = <span class="atom">1</span>;
<span class="keyword">while</span> (<span class="variable">count</span> <= <span class="atom">10</span>) {
<span class="variable">total</span> += <span class="variable">count</span>;
<span class="variable">count</span> += <span class="atom">1</span>;
}
<span class="variable">print</span>(<span class="variable">total</span>);</pre>
<p>This gives us a few more improvements. Most importantly, there is no need to specify the way we want the program to jump back and forth anymore. The magic word <code>while</code> takes care of that. It continues executing the lines below it as long as the condition it was given holds: <code>count <= 10</code>, which means '<code>count</code> is less than or equal to <code>10</code>'. Apparently, there is no need anymore to create a temporary value and compare that to zero. This was a stupid little detail, and the power of programming languages is that they take care of stupid little details for us.</p>
<p>Finally, here is what the program could look like if we happened to have the convenient operations <code>range</code> and <code>sum</code> available, which respectively create a collection of numbers within a range and compute the sum of a collection of numbers:</p>
<pre class="code"><span class="variable">print</span>(<span class="variable">sum</span>(<span class="variable">range</span>(<span class="atom">1</span>, <span class="atom">10</span>)));</pre>
<p>The moral of this story, then, is that the same program can be expressed in long and short, unreadable and readable ways. The first version of the program was extremely obscure, while this last one is almost English: <code>print</code> the <code>sum</code> of the <code>range</code> of numbers from <code>1</code> to <code>10</code>. (We will see in later chapters how to build things like <code>sum</code> and <code>range</code>.)</p>
<p>A good programming language helps the programmer by providing a more abstract way to express himself. It hides uninteresting details, provides convenient building blocks (such as the <code>while</code> construct), and, most of the time, allows the programmer to add building blocks himself (such as the <code>sum</code> and <code>range</code> operations).</p>
</div><hr/><div class="block">
<p>JavaScript is the language that is, at the moment, mostly being used to do all kinds of clever and horrible things with pages on the World Wide Web. Some <a href="http://steve-yegge.blogspot.com/2007/02/next-big-language.html">people</a> claim that the next version of JavaScript will become an important language for other tasks too. I am unsure whether that will happen, but if you are interested in programming, JavaScript is definitely a useful language to learn. Even if you do not end up doing much web programming, the mind-bending programs I will show you in this book will always stay with you, haunt you, and influence the programs you write in other languages.</p>
<p>There are those who will say <em>terrible</em> things about JavaScript. Many of these things are true. When I was for the first time required to write something in JavaScript, I quickly came to despise the language. It would accept almost anything I typed, but interpret it in a way that was completely different from what I meant. This had a lot to do with the fact that I did not have a clue what I was doing, but there is also a real issue here: JavaScript is ridiculously liberal in what it allows. The idea behind this design was that it would make programming in JavaScript easier for beginners. In actuality, it mostly makes finding problems in your programs harder, because the system will not point them out to you.</p>
<p>However, the flexibility of the language is also an advantage. It leaves space for a lot of techniques that are impossible in more rigid languages, and it can be used to overcome some of JavaScript's shortcomings. After learning it properly, and working with it for a while, I have really learned to <em>like</em> this language.</p>
</div><hr/><div class="block">
<p>Contrary to what the name suggests, JavaScript has very little to do with the programming language named Java. The similar name was inspired by marketing considerations, rather than good judgement. In 1995, when JavaScript was introduced by Netscape, the Java language was being heavily marketed and gaining in popularity. Apparently, someone thought it a good idea to try and ride along on this marketing. Now we are stuck with the name.</p>
<p>Related to JavaScript is a thing called ECMAScript. When browsers other than Netscape started to support JavaScript, or something that looked like it, a document was written to describe precisely how the language should work. The language described in this document is called ECMAScript, after the organisation that standardised it.</p>
<p>ECMAScript describes a general-purpose programming language, and does not say anything about the integration of this language in an Internet browser. JavaScript is ECMAScript plus extra tools for dealing with Internet pages and browser windows.</p>
<p>A few other pieces of software use the language described in the ECMAScript document. Most importantly, the ActionScript language used by Flash is based on ECMAScript (though it does not precisely follow the standard). Flash is a system for adding things that move and make lots of noise to web-pages. Knowing JavaScript won't hurt if you ever find yourself learning to build Flash movies.</p>
<p>JavaScript is still evolving. Since this book came out, ECMAScript 5 has been released, which is compatible with the version described here, but adds some of the functionality we will be writing ourselves as built-in methods. The newest generation of browsers provides this expanded version of JavaScript. As of 2011, 'ECMAScript harmony', a more radical extension of the language, is in the process of being standardised. You should not worry too much about these new versions making the things you learn from this book obsolete. For one thing, they will be an extension of the language we have now, so almost everything written in this book will still hold.</p>
</div><hr/><div class="block">
<p>Most chapters in this book contain quite a lot of code<a class="footref" href="#footnote1">1</a>. In my experience, reading and writing code is an important part of learning to program. Try to not just glance over these examples, but read them attentively and understand them. This can be slow and confusing at first, but you will quickly get the hang of it. The same goes for the exercises. Don't assume you understand them until you've actually written a working solution.</p>
<p>Because of the way the web works, it is always possible to look at the JavaScript programs that people put in their web-pages. This can be a good way to learn how some things are done. Because most web programmers are not 'professional' programmers, or consider JavaScript programming so uninteresting that they never properly learned it, a lot of the code you can find like this is of a <em>very</em> bad quality. When learning from ugly or incorrect code, the ugliness and confusion will propagate into your own code, so be careful who you learn from.</p>
</div><hr/><div class="block">
<p>To allow you to try out programs, both the examples and the code you write yourself, this book makes use of something called a <a name="key2"></a>console. If you are using a modern graphical browser (Internet Explorer version 6 or higher, Firefox 1.5 or higher, Opera 9 or higher, Safari 3 or higher), the pages in this book will show a bar at the bottom of your screen. You can open the console by clicking on the little arrow on the far right of this bar.</p>
<p>The console contains three important elements. There is the output window, which is used to show error messages and things that programs print out. Below that, there is a line where you can type in a piece of JavaScript. Try typing in a number, and pressing the enter key to run what you typed. If the text you typed produced something meaningful, it will be shown in the output window. Now try typing <code>wrong!</code>, and press enter again. The output window will show an error message. You can use the arrow-up and arrow-down keys to go back to previous commands that you typed.</p>
<p>For bigger pieces of code, those that span multiple lines and which you want to keep around for a while, the field on the right can be used. The 'Run' button is used to execute programs written in this field. It is possible to have multiple programs open at the same time. Use the 'New' and 'Load' buttons to add a new program (empty or from a file on the web). When there is more than one open program, the menu next to the 'Run' button can be used to choose which one is being shown. The 'Close' button, as you might expect, closes a program.</p>
<p>Example programs in this book always have a small button with an arrow in their top-right corner, which can be used to run them. The example we saw earlier looked like this:</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">total</span> = <span class="atom">0</span>, <span class="variable">count</span> = <span class="atom">1</span>;
<span class="keyword">while</span> (<span class="variable">count</span> <= <span class="atom">10</span>) {
<span class="variable">total</span> += <span class="variable">count</span>;
<span class="variable">count</span> += <span class="atom">1</span>;
}
<span class="variable">print</span>(<span class="variable">total</span>);</pre>
<p>Run it by clicking the arrow. There is also another button, which is used to load the program into the console. Do not hesitate to modify it and try out the result. The worst that could happen is that you create an endless loop. An endless loop is what you get when the condition of the <code>while</code> never becomes false, for example if you choose to add <code>0</code> instead of <code>1</code> to the count variable. Now the program will run forever.</p>
<p>Fortunately, browsers keep an eye on the programs running inside them. Whenever one of them is taking suspiciously long to finish, they will ask you if you want to cut it off.</p>
</div><hr/><div class="block">
<p>In some later chapters, we will build example programs that consist of many blocks of code. Often, you have to run every one of them for the program to work. As you may have noticed, the arrow in a block of code turns purple after the block has been run. When reading a chapter, try to run every block of code you come across, especially those that 'define' something new (you will see what that means in the next chapter).</p>
<p>It is, of course, possible that you can not read a chapter in one sitting. This means you will have to start halfway when you continue reading, but if you don't run all the code starting from the top of the chapter, some things might not work. By holding the shift key while pressing the 'run' arrow on a block of code, all blocks before that one will be run as well, so when you start in the middle of a chapter, hold shift the first time you run a piece of code, and everything should work as expected.</p>
</div><hr/><div class="block">
<p>Finally, the little face in the top-left corner of your screen can be used to send me, the author, a message. If you have a comment, or you find a passage ridiculously confusing, or you just spot a spelling error, tell me about it. Sending a message can be done without leaving the page, so it won't interrupt your reading.</p>
</div>
<ol class="footnotes"><li>
<a name="footnote1"></a>
'Code' is the substance that programs are made of. Every piece of a program, whether it is a single line or the whole thing, can be referred to as 'code'.
</li></ol>
<h1><span class="number">Chapitre 2 : </span>Les bases du JavaScript : valeurs, variables et structures de contrôle</h1>
<div class="block">
<p>Inside the computer's world, there is only data. That which is not data, does not exist. Although all data is in essence just a sequence of bits<a class="footref" href="#footnote1">1</a>, and is thus fundamentally alike, every piece of data plays its own role. In JavaScript's system, most of this data is neatly separated into things called <a name="key1"></a>values. Every value has a type, which determines the kind of role it can play. There are six basic types of values: Numbers, strings, booleans, objects, functions, and undefined values.</p>
<p>To create a value, one must merely invoke its name. This is very convenient. You don't have to gather building material for your values, or pay for them, you just call for one and <em>woosh</em>, you have it. They are not created from thin air, of course. Every value has to be stored somewhere, and if you want to use a gigantic number of them at the same time you might run out of computer memory. Fortunately, this is only a problem if you need them all simultaneously. As soon as you no longer use a value, it will dissipate, leaving behind only a few bits. These bits are recycled to make the next generation of values.</p>
</div><hr/><div class="block">
<p>Values of the type <a name="key2"></a>number are, as you might have deduced, numeric values. They are written the way numbers are usually written:</p>
<pre class="code expression"><span class="atom">144</span></pre>
<p>Enter that in the console, and the same thing is printed in the output window. The text you typed in gave rise to a number value, and the console took this number and wrote it out to the screen again. In a case like this, that was a rather pointless exercise, but soon we will be producing values in less straightforward ways, and it can be useful to 'try them out' on the console to see what they produce.</p>
<p>This is what <code>144</code> looks like in bits<a class="footref" href="#footnote2">2</a>:</p>
<pre class="preformatted">0100000001100010000000000000000000000000000000000000000000000000</pre>
<p>The number above has 64 bits. Numbers in JavaScript always do. This has one important repercussion: There is a limited amount of different numbers that can be expressed. With three decimal digits, only the numbers 0 to 999 can be written, which is 10<span class="exponent">3</span> = 1000 different numbers. With 64 binary digits, 2<span class="exponent">64</span> different numbers can be written. This is a lot, more than 10<span class="exponent">19</span> (a one with nineteen zeroes).</p>
<p>Not all whole numbers below 10<span class="exponent">19</span> fit in a JavaScript number though. For one, there are also negative numbers, so one of the bits has to be used to store the sign of the number. A bigger issue is that non-whole numbers must also be represented. To do this, 11 bits are used to store the position of the fractional dot within the number.</p>
<p>That leaves 52 bits<a class="footref" href="#footnote3">3</a>. Any whole number less than 2<span class="exponent">52</span>, which is over 10<span class="exponent">15</span>, will safely fit in a JavaScript number. In most cases, the numbers we are using stay well below that, so we do not have to concern ourselves with bits at all. Which is good. I have nothing in particular against bits, but you <em>do</em> need a terrible lot of them to get anything done. When at all possible, it is more pleasant to deal with bigger things.</p>
<p>Fractional numbers are written by using a dot.</p>
<pre class="code expression"><span class="atom">9.81</span></pre>
<p>For very big or very small numbers, one can also use 'scientific' notation by adding an <code>e</code>, followed by the exponent of the number:</p>
<pre class="code expression"><span class="atom">2.998e8</span></pre>
<p>Which is 2.998 * 10<span class="exponent">8</span> = 299800000.</p>
<p>Calculations with whole numbers (also called integers) that fit in 52 bits are guaranteed to always be precise. Unfortunately, calculations with fractional numbers are generally not. Like π (pi) can not be precisely expressed by a finite amount of decimal digits, many numbers lose some precision when only 64 bits are available to store them. This is a shame, but it only causes practical problems in very specific situations. The important thing is to be aware of it, and treat fractional digital numbers as approximations, not as precise values.</p>
</div><hr/><div class="block">
<p>The main thing to do with numbers is arithmetic. Arithmetic operations such as addition or multiplication take two number values and produce a new number from them. Here is what they look like in JavaScript:</p>
<pre class="code expression"><span class="atom">100</span> + <span class="atom">4</span> * <span class="atom">11</span></pre>
<p>The <a name="key3"></a><code>+</code> and <a name="key4"></a><code>*</code> symbols are called operators. The first stands for addition, and the second for multiplication. Putting an operator between two values will <a name="key5"></a>apply it to those values, and produce a new value.</p>
<p>Does the example mean 'add 4 and 100, and multiply the result by 11', or is the multiplication done before the adding? As you might have guessed, the multiplication happens first. But, as in mathematics, this can be changed by wrapping the addition in parentheses<a name="key6"></a>:</p>
<pre class="code expression">(<span class="atom">100</span> + <span class="atom">4</span>) * <span class="atom">11</span></pre>
<p>For subtraction, there is the <a name="key7"></a><code>-</code> operator, and division can be done with <a name="key8"></a><code>/</code>. When operators appear together without parentheses, the order in which they are applied is determined by the <a name="key9"></a>precedence of the operators. The first example shows that multiplication has a higher precedence than addition. Division and multiplication always come before subtraction and addition. When multiple operators with the same precedence appear next to each other (<code>1 - 1 + 1</code>) they are applied left-to-right.</p>
<p>Try to figure out what value this produces, and then run it to see if you were correct...</p>
<pre class="code expression"><span class="atom">115</span> * <span class="atom">4</span> - <span class="atom">4</span> + <span class="atom">88</span> / <span class="atom">2</span></pre>
<p>These rules of precedence are not something you should worry about. When in doubt, just add parentheses.</p>
<p>There is one more arithmetic operator which is probably less familiar to you. The <a name="key10"></a><code>%</code> symbol is used to represent the <a name="key11"></a>modulo operation. <code>X</code> modulo <code>Y</code> is the remainder of dividing <code>X</code> by <code>Y</code>. For example <code>314 % 100</code> is <code>14</code>, <code>10 % 3</code> is <code>1</code>, and <code>144 % 12</code> is <code>0</code>. Modulo has the same precedence as multiplication and division.</p>
</div><hr/><div class="block">
<p>The next data type is the <a name="key12"></a>string. Its use is not as evident from its name as with numbers, but it also fulfills a very basic role. Strings are used to represent text, the name supposedly derives from the fact that it strings together a bunch of characters. Strings are written by enclosing their content in quotes:</p>
<pre class="code expression"><span class="string">"Patch my boat with chewing gum."</span></pre>
<p>Almost anything can be put between double quotes, and JavaScript will make a string value out of it. But a few characters are tricky. You can imagine how putting quotes between quotes might be hard. Newlines, <a name="key13"></a>the things you get when you press enter, can also not be put between quotes, the string has to stay on a single line.</p>
<p>To be able to have such characters in a string, the following trick is used: Whenever a backslash ('<code>\</code>') is found inside quoted text, it indicates that the character after it has a special meaning. A quote that is preceded by a backslash will not end the string, but be part of it. When an '<code>n</code>' character occurs after a backslash, it is interpreted as a newline. Similarly, a '<code>t</code>' after a backslash means a tab character<a class="footref" href="#footnote4">4</a>.</p>
<pre class="code expression"><span class="string">"This is the first line\nAnd this is the second"</span></pre>
<p>There are of course situations where you want a backslash in a string to be just a backslash, not a special code. If two backslashes follow each other, they will collapse right into each other, and only one will be left in the resulting string value:</p>
<pre class="code expression"><span class="string">"A newline character is written like \"\\n\"."</span></pre>
</div><hr/><div class="block">
<p>Strings can not be divided, multiplied, or subtracted. The <a name="key14"></a><code>+</code> operator <em>can</em> be used on them. It does not add, but it concatenates, it glues two strings together.</p>
<pre class="code expression"><span class="string">"con"</span> + <span class="string">"cat"</span> + <span class="string">"e"</span> + <span class="string">"nate"</span></pre>
<p>There are more ways of manipulating strings, but these are discussed later.</p>
</div><hr/><div class="block">
<p>Not all operators are symbols, some are written as words. For example, the <a name="key15"></a><code>typeof</code> operator, which produces a string value naming the type of the value you give it.</p>
<pre class="code expression">typeof <span class="atom">4.5</span></pre>
<p>The other operators we saw all operated on two values, <code>typeof</code> takes only one. Operators that use two values are called <a name="key16"></a>binary operators, while those that take one are called <a name="key17"></a>unary operators. The <a name="key18"></a>minus operator can be used both as a binary and a unary operator:</p>
<pre class="code expression">- (<span class="atom">10</span> - <span class="atom">2</span>)</pre>
</div><hr/><div class="block">
<p>Then there are values of the <a name="key19"></a>boolean type. There are only two of these: <a name="key20"></a><code>true</code> and <a name="key21"></a><code>false</code>. Here is one way to produce a <code>true</code> value:</p>
<pre class="code expression"><span class="atom">3</span> > <span class="atom">2</span></pre>
<p>And <code>false</code> can be produced like this:</p>
<pre class="code expression"><span class="atom">3</span> < <span class="atom">2</span></pre>
<p>I hope you have seen the <a name="key22"></a><code>></code> and <a name="key23"></a><code><</code> signs before. They mean, respectively, 'is greater than' and 'is less than'. They are binary operators, and the result of applying them is a boolean value that indicates whether they hold in this case.</p>
<p>Strings can be compared in the same way:</p>
<pre class="code expression"><span class="string">"Aardvark"</span> < <span class="string">"Zoroaster"</span></pre>
<p>The way strings are ordered is more or less alphabetic. More or less... Uppercase letters are always 'less' than lowercase ones, so <code>"Z" < "a"</code> (upper-case Z, lower-case a) is <code>true</code>, and non-alphabetic characters ('<code>!</code>', '<code>@</code>', etc) are also included in the ordering. The actual way in which the comparison is done is based on the <a name="key24"></a>Unicode standard. This standard assigns a number to virtually every character one would ever need, including characters from Greek, Arabic, Japanese, Tamil, and so on. Having such numbers is practical for storing strings inside a computer ― you can represent them as a list of numbers. When comparing strings, JavaScript just compares the numbers of the characters inside the string, from left to right.</p>
<p>Other similar operators are <a name="key25"></a><code>>=</code> ('is greater than or equal to'), <a name="key26"></a><code><=</code> (is less than or equal to), <a name="key27"></a><code>==</code> ('is equal to'), and <a name="key28"></a><code>!=</code> ('is not equal to').</p>
<pre class="code expression"><span class="string">"Itchy"</span> != <span class="string">"Scratchy"</span></pre>
<pre class="code expression"><span class="atom">5e2</span> == <span class="atom">500</span></pre>
</div><hr/><div class="block">
<p>There are also some useful operations that can be applied to boolean values themselves. JavaScript supports three logical operators: <em>and</em>, <em>or</em>, and <em>not</em>. These can be used to 'reason' about booleans.</p>
<p>The <a name="key29"></a><code>&&</code> operator represents logical <em>and</em>. It is a binary operator, and its result is only <code>true</code> if both of the values given to it are <code>true</code>.</p>
<pre class="code expression"><span class="atom">true</span> && <span class="atom">false</span></pre>
<p><a name="key30"></a><code>||</code> is the logical <em>or</em>, it is <code>true</code> if either of the values given to it is <code>true</code>:</p>
<pre class="code expression"><span class="atom">true</span> || <span class="atom">false</span></pre>
<p><em>Not</em> is written as an exclamation mark, <a name="key31"></a><code>!</code>, it is a unary operator that flips the value given to it, <code>!true</code> is <code>false</code>, and <code>!false</code> is <code>true</code>.</p>
</div><hr/><div class="block">
<a name="exercise1"></a>
<div class="exercisenum">Ex. 2.1</div>
<div class="exercise">
<pre class="code expression">((<span class="atom">4</span> >= <span class="atom">6</span>) || (<span class="string">"grass"</span> != <span class="string">"green"</span>)) &&
!(((<span class="atom">12</span> * <span class="atom">2</span>) == <span class="atom">144</span>) && <span class="atom">true</span>)</pre>
<p>Is this true? For readability, there are a lot of unnecessary parentheses in there. This simple version means the same thing:</p>
<pre class="code expression">(<span class="atom">4</span> >= <span class="atom">6</span> || <span class="string">"grass"</span> != <span class="string">"green"</span>) &&
!(<span class="atom">12</span> * <span class="atom">2</span> == <span class="atom">144</span> && <span class="atom">true</span>)</pre>
</div>
<div class="solution">
<p>Yes, it is <code>true</code>. You can reduce it step by step like this:</p>
<pre class="code expression">(<span class="atom">false</span> || <span class="atom">true</span>) && !(<span class="atom">false</span> && <span class="atom">true</span>)</pre>
<pre class="code expression"><span class="atom">true</span> && !<span class="atom">false</span></pre>
<pre class="code expression"><span class="atom">true</span></pre>
<p>I hope you noticed that <code>"grass" != "green"</code> is <code>true</code>. Grass may be green, but it is not equal to green.</p>
</div>
</div><hr/><div class="block">
<p>It is not always obvious when parentheses are needed. In practice, one can usually get by with knowing that of the operators we have seen so far, <code>||</code> has the lowest precedence, then comes <code>&&</code>, then the comparison operators (<code>></code>, <code>==</code>, etcetera), and then the rest. This has been chosen in such a way that, in simple cases, as few parentheses as possible are necessary.</p>
</div><hr/><div class="block">
<p>All the examples so far have used the language like you would use a pocket calculator. Make some values and apply operators to them to get new values. Creating values like this is an essential part of every JavaScript program, but it is only a part. A piece of code that produces a value is called an <a name="key32"></a>expression. Every value that is written directly (such as <code>22</code> or <code>"psychoanalysis"</code>) is an expression. An expression between parentheses is also an expression. And a binary operator applied to two expressions, or a unary operator applied to one, is also an expression.</p>
<p>There are a few more ways of building expressions, which will be revealed when the time is ripe.</p>
<p>There exists a unit that is bigger than an expression. It is called a <a name="key33"></a>statement. A program is built as a list of statements. Most statements end with a <a name="key34"></a>semicolon (<code>;</code>). The simplest kind of statement is an expression with a semicolon after it. This is a program:</p>
<pre class="code"><span class="atom">1</span>;
!<span class="atom">false</span>;</pre>
<p>It is a useless program. An expression can be content to just produce a value, but a statement only amounts to something if it somehow changes the world. It could print something to the screen ― that counts as changing the world ― or it could change the internal state of the program in a way that will affect the statements that come after it. These changes are called '<a name="key35"></a>side effects'. The statements in the example above just produce the values <code>1</code> and <code>true</code>, and then immediately throw them into the bit bucket<a class="footref" href="#footnote5">5</a>. This leaves no impression on the world at all, and is not a side effect.</p>
</div><hr/><div class="block">
<p>How does a program keep an internal state? How does it remember things? We have seen how to produce new values from old values, but this does not change the old values, and the new value has to be immediately used or it will dissipate again. To catch and hold values, JavaScript provides a thing called a <a name="key36"></a>variable.</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">caught</span> = <span class="atom">5</span> * <span class="atom">5</span>;</pre>
<p>A variable always has a name, and it can point at a value, holding on to it. The statement above creates a variable called <code>caught</code> and uses it to grab hold of the number that is produced by multiplying <code>5</code> by <code>5</code>.</p>
<p>After running the above program, you can type the word <code>caught</code> into the console, and it will retrieve the value <code>25</code> for you. The name of a variable is used to fetch its value. <code>caught + 1</code> also works. A variable name can be used as an expression, and thus can be part of bigger expressions.</p>
<p>The word <a name="key37"></a><code>var</code> is used to create a new variable. After <code>var</code>, the name of the variable follows. Variable names can be almost every word, but they may not include spaces. Digits can be part of variable names, <code>catch22</code> is a valid name, but the name must not start with one. The characters '<code>$</code>' and '<code>_</code>' can be used in names as if they were letters, so <code>$_$</code> is a correct variable name.</p>
<p>If you want the new variable to immediately capture a value, which is often the case, the <a name="key38"></a><code>=</code> operator can be used to give it the value of some expression.</p>
<p>When a variable points at a value, that does not mean it is tied to that value forever. At any time, the <code>=</code> operator can be used on existing variables to yank them away from their current value and make them point to a new one.</p>
<pre class="code"><span class="variable">caught</span> = <span class="atom">4</span> * <span class="atom">4</span>;</pre>
</div><hr/><div class="block">
<p>You should imagine variables as tentacles, rather than boxes. They do not <em>contain</em> values, they <em>grasp</em> them ― two variables can refer to the same value. Only the values that the program still has a hold on can be accessed by it. When you need to remember something, you grow a tentacle to hold on to it, or re-attach one of your existing tentacles to a new value: To remember the amount of dollars that Luigi still owes you, you could do...</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">luigiDebt</span> = <span class="atom">140</span>;</pre>
<p>Then, every time Luigi pays something back, this amount can be decremented by giving the variable a new number:</p>
<pre class="code"><span class="variable">luigiDebt</span> = <span class="variable">luigiDebt</span> - <span class="atom">35</span>;</pre>
<p>The collection of variables and their values that exist at a given time is called the <a name="key39"></a>environment. When a program starts up, this environment is not empty. It always contains a number of standard variables. When your browser loads a page, it creates a new environment and attaches these standard values to it. The variables created and modified by programs on that page survive until the browser goes to a new page.</p>
</div><hr/><div class="block">
<p>A lot of the values provided by the standard environment have the type '<a name="key40"></a>function'. A function is a piece of program wrapped in a value. Generally, this piece of program does something useful, which can be evoked using the function value that contains it. In a browser environment, the variable <a name="key41"></a><code>alert</code> holds a function that shows a little dialog window with a message. It is used like this:</p>
<pre class="code"><span class="variable">alert</span>(<span class="string">"Also, your hair is on fire."</span>);</pre>
<p><a name="key42"></a>Executing the code in a function is called <a name="key43"></a>invoking or <a name="key44"></a>applying it. The notation for doing this uses parentheses. Every expression that produces a function value can be invoked by putting parentheses after it. The string value between the parentheses is given to the function, which uses it as the text to show in the dialog window. Values given to functions are called <a name="key45"></a>parameters or <a name="key46"></a>arguments. <code>alert</code> needs only one of them, but other functions might need a different number.</p>
</div><hr/><div class="block">
<p>Showing a dialog window is a side effect. A lot of functions are useful because of the side effects they produce. It is also possible for a function to produce a value, in which case it does not need to have a side effect to be useful. For example, there is a function <a name="key47"></a><code>Math.max</code>, which takes two arguments and gives back the biggest of the two:</p>
<pre class="code"><span class="variable">alert</span>(<span class="variable">Math</span>.<span class="property">max</span>(<span class="atom">2</span>, <span class="atom">4</span>));</pre>
<p><a name="key48"></a>When a function produces a value, it is said to <a name="key49"></a>return it. Because things that produce values are always expressions in JavaScript, function calls can be used as a part of bigger expressions:</p>
<pre class="code"><span class="variable">alert</span>(<span class="variable">Math</span>.<span class="property">min</span>(<span class="atom">2</span>, <span class="atom">4</span>) + <span class="atom">100</span>);</pre>
<p><a href="chapter3.html">Chapter 3</a> discusses writing your own functions.</p>
</div><hr/><div class="block">
<p>As the previous examples show, <code>alert</code> can be useful for showing the result of some expression. Clicking away all those little windows can get on one's nerves though, so from now on we will prefer to use a similar function, called <a name="key50"></a><code>print</code>, which does not pop up a window, but just writes a value to the output area of the console. <code>print</code> is not a standard JavaScript function, browsers do not provide it for you, but it is made available by this book, so you can use it on these pages.</p>
<pre class="code"><span class="variable">print</span>(<span class="string">"N"</span>);</pre>
<p>A similar function, also provided on these pages, is <code>show</code>. While <code>print</code> will display its argument as flat text, <a name="key51"></a><code>show</code> tries to display it the way it would look in a program, which can give more information about the type of the value. For example, string values keep their quotes when given to <code>show</code>:</p>
<pre class="code"><span class="variable">show</span>(<span class="string">"N"</span>);</pre>
<p>The standard environment provided by browsers contains a few more functions for popping up windows. You can ask the user an OK/Cancel question using <a name="key52"></a><code>confirm</code>. This returns a boolean, <code>true</code> if the user presses 'OK', and <code>false</code> if he presses 'Cancel'.</p>
<pre class="code"><span class="variable">show</span>(<span class="variable">confirm</span>(<span class="string">"Shall we, then?"</span>));</pre>
<p><a name="key53"></a><code>prompt</code> can be used to ask an 'open' question. The first argument is the question, the second one is the text that the user starts with. A line of text can be typed into the window, and the function will return this as a string.</p>
<pre class="code"><span class="variable">show</span>(<span class="variable">prompt</span>(<span class="string">"Tell us everything you know."</span>, <span class="string">"..."</span>));</pre>
</div><hr/><div class="block">
<p>It is possible to give almost every variable in the environment a new value. This can be useful, but also dangerous. If you give <code>print</code> the value <code>8</code>, you won't be able to print things anymore. Fortunately, there is a big 'Reset' button on the console, which will reset the environment to its original state.</p>
</div><hr/><div class="block">
<p>One-line programs are not very interesting. When you put more than one statement into a program, the statements are, predictably, executed one at a time, from top to bottom.</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">theNumber</span> = <span class="variable">Number</span>(<span class="variable">prompt</span>(<span class="string">"Pick a number"</span>, <span class="string">""</span>));
<span class="variable">print</span>(<span class="string">"Your number is the square root of "</span> +
(<span class="variable">theNumber</span> * <span class="variable">theNumber</span>));</pre>
<p>The function <a name="key54"></a><code>Number</code> converts a value to a number, which is needed in this case because the result of <code>prompt</code> is a string value. There are similar functions called <a name="key55"></a><code>String</code> and <a name="key56"></a><code>Boolean</code> which convert values to those types.</p>
</div><hr/><div class="block">
<p>Consider a program that prints out all even numbers from 0 to 12. One way to write this is:</p>
<pre class="code"><span class="variable">print</span>(<span class="atom">0</span>);
<span class="variable">print</span>(<span class="atom">2</span>);
<span class="variable">print</span>(<span class="atom">4</span>);
<span class="variable">print</span>(<span class="atom">6</span>);
<span class="variable">print</span>(<span class="atom">8</span>);
<span class="variable">print</span>(<span class="atom">10</span>);
<span class="variable">print</span>(<span class="atom">12</span>);</pre>
<p>That works, but the idea of writing a program is to make something <em>less</em> work, not more. If we needed all even numbers below 1000, the above would be unworkable. What we need is a way to automatically repeat some code.</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">currentNumber</span> = <span class="atom">0</span>;
<span class="keyword">while</span> (<span class="variable">currentNumber</span> <= <span class="atom">12</span>) {
<span class="variable">print</span>(<span class="variable">currentNumber</span>);
<span class="variable">currentNumber</span> = <span class="variable">currentNumber</span> + <span class="atom">2</span>;
}</pre>
<p>You may have seen <a name="key57"></a><code>while</code> in the introduction chapter. A statement starting with the word <code>while</code> creates a <a name="key58"></a>loop. A loop is a disturbance in the sequence of statements, it may cause the program to repeat some statements multiple times. In this case, the word <code>while</code> is followed by an expression in parentheses (the parentheses are compulsory here), which is used to determine whether the loop will loop or finish. As long as the boolean value produced by this expression is <code>true</code>, the code in the loop is repeated. As soon as it is false, the program goes to the bottom of the loop and continues as normal.</p>
<p>The variable <code>currentNumber</code> demonstrates the way a variable can track the progress of a program. Every time the loop repeats, it is incremented by <code>2</code>, and at the beginning of every repetition, it is compared with the number <code>12</code> to decide whether to keep on looping.</p>
<p>The third part of a <code>while</code> statement is another statement. This is the <a name="key59"></a>body of the loop, the action or actions that must take place multiple times. If we did not have to print the numbers, the program could have been:</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">currentNumber</span> = <span class="atom">0</span>;
<span class="keyword">while</span> (<span class="variable">currentNumber</span> <= <span class="atom">12</span>)
<span class="variable">currentNumber</span> = <span class="variable">currentNumber</span> + <span class="atom">2</span>;</pre>
<p>Here, <code>currentNumber = currentNumber + 2;</code> is the statement that forms the body of the loop. We must also print the number, though, so the loop statement must consist of more than one statement. <a name="key60"></a>Braces (<code>{</code> and <code>}</code>) are used to group statements into <a name="key61"></a>blocks. To the world outside the block, a block counts as a single statement. In the earlier example, this is used to include in the loop both the call to <code>print</code> and the statement that updates <code>currentNumber</code>.</p>
</div><hr/><div class="block">
<a name="exercise2"></a>
<div class="exercisenum">Ex. 2.2</div>
<div class="exercise">
<p>Use the techniques shown so far to write a program that calculates and shows the value of 2<span class="exponent">10</span> (2 to the 10th power). You are, obviously, not allowed to use a cheap trick like just writing <code>2 * 2 * ...</code>.</p>
<p>If you are having trouble with this, try to see it in terms of the even-numbers example. The program must perform an action a certain amount of times. A counter variable with a <code>while</code> loop can be used for that. Instead of printing the counter, the program must multiply something by 2. This something should be another variable, in which the result value is built up.</p>
<p>Don't worry if you don't quite see how this would work yet. Even if you perfectly understand all the techniques this chapter covers, it can be hard to apply them to a specific problem. Reading and writing code will help develop a feeling for this, so study the solution, and try the next exercise.</p>
</div>
<div class="solution">
<pre class="code"><span class="keyword">var</span> <span class="variable">result</span> = <span class="atom">1</span>;
<span class="keyword">var</span> <span class="variable">counter</span> = <span class="atom">0</span>;
<span class="keyword">while</span> (<span class="variable">counter</span> < <span class="atom">10</span>) {
<span class="variable">result</span> = <span class="variable">result</span> * <span class="atom">2</span>;
<span class="variable">counter</span> = <span class="variable">counter</span> + <span class="atom">1</span>;
}
<span class="variable">show</span>(<span class="variable">result</span>);</pre>
<p>The counter could also start at <code>1</code> and check for <code><= 10</code>, but, for reasons that will become apparent later on, it is a good idea to get used to counting from 0.</p>
<p>Obviously, your own solutions aren't required to be precisely the same as mine. They should work. And if they are very different, make sure you also understand my solution.</p>
</div>
</div><hr/><div class="block">
<a name="exercise3"></a>
<div class="exercisenum">Ex. 2.3</div>
<div class="exercise">
<p>With some slight modifications, the solution to the previous exercise can be made to draw a triangle. And when I say 'draw a triangle' I mean 'print out some text that almost looks like a triangle when you squint'.</p>
<p>Print out ten lines. On the first line there is one '#' character. On the second there are two. And so on.</p>
<p>How does one get a string with X '#' characters in it? One way is to build it every time it is needed with an 'inner loop' ― a loop inside a loop. A simpler way is to reuse the string that the previous iteration of the loop used, and add one character to it.</p>
</div>
<div class="solution">
<pre class="code"><span class="keyword">var</span> <span class="variable">line</span> = <span class="string">""</span>;
<span class="keyword">var</span> <span class="variable">counter</span> = <span class="atom">0</span>;
<span class="keyword">while</span> (<span class="variable">counter</span> < <span class="atom">10</span>) {
<span class="variable">line</span> = <span class="variable">line</span> + <span class="string">"#"</span>;
<span class="variable">print</span>(<span class="variable">line</span>);
<span class="variable">counter</span> = <span class="variable">counter</span> + <span class="atom">1</span>;
}</pre>
</div>
</div><hr/><div class="block">
<p>You will have noticed the spaces I put in front of some statements. These are not required: The computer will accept the program just fine without them. In fact, even the line breaks in programs are optional. You could write them as a single long line if you felt like it. The role of the <a name="key62"></a>indentation inside blocks is to make the structure of the code clearer to a reader. Because new blocks can be opened inside other blocks, it can become hard to see where one block ends and another begins in a complex piece of code. When lines are indented, the visual shape of a program corresponds to the shape of the blocks inside it. I like to use two spaces for every open block, but tastes differ.</p>
<p>On browsers other than Opera, the field in the console where you can type programs will help you by automatically adding these spaces. This may seem annoying at first, but when you write a lot of code it becomes a huge time-saver. Pressing the tab key will re-indent the line your cursor is currently on.</p>
<p>In some cases, JavaScript allows you to omit the semicolon at the end of a statement. In other cases, it has to be there or strange things will happen. The rules for when it can be safely omitted are complex and weird. In this book, I won't leave out any semicolons, and I strongly urge you to do the same in your own programs.</p>
</div><hr/><div class="block">
<p>The uses of <code>while</code> we have seen so far all show the same pattern. First, a 'counter' variable is created. This variable tracks the progress of the loop. The <code>while</code> itself contains a check, usually to see whether the counter has reached some boundary yet. Then, at the end of the loop body, the counter is updated.</p>
<p>A lot of loops fall into this pattern. For this reason, JavaScript, and similar languages, also provide a slightly shorter and more comprehensive form:</p>
<pre class="code"><span class="keyword">for</span> (<span class="keyword">var</span> <span class="variable">number</span> = <span class="atom">0</span>; <span class="variable">number</span> <= <span class="atom">12</span>; <span class="variable">number</span> = <span class="variable">number</span> + <span class="atom">2</span>)
<span class="variable">show</span>(<span class="variable">number</span>);</pre>
<p>This program is exactly equivalent to the earlier even-number-printing example. The only change is that all the statements that are related to the 'state' of the loop are now on one line. The parentheses after the <a name="key63"></a><code>for</code> should contain two semicolons. The part before the first semicolon <em>initialises</em> the loop, usually by defining a variable. The second part is the expression that <em>checks</em> whether the loop must still continue. The final part <em>updates</em> the state of the loop. In most cases this is shorter and clearer than a <code>while</code> construction.</p>
</div><hr/><div class="block">
<p>I have been using some rather odd <a name="key64"></a>capitalisation in some variable names. Because you can not have spaces in these names ― the computer would read them as two separate variables ― your choices for a name that is made of several words are more or less limited to the following: <code>fuzzylittleturtle</code>, <code>fuzzy_little_turtle</code>, <code>FuzzyLittleTurtle</code>, or <code>fuzzyLittleTurtle</code>. The first one is hard to read. Personally, I like the one with the underscores, though it is a little painful to type. However, the standard JavaScript functions, and most JavaScript programmers, follow the last one. It is not hard to get used to little things like that, so I will just follow the crowd and capitalise the first letter of every word after the first.</p>
<p>In a few cases, such as the <code>Number</code> function, the first letter of a variable is also capitalised. This was done to mark this function as a constructor. What a constructor is will become clear in <a href="chapter8.html">chapter 8</a>. For now, the important thing is not to be bothered by this apparent lack of consistency.</p>
<p>Note that names that have a special meaning, such as <code>var</code>, <code>while</code>, and <code>for</code> may not be used as variable names. These are called <a name="key65"></a>keywords. There are also a number of <a name="key66"></a>words which are 'reserved for use' in future versions of JavaScript. These are also officially not allowed to be used as variable names, though some browsers do allow them. The full list is rather long:</p>
<pre class="preformatted">abstract boolean break byte case catch char class const continue
debugger default delete do double else enum export extends false
final finally float for function goto if implements import in
instanceof int interface long native new null package private
protected public return short static super switch synchronized
this throw throws transient true try typeof var void volatile
while with</pre>
<p>Don't worry about memorising these for now, but remember that this might be the problem when something does not work as expected. In my experience, <code>char</code> (to store a one-character string) and <a name="key67"></a><code>class</code> are the most common names to accidentally use.</p>
</div><hr/><div class="block">
<a name="exercise4"></a>
<div class="exercisenum">Ex. 2.4</div>
<div class="exercise">
<p>Rewrite the solutions of the previous two exercises to use <code>for</code> instead of <code>while</code>.</p>
</div>
<div class="solution">
<pre class="code"><span class="keyword">var</span> <span class="variable">result</span> = <span class="atom">1</span>;
<span class="keyword">for</span> (<span class="keyword">var</span> <span class="variable">counter</span> = <span class="atom">0</span>; <span class="variable">counter</span> < <span class="atom">10</span>; <span class="variable">counter</span> = <span class="variable">counter</span> + <span class="atom">1</span>)
<span class="variable">result</span> = <span class="variable">result</span> * <span class="atom">2</span>;
<span class="variable">show</span>(<span class="variable">result</span>);</pre>
<p>Note that even if no block is opened with a '<code>{</code>', the statement in the loop is still indented two spaces to make it clear that it 'belongs' to the line above it.</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">line</span> = <span class="string">""</span>;
<span class="keyword">for</span> (<span class="keyword">var</span> <span class="variable">counter</span> = <span class="atom">0</span>; <span class="variable">counter</span> < <span class="atom">10</span>; <span class="variable">counter</span> = <span class="variable">counter</span> + <span class="atom">1</span>) {
<span class="variable">line</span> = <span class="variable">line</span> + <span class="string">"#"</span>;
<span class="variable">print</span>(<span class="variable">line</span>);
}</pre>
</div>
</div><hr/><div class="block">
<p><a name="key68"></a><a name="key69"></a><a name="key70"></a><a name="key71"></a>A program often needs to 'update' a variable with a value that is based on its previous value. For example <code>counter = counter + 1</code>. JavaScript provides a shortcut for this: <code>counter += 1</code>. This also works for many other operators, for example <code>result *= 2</code> to double the value of <code>result</code>, or <code>counter -= 1</code> to count downwards.</p>
<p><a name="key72"></a><a name="key73"></a>For <code>counter += 1</code> and <code>counter -= 1</code> there are even shorter versions: <code>counter++</code> and <code>counter--</code>.</p>
</div><hr/><div class="block">
<p>Loops are said to affect the <a name="key74"></a>control flow of a program. They change the order in which statements are executed. In many cases, another kind of flow is useful: skipping statements.</p>
<p>We want to show all numbers below 20 which are divisible both by 3 and by 4.</p>
<pre class="code"><span class="keyword">for</span> (<span class="keyword">var</span> <span class="variable">counter</span> = <span class="atom">0</span>; <span class="variable">counter</span> < <span class="atom">20</span>; <span class="variable">counter</span>++) {
<span class="keyword">if</span> (<span class="variable">counter</span> % <span class="atom">3</span> == <span class="atom">0</span> && <span class="variable">counter</span> % <span class="atom">4</span> == <span class="atom">0</span>)
<span class="variable">show</span>(<span class="variable">counter</span>);
}</pre>
<p>The keyword <a name="key75"></a><code>if</code> is not too different from the keyword <code>while</code>: It checks the condition it is given (between parentheses), and executes the statement after it based on this condition. But it does this only once, so that the statement is executed zero or one time.</p>
<p>The trick with the modulo (<a name="key76"></a><code>%</code>) operator is an easy way to test whether a number is divisible by another number. If it is, the remainder of their division, which is what modulo gives you, is zero.</p>
<p>If we wanted to print all numbers below 20, but put parentheses around the ones that are not divisible by 4, we can do it like this:</p>
<pre class="code"><span class="keyword">for</span> (<span class="keyword">var</span> <span class="variable">counter</span> = <span class="atom">0</span>; <span class="variable">counter</span> < <span class="atom">20</span>; <span class="variable">counter</span>++) {
<span class="keyword">if</span> (<span class="variable">counter</span> % <span class="atom">4</span> == <span class="atom">0</span>)
<span class="variable">print</span>(<span class="variable">counter</span>);
<span class="keyword">if</span> (<span class="variable">counter</span> % <span class="atom">4</span> != <span class="atom">0</span>)
<span class="variable">print</span>(<span class="string">"("</span> + <span class="variable">counter</span> + <span class="string">")"</span>);
}</pre>
<p>But now the program has to determine whether <code>counter</code> is divisible by <code>4</code> two times. The same effect can be gotten by appending an <code>else</code> part after an <code>if</code> statement. The <a name="key77"></a><code>else</code> statement is executed only when the <code>if</code>'s condition is false.</p>
<pre class="code"><span class="keyword">for</span> (<span class="keyword">var</span> <span class="variable">counter</span> = <span class="atom">0</span>; <span class="variable">counter</span> < <span class="atom">20</span>; <span class="variable">counter</span>++) {
<span class="keyword">if</span> (<span class="variable">counter</span> % <span class="atom">4</span> == <span class="atom">0</span>)
<span class="variable">print</span>(<span class="variable">counter</span>);
<span class="keyword">else</span>
<span class="variable">print</span>(<span class="string">"("</span> + <span class="variable">counter</span> + <span class="string">")"</span>);
}</pre>
<p>To stretch this trivial example a bit further, we now want to print these same numbers, but add two stars after them when they are greater than 15, one star when they are greater than 10 (but not greater than 15), and no stars otherwise.</p>
<pre class="code"><span class="keyword">for</span> (<span class="keyword">var</span> <span class="variable">counter</span> = <span class="atom">0</span>; <span class="variable">counter</span> < <span class="atom">20</span>; <span class="variable">counter</span>++) {
<span class="keyword">if</span> (<span class="variable">counter</span> > <span class="atom">15</span>)
<span class="variable">print</span>(<span class="variable">counter</span> + <span class="string">"**"</span>);
<span class="keyword">else</span> <span class="keyword">if</span> (<span class="variable">counter</span> > <span class="atom">10</span>)
<span class="variable">print</span>(<span class="variable">counter</span> + <span class="string">"*"</span>);
<span class="keyword">else</span>
<span class="variable">print</span>(<span class="variable">counter</span>);
}</pre>
<p>This demonstrates that you can chain <code>if</code> statements together. In this case, the program first looks if <code>counter</code> is greater than <code>15</code>. If it is, the two stars are printed and the other tests are skipped. If it is not, we continue to check if <code>counter</code> is greater than <code>10</code>. Only if <code>counter</code> is also not greater than <code>10</code> does it arrive at the last <code>print</code> statement.</p>
</div><hr/><div class="block">
<a name="exercise5"></a>
<div class="exercisenum">Ex. 2.5</div>
<div class="exercise">
<p>Write a program to ask yourself, using <code>prompt</code>, what the value of 2 + 2 is. If the answer is "4", use <code>alert</code> to say something praising. If it is "3" or "5", say "Almost!". In other cases, say something mean.</p>
</div>
<div class="solution">
<pre class="code"><span class="keyword">var</span> <span class="variable">answer</span> = <span class="variable">prompt</span>(<span class="string">"You! What is the value of 2 + 2?"</span>, <span class="string">""</span>);
<span class="keyword">if</span> (<span class="variable">answer</span> == <span class="string">"4"</span>)
<span class="variable">alert</span>(<span class="string">"You must be a genius or something."</span>);
<span class="keyword">else</span> <span class="keyword">if</span> (<span class="variable">answer</span> == <span class="string">"3"</span> || <span class="variable">answer</span> == <span class="string">"5"</span>)
<span class="variable">alert</span>(<span class="string">"Almost!"</span>);
<span class="keyword">else</span>
<span class="variable">alert</span>(<span class="string">"You're an embarrassment."</span>);</pre>
</div>
</div><hr/><div class="block">
<p>When a loop does not always have to go all the way through to its end, the <a name="key78"></a><code>break</code> keyword can be useful. It immediately jumps out of the current loop, continuing after it. This program finds the first number that is greater than 20 and divisible by 7:</p>
<pre class="code"><span class="keyword">for</span> (<span class="keyword">var</span> <span class="variable">current</span> = <span class="atom">20</span>; ; <span class="variable">current</span>++) {
<span class="keyword">if</span> (<span class="variable">current</span> % <span class="atom">7</span> == <span class="atom">0</span>)
<span class="keyword">break</span>;
}
<span class="variable">print</span>(<span class="variable">current</span>);</pre>
<p>The <code>for</code> construct does not have a part that checks for the end of the loop. This means that it is dependant on the <code>break</code> statement inside it to ever stop. The same program could also have been written as simply...</p>
<pre class="code"><span class="keyword">for</span> (<span class="keyword">var</span> <span class="variable">current</span> = <span class="atom">20</span>; <span class="variable">current</span> % <span class="atom">7</span> != <span class="atom">0</span>; <span class="variable">current</span>++)
;
<span class="variable">print</span>(<span class="variable">current</span>);</pre>
<p>In this case, the body of the loop is empty. A lone semicolon can be used to produce an empty statement. Here, the only effect of the loop is to increment the variable <code>current</code> to its desired value. But I needed an example that uses <code>break</code>, so pay attention to the first version too.</p>
</div><hr/><div class="block">
<a name="exercise6"></a>
<div class="exercisenum">Ex. 2.6</div>
<div class="exercise">
<p>Add a <code>while</code> and optionally a <code>break</code> to your solution for the previous exercise, so that it keeps repeating the question until a correct answer is given.</p>
<p>Note that <code>while (true) ...</code> can be used to create a loop that does not end on its own account. This is a bit silly, you ask the program to loop as long as <code>true</code> is <code>true</code>, but it is a useful trick.</p>
</div>
<div class="solution">
<pre class="code"><span class="keyword">var</span> <span class="variable">answer</span>;
<span class="keyword">while</span> (<span class="atom">true</span>) {
<span class="variable">answer</span> = <span class="variable">prompt</span>(<span class="string">"You! What is the value of 2 + 2?"</span>, <span class="string">""</span>);
<span class="keyword">if</span> (<span class="variable">answer</span> == <span class="string">"4"</span>) {
<span class="variable">alert</span>(<span class="string">"You must be a genius or something."</span>);
<span class="keyword">break</span>;
}
<span class="keyword">else</span> <span class="keyword">if</span> (<span class="variable">answer</span> == <span class="string">"3"</span> || <span class="variable">answer</span> == <span class="string">"5"</span>) {
<span class="variable">alert</span>(<span class="string">"Almost!"</span>);
}
<span class="keyword">else</span> {
<span class="variable">alert</span>(<span class="string">"You're an embarrassment."</span>);
}
}</pre>
<p>Because the first <code>if</code>'s body now has two statements, I added braces around all the bodies. This is a matter of taste. Having an <code>if</code>/<code>else</code> chain where some of the bodies are blocks and others are single statements looks a bit lopsided to me, but you can make up your own mind about that.</p>
<p>Another solution, arguably nicer, but without <code>break</code>:</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">value</span> = <span class="atom">null</span>;
<span class="keyword">while</span> (<span class="variable">value</span> != <span class="string">"4"</span>) {
<span class="variable">value</span> = <span class="variable">prompt</span>(<span class="string">"You! What is the value of 2 + 2?"</span>, <span class="string">""</span>);
<span class="keyword">if</span> (<span class="variable">value</span> == <span class="string">"4"</span>)
<span class="variable">alert</span>(<span class="string">"You must be a genius or something."</span>);
<span class="keyword">else</span> <span class="keyword">if</span> (<span class="variable">value</span> == <span class="string">"3"</span> || <span class="variable">value</span> == <span class="string">"5"</span>)
<span class="variable">alert</span>(<span class="string">"Almost!"</span>);
<span class="keyword">else</span>
<span class="variable">alert</span>(<span class="string">"You're an embarrassment."</span>);
}</pre>
</div>
</div><hr/><div class="block">
<p>In the solution to the previous exercise there is a statement <code>var answer;</code>. This creates a variable named <code>answer</code>, but does not give it a value. What happens when you take the value of this variable?</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">mysteryVariable</span>;
<span class="variable">show</span>(<span class="variable">mysteryVariable</span>);</pre>
<p>In terms of tentacles, this variable ends in thin air, it has nothing to grasp. When you ask for the value of an empty place, you get a special value named <a name="key79"></a><code>undefined</code>. Functions which do not return an interesting value, such as <code>print</code> and <code>alert</code>, also return an <code>undefined</code> value.</p>
<pre class="code"><span class="variable">show</span>(<span class="variable">alert</span>(<span class="string">"I am a side effect."</span>));</pre>
<p>There is also a similar value, <a name="key80"></a><code>null</code>, whose meaning is 'this variable is defined, but it does not have a value'. The difference in meaning between <code>undefined</code> and <code>null</code> is mostly academic, and usually not very interesting. In practical programs, it is often necessary to check whether something 'has a value'. In these cases, the expression <code>something == undefined</code> may be used, because, even though they are not exactly the same value, <code>null == undefined</code> will produce <code>true</code>.</p>
</div><hr/><div class="block">
<p>Which brings us to another tricky subject...</p>
<pre class="code"><span class="variable">show</span>(<span class="atom">false</span> == <span class="atom">0</span>);
<span class="variable">show</span>(<span class="string">""</span> == <span class="atom">0</span>);
<span class="variable">show</span>(<span class="string">"5"</span> == <span class="atom">5</span>);</pre>
<p><a name="key81"></a>All these give the value <code>true</code>. When comparing values that have different types, JavaScript uses a complicated and confusing set of rules. I am not going to try to explain them precisely, but in most cases it just tries to convert one of the values to the type of the other value. However, when <code>null</code> or <code>undefined</code> occur, it only produces <code>true</code> if both sides are <code>null</code> or <code>undefined</code>.</p>
<p>What if you want to test whether a variable refers to the value <code>false</code>? The rules for converting strings and numbers to boolean values state that <code>0</code> and the empty string count as <code>false</code>, while all the other values count as <code>true</code>. Because of this, the expression <code>variable == false</code> is also <code>true</code> when <code>variable</code> refers to <code>0</code> or <code>""</code>. For cases like this, where you do <em>not</em> want any automatic type conversions to happen, there are two extra operators: <a name="key82"></a><code>===</code> and <a name="key83"></a><code>!==</code>. The first tests whether a value is precisely equal to the other, and the second tests whether it is not precisely equal.</p>
<pre class="code"><span class="variable">show</span>(<span class="atom">null</span> === <span class="atom">undefined</span>);
<span class="variable">show</span>(<span class="atom">false</span> === <span class="atom">0</span>);
<span class="variable">show</span>(<span class="string">""</span> === <span class="atom">0</span>);
<span class="variable">show</span>(<span class="string">"5"</span> === <span class="atom">5</span>);</pre>
<p>All these are <code>false</code>.</p>
</div><hr/><div class="block">
<p>Values given as the condition in an <code>if</code>, <code>while</code>, or <code>for</code> statement do not have to be booleans. They will be automatically converted to booleans before they are checked. This means that the number <code>0</code>, the empty string <code>""</code>, <code>null</code>, <code>undefined</code>, and of course <code>false</code>, will all count as false.</p>
<p>The fact that all other values are converted to <code>true</code> in this case makes it possible to leave out explicit comparisons in many situations. If a variable is known to contain either a string or <code>null</code>, one could check for this very simply...</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">maybeNull</span> = <span class="atom">null</span>;
<span class="comment">// ... mystery code that might put a string into maybeNull ...</span>
<span class="keyword">if</span> (<span class="variable">maybeNull</span>)
<span class="variable">print</span>(<span class="string">"maybeNull has a value"</span>);</pre>
<p>Except in the case where the mystery code gives <code>maybeNull</code> the value <code>""</code>. An empty string is false, so nothing is printed. Depending on what you are trying to do, this might be <em>wrong</em>. It is often a good idea to add an explicit <code>=== null</code> or <code>=== false</code> in cases like this to prevent subtle mistakes. The same occurs with number values that might be <code>0</code>.</p>
</div><hr/><div class="block">
<p>The line that talks about 'mystery code' in the previous example might have looked a bit suspicious to you. It is often useful to include extra text in a program. The most common use for this is adding some explanations in human language to a program.</p>
<pre class="code"><span class="comment">// The variable counter, which is about to be defined, is going</span>
<span class="comment">// to start with a value of 0, which is zero.</span>
<span class="keyword">var</span> <span class="variable">counter</span> = <span class="atom">0</span>;
<span class="comment">// Now, we are going to loop, hold on to your hat.</span>
<span class="keyword">while</span> (<span class="variable">counter</span> < <span class="atom">100</span> <span class="comment">/* counter is less than one hundred */</span>)
<span class="comment">/* Every time we loop, we INCREMENT the value of counter,
Seriously, we just add one to it. */</span>
<span class="variable">counter</span>++;
<span class="comment">// And then, we are done.</span></pre>
<p>This kind of text is called a <a name="key84"></a>comment. The rules are like this:
'<code>/*</code>' starts a comment that goes on until a '<code>*/</code>' is found. '<code>//</code>' starts another kind of comment, which goes on until the end of the line.</p>
<p>As you can see, even the simplest programs can be made to look big, ugly, and complicated by simply adding a lot of comments to them.</p>
</div><hr/><div class="block">
<p>There are some other situations that cause automatic <a name="key85"></a>type conversions to happen. If you add a non-string value to a string, the value is automatically converted to a string before it is concatenated. If you multiply a number and a string, JavaScript tries to make a number out of the string.</p>
<pre class="code"><span class="variable">show</span>(<span class="string">"Apollo"</span> + <span class="atom">5</span>);
<span class="variable">show</span>(<span class="atom">null</span> + <span class="string">"ify"</span>);
<span class="variable">show</span>(<span class="string">"5"</span> * <span class="atom">5</span>);
<span class="variable">show</span>(<span class="string">"strawberry"</span> * <span class="atom">5</span>);</pre>
<p>The last statement prints <a name="key86"></a><code>NaN</code>, which is a special value. It stands
for 'not a number', and is of type number (which might sound a little contradictory). In this case, it refers to the fact that a strawberry is not a number. All arithmetic operations on the value <code>NaN</code> result in <code>NaN</code>, which is why multiplying it by <code>5</code>, as in the example, still gives a <code>NaN</code> value. Also, and this can be disorienting at times, <code>NaN == NaN</code> equals <code>false</code>, checking whether a value is <code>NaN</code> can be done with the <a name="key87"></a><code>isNaN</code> function. <code>NaN</code> is another (the last) value that counts as <code>false</code> when converted to a boolean.</p>
<p>These automatic conversions can be very convenient, but they are also rather weird and error prone. Even though <code>+</code> and <code>*</code> are both arithmetic operators, they behave completely different in the example. In my own code, I use <code>+</code> to combine strings and non-strings a lot, but make it a point not to use <code>*</code> and the other numeric operators on string values. Converting a number to a string is always possible and straightforward, but converting a string to a number may not even work (as in the last line of the example). We can use <code>Number</code> to explicitly convert the string to a number, making it clear that we might run the risk of getting a <code>NaN</code> value.</p>
<pre class="code"><span class="variable">show</span>(<span class="variable">Number</span>(<span class="string">"5"</span>) * <span class="atom">5</span>);</pre>
</div><hr/><div class="block">
<p>When we discussed the boolean operators <code>&&</code> and <code>||</code> earlier, I claimed they produced boolean values. This turns out to be a bit of an oversimplification. If you apply them to boolean values, they will indeed return booleans. But they can also be applied to other kinds of values, in which case they will return one of their arguments.</p>
<p>What <a name="key88"></a><code>||</code> really does is this: It looks at the value to the left of it first. If converting this value to a boolean would produce <code>true</code>, it returns this left value, and otherwise it returns the one on its right. Check for yourself that this does the correct thing when the arguments are booleans. Why does it work like that? It turns out this is very practical. Consider this example:</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">input</span> = <span class="variable">prompt</span>(<span class="string">"What is your name?"</span>, <span class="string">"Kilgore Trout"</span>);
<span class="variable">print</span>(<span class="string">"Well hello "</span> + (<span class="variable">input</span> || <span class="string">"dear"</span>));</pre>
<p>If the user presses 'Cancel' or closes the <code>prompt</code> dialog in some other way without giving a name, the variable <code>input</code> will hold the value <code>null</code> or <code>""</code>. Both of these would give <code>false</code> when converted to a boolean. The expression <code>input || "dear"</code> can in this case be read as 'the value of the variable <code>input</code>, or else the string <code>"dear"</code>'. It is an easy way to provide a 'fallback' value.</p>
<p>The <a name="key89"></a><code>&&</code> operator works similarly, but the other way around. When the value to its left is something that would give <code>false</code> when converted to a boolean, it returns that value, and otherwise it returns the value on its right.</p>
<p>Another property of these two operators is that the expression to their right is only evaluated when necessary. In the case of <code>true || X</code>, no matter what <code>X</code> is, the result will be <code>true</code>, so <code>X</code> is never evaluated, and if it has side effects they never happen. The same goes for <code>false && X</code>.</p>
<pre class="code"><span class="atom">false</span> || <span class="variable">alert</span>(<span class="string">"I'm happening!"</span>);
<span class="atom">true</span> || <span class="variable">alert</span>(<span class="string">"Not me."</span>);</pre>
</div>
<ol class="footnotes"><li>
<a name="footnote1"></a>
Bits are any kinds of two-valued things, usually described as <code>0</code>s and <code>1</code>s. Inside the computer, they take forms like a high or low electrical charge, a strong or weak signal, a shiny or dull spot on the surface of a CD.
</li><li>
<a name="footnote2"></a>
If you were expecting something like <code>10010000</code> here ― good call, but read on. JavaScript's numbers are not stored as integers.
</li><li>
<a name="footnote3"></a>
Actually, 53, because of a trick that can be used to get one bit for free. Look up the 'IEEE 754' format if you are curious about the details.
</li><li>
<a name="footnote4"></a>
When you type string values at the console, you'll notice that they will come back with the quotes and backslashes the way you typed them. To get special characters to show properly, you can do <code>print("a\nb")</code> ― why this works, we will see in a moment.
</li><li>
<a name="footnote5"></a>
The bit bucket is supposedly the place where old bits are kept. On some systems, the programmer has to manually empty it now and then. Fortunately, JavaScript comes with a fully-automatic bit-recycling system.
</li></ol>
<h1><span class="number">Chapitre 3 : </span>Fonctions</h1>
<div class="block">
<p>A program often needs to do the same thing in different places. Repeating all the necessary statements every time is tedious and error-prone. It would be better to put them in one place, and have the program take a detour through there whenever necessary. This is what <a name="key1"></a>functions were invented for: They are canned code that a program can go through whenever it wants. Putting a string on the screen requires quite a few statements, but when we have a <code>print</code> function we can just write <code>print("Aleph")</code> and be done with it.</p>
<p>To view functions merely as canned chunks of code doesn't do them justice though. When needed, they can play the role of pure functions, algorithms, indirections, abstractions, decisions, modules, continuations, data structures, and more. Being able to effectively use functions is a necessary skill for any kind of serious programming. This chapter provides an introduction into the subject, <a href="chapter6.html">chapter 6</a> discusses the subtleties of functions in more depth.</p>
</div><hr/><div class="block">
<p><a name="key2"></a>Pure functions, for a start, are the things that were called functions in the mathematics classes that I hope you have been subjected to at some point in your life. Taking the cosine or the absolute value of a number is a pure function of one argument. Addition is a pure function of two arguments.</p>
<p>The defining properties of pure functions are that they always return the same value when given the same arguments, and never have side effects. They take some arguments, return a value based on these arguments, and do not monkey around with anything else.</p>
<p>In JavaScript, addition is an operator, but it could be wrapped in a function like this (and as pointless as this looks, we will come across situations where it is actually useful):</p>
<pre class="code"><span class="keyword">function</span> <span class="variable">add</span>(<span class="variabledef">a</span>, <span class="variabledef">b</span>) {
<span class="keyword">return</span> <span class="localvariable">a</span> + <span class="localvariable">b</span>;
}
<span class="variable">show</span>(<span class="variable">add</span>(<span class="atom">2</span>, <span class="atom">2</span>));</pre>
<p><code>add</code> is the name of the function. <code>a</code> and <code>b</code> are the names of the two arguments. <code>return a + b;</code> is the body of the function.</p>
<p>The keyword <a name="key3"></a><code>function</code> is always used when creating a new function. When it is followed by a variable name, the resulting function will be stored under this name. After the name comes a list of <a name="key4"></a>argument names, and then finally the <a name="key5"></a>body of the function. Unlike those around the body of <code>while</code> loops or <code>if</code> statements, the braces around a function body are obligatory<a class="footref" href="#footnote1">1</a>.</p>
<p>The keyword <a name="key6"></a><code>return</code>, followed by an expression, is used to determine the value the function returns. When control comes across a <code>return</code> statement, it immediately jumps out of the current function and gives the returned value to the code that called the function. A <code>return</code> statement without an expression after it will cause the function to return <code>undefined</code>.</p>
<p>A body can, of course, have more than one statement in it. Here is a function for computing powers (with positive, integer exponents):</p>
<pre class="code"><span class="keyword">function</span> <span class="variable">power</span>(<span class="variabledef">base</span>, <span class="variabledef">exponent</span>) {
<span class="keyword">var</span> <span class="variabledef">result</span> = <span class="atom">1</span>;
<span class="keyword">for</span> (<span class="keyword">var</span> <span class="variabledef">count</span> = <span class="atom">0</span>; <span class="localvariable">count</span> < <span class="localvariable">exponent</span>; <span class="localvariable">count</span>++)
<span class="localvariable">result</span> *= <span class="localvariable">base</span>;
<span class="keyword">return</span> <span class="localvariable">result</span>;
}
<span class="variable">show</span>(<span class="variable">power</span>(<span class="atom">2</span>, <span class="atom">10</span>));</pre>
<p>If you solved <a href="chapter2.html#exercise2">exercise 2.2</a>, this technique for computing a power should look familiar.</p>
<p>Creating a variable (<code>result</code>) and updating it are side effects. Didn't I just say pure functions had no side effects?</p>
<p>A variable created inside a function exists only inside the function. This is fortunate, or a programmer would have to come up with a different name for every variable he needs throughout a program. Because <code>result</code> only exists inside <code>power</code>, the changes to it only last until the function returns, and from the perspective of code that calls it there are no side effects.</p>
</div><hr/><div class="block">
<a name="exercise1"></a>
<div class="exercisenum">Ex. 3.1</div>
<div class="exercise">
<p>Write a function called <code>absolute</code>, which returns the absolute value of the number it is given as its argument. The absolute value of a negative number is the positive version of that same number, and the absolute value of a positive number (or zero) is that number itself.</p>
</div>
<div class="solution">
<pre class="code"><span class="keyword">function</span> <span class="variable">absolute</span>(<span class="variabledef">number</span>) {
<span class="keyword">if</span> (<span class="localvariable">number</span> < <span class="atom">0</span>)
<span class="keyword">return</span> -<span class="localvariable">number</span>;
<span class="keyword">else</span>
<span class="keyword">return</span> <span class="localvariable">number</span>;
}
<span class="variable">show</span>(<span class="variable">absolute</span>(-<span class="atom">144</span>));</pre>
</div>
</div><hr/><div class="block">
<p>Pure functions have two very nice properties. They are easy to think about, and they are easy to re-use.</p>
<p>If a function is pure, a call to it can be seen as a thing in itself. When you are not sure that it is working correctly, you can test it by calling it directly from the console, which is simple because it does not depend on any context<a class="footref" href="#footnote2">2</a>. It is easy to make these tests automatic ― to write a program that tests a specific function. Non-pure functions might return different values based on all kinds of factors, and have side effects that might be hard to test and think about.</p>
<p>Because pure functions are self-sufficient, they are likely to be useful and relevant in a wider range of situations than non-pure ones. Take <code>show</code>, for example. This function's usefulness depends on the presence of a special place on the screen for printing output. If that place is not there, the function is useless. We can imagine a related function, let's call it <code>format</code>, that takes a value as an argument and returns a string that represents this value. This function is useful in more situations than <code>show</code>.</p>
<p>Of course, <code>format</code> does not solve the same problem as <code>show</code>, and no pure function is going to be able to solve that problem, because it requires a side effect. In many cases, non-pure functions are precisely what you need. In other cases, a problem can be solved with a pure function but the non-pure variant is much more convenient or efficient.</p>
<p>Thus, when something can easily be expressed as a pure function, write it that way. But never feel dirty for writing non-pure functions.</p>
</div><hr/><div class="block">
<p>Functions with side effects do not have to contain a <code>return</code> statement. If no <code>return</code> statement is encountered, the function returns <code>undefined</code>.</p>
<pre class="code"><span class="keyword">function</span> <span class="variable">yell</span>(<span class="variabledef">message</span>) {
<span class="variable">alert</span>(<span class="localvariable">message</span> + <span class="string">"!!"</span>);
}
<span class="variable">yell</span>(<span class="string">"Yow"</span>);</pre>
</div><hr/><div class="block">
<p>The names of the arguments of a function are available as variables inside it. They will refer to the values of the arguments the function is being called with, and like normal variables created inside a function, they do not exist outside it. Aside from the <a name="key7"></a>top-level environment, there are smaller, <a name="key8"></a>local environments created by function calls. When looking up a variable inside a function, the local environment is checked first, and only if the variable does not exist there is it looked up in the top-level environment. This makes it possible for variables inside a function to '<a name="key9"></a>shadow' top-level variables that have the same name.</p>
<pre class="code"><span class="keyword">function</span> <span class="variable">alertIsPrint</span>(<span class="variabledef">value</span>) {
<span class="keyword">var</span> <span class="variabledef">alert</span> = <span class="variable">print</span>;
<span class="localvariable">alert</span>(<span class="localvariable">value</span>);
}
<span class="variable">alertIsPrint</span>(<span class="string">"Troglodites"</span>);</pre>
<p>The variables in this local environment are only visible to the code inside the function. If this function calls another function, the newly called function does not see the variables inside the first function:</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">variable</span> = <span class="string">"top-level"</span>;
<span class="keyword">function</span> <span class="variable">printVariable</span>() {
<span class="variable">print</span>(<span class="string">"inside printVariable, the variable holds '"</span> +
<span class="variable">variable</span> + <span class="string">"'."</span>);
}
<span class="keyword">function</span> <span class="variable">test</span>() {
<span class="keyword">var</span> <span class="variabledef">variable</span> = <span class="string">"local"</span>;
<span class="variable">print</span>(<span class="string">"inside test, the variable holds '"</span> + <span class="localvariable">variable</span> + <span class="string">"'."</span>);
<span class="variable">printVariable</span>();
}
<span class="variable">test</span>();</pre>
<p>However, and this is a subtle but extremely useful phenomenon, when a function is defined <em>inside</em> another function, its local environment will be based on the local environment that surrounds it instead of the top-level environment.</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">variable</span> = <span class="string">"top-level"</span>;
<span class="keyword">function</span> <span class="variable">parentFunction</span>() {
<span class="keyword">var</span> <span class="variabledef">variable</span> = <span class="string">"local"</span>;
<span class="keyword">function</span> <span class="variabledef">childFunction</span>() {
<span class="variable">print</span>(<span class="localvariable">variable</span>);
}
<span class="localvariable">childFunction</span>();
}
<span class="variable">parentFunction</span>();</pre>
<p>What this comes down to is that which variables are visible inside a function is determined by the place of that function in the program text. All variables that were defined 'above' a function's definition are visible, which means both those in function bodies that enclose it, and those at the top-level of the program. This approach to variable visibility is called <a name="key10"></a>lexical scoping.</p>
</div><hr/><div class="block">
<p>People who have experience with other programming languages might expect that a <a name="key11"></a>block of code (between braces) also produces a new local environment. Not in JavaScript. Functions are the only things that create a new scope. You are allowed to use free-standing blocks like this...</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">something</span> = <span class="atom">1</span>;
{
<span class="keyword">var</span> <span class="variable">something</span> = <span class="atom">2</span>;
<span class="variable">print</span>(<span class="string">"Inside: "</span> + <span class="variable">something</span>);
}
<span class="variable">print</span>(<span class="string">"Outside: "</span> + <span class="variable">something</span>);</pre>
<p>... but the <code>something</code> inside the block refers to the same variable as the one outside the block. In fact, although blocks like this are allowed, they are utterly pointless. Most people agree that this is a bit of a design blunder by the designers of JavaScript, and ECMAScript Harmony will add some way to define variables that stay inside blocks (the <code>let</code> keyword).</p>
</div><hr/><div class="block">
<p>Here is a case that might surprise you:</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">variable</span> = <span class="string">"top-level"</span>;
<span class="keyword">function</span> <span class="variable">parentFunction</span>() {
<span class="keyword">var</span> <span class="variabledef">variable</span> = <span class="string">"local"</span>;
<span class="keyword">function</span> <span class="variabledef">childFunction</span>() {
<span class="variable">print</span>(<span class="localvariable">variable</span>);
}
<span class="keyword">return</span> <span class="localvariable">childFunction</span>;
}
<span class="keyword">var</span> <span class="variable">child</span> = <span class="variable">parentFunction</span>();
<span class="variable">child</span>();</pre>
<p><code>parentFunction</code> <em>returns</em> its internal function, and the code at the bottom calls this function. Even though <code>parentFunction</code> has finished executing at this point, the local environment where <code>variable</code> has the value <code>"local"</code> still exists, and <code>childFunction</code> still uses it. This phenomenon is called <a name="key12"></a>closure.</p>
</div><hr/><div class="block">
<p>Apart from making it very easy to quickly see in which part of a program a variable will be available by looking at the shape of the program text, lexical scoping also allows us to 'synthesise' functions. By using some of the variables from an enclosing function, an inner function can be made to do different things. Imagine we need a few different but similar functions, one that adds 2 to its argument, one that adds 5, and so on.</p>
<pre class="code"><span class="keyword">function</span> <span class="variable">makeAddFunction</span>(<span class="variabledef">amount</span>) {
<span class="keyword">function</span> <span class="variabledef">add</span>(<span class="variabledef">number</span>) {
<span class="keyword">return</span> <span class="localvariable">number</span> + <span class="localvariable">amount</span>;
}
<span class="keyword">return</span> <span class="localvariable">add</span>;
}
<span class="keyword">var</span> <span class="variable">addTwo</span> = <span class="variable">makeAddFunction</span>(<span class="atom">2</span>);
<span class="keyword">var</span> <span class="variable">addFive</span> = <span class="variable">makeAddFunction</span>(<span class="atom">5</span>);
<span class="variable">show</span>(<span class="variable">addTwo</span>(<span class="atom">1</span>) + <span class="variable">addFive</span>(<span class="atom">1</span>));</pre>
</div><hr/><div class="block">
<p>On top of the fact that different functions can contain variables of the same name without getting tangled up, these scoping rules also allow functions to call <em>themselves</em> without running into problems. A function that calls itself is called recursive. <a name="key13"></a>Recursion allows for some interesting definitions. Look at this implementation of <code>power</code>:</p>
<pre class="code"><span class="keyword">function</span> <span class="variable">power</span>(<span class="variabledef">base</span>, <span class="variabledef">exponent</span>) {
<span class="keyword">if</span> (<span class="localvariable">exponent</span> == <span class="atom">0</span>)
<span class="keyword">return</span> <span class="atom">1</span>;
<span class="keyword">else</span>
<span class="keyword">return</span> <span class="localvariable">base</span> * <span class="variable">power</span>(<span class="localvariable">base</span>, <span class="localvariable">exponent</span> - <span class="atom">1</span>);
}</pre>
<p>This is rather close to the way mathematicians define exponentiation, and to me it looks a lot nicer than the earlier version. It sort of loops, but there is no <code>while</code>, <code>for</code>, or even a local side effect to be seen. By calling itself, the function produces the same effect.</p>
<p>There is one important problem though: In most browsers, this second version is about ten times slower than the first one. In JavaScript, running through a simple loop is a lot cheaper than calling a function multiple times.</p>
</div><hr/><div class="block">
<p><a name="key14"></a>The dilemma of speed versus <a name="key15"></a>elegance is an interesting one. It not only occurs when deciding for or against recursion. In many situations, an elegant, intuitive, and often short solution can be replaced by a more convoluted but faster solution.</p>
<p>In the case of the <code>power</code> function above the un-elegant version is still sufficiently simple and easy to read. It doesn't make very much sense to replace it with the recursive version. Often, though, the concepts a program is dealing with get so complex that giving up some efficiency in order to make the program more straightforward becomes an attractive choice.</p>
<p>The basic rule, which has been repeated by many programmers and with which I wholeheartedly agree, is to not worry about efficiency until your program is provably too slow. When it is, find out which parts are too slow, and start exchanging elegance for efficiency in those parts.</p>
<p>Of course, the above rule doesn't mean one should start ignoring performance altogether. In many cases, like the <code>power</code> function, not much simplicity is gained by the 'elegant' approach. In other cases, an experienced programmer can see right away that a simple approach is never going to be fast enough.</p>
<p>The reason I am making a big deal out of this is that surprisingly many programmers focus fanatically on efficiency, even in the smallest details. The result is bigger, more complicated, and often less correct programs, which take longer to write than their more straightforward equivalents and often run only marginally faster.</p>
</div><hr/><div class="block">
<p>But I was talking about recursion. A concept closely related to recursion is a thing called the <a name="key16"></a>stack. When a function is called, control is given to the body of that function. When that body returns, the code that called the function is resumed. While the body is running, the computer must remember the context from which the function was called, so that it knows where to continue afterwards. The place where this context is stored is called the stack.</p>
<p>The fact that it is called 'stack' has to do with the fact that, as we saw, a function body can again call a function. Every time a function is called, another context has to be stored. One can visualise this as a stack of contexts. Every time a function is called, the current context is thrown on top of the stack. When a function returns, the context on top is taken off the stack and resumed.</p>
<p>This stack requires space in the computer's memory to be stored. When the stack grows too big, the computer will give up with a message like "out of stack space" or "too much recursion". This is something that has to be kept in mind when writing recursive functions.</p>
<pre class="code invalid"><span class="keyword">function</span> <span class="variable">chicken</span>() {
<span class="keyword">return</span> <span class="variable">egg</span>();
}
<span class="keyword">function</span> <span class="variable">egg</span>() {
<span class="keyword">return</span> <span class="variable">chicken</span>();
}
<span class="variable">print</span>(<span class="variable">chicken</span>() + <span class="string">" came first."</span>);</pre>
<p>In addition to demonstrating a very interesting way of writing a broken program, this example shows that a function does not have to call itself directly to be recursive. If it calls another function which (directly or indirectly) calls the first function again, it is still recursive.</p>
</div><hr/><div class="block">
<p>Recursion is not always just a less-efficient alternative to looping. Some problems are much easier to solve with recursion than with loops. Most often these are problems that require exploring or processing several 'branches', each of which might branch out again into more branches.</p>
<p>Consider this puzzle: By starting from the number 1 and repeatedly either adding 5 or multiplying by 3, an infinite amount of new numbers can be produced. How would you write a function that, given a number, tries to find a sequence of additions and multiplications that produce that number?</p>
<p>For example, the number 13 could be reached by first multiplying 1 by 3, and then adding 5 twice. The number 15 can not be reached at all.</p>
<p>Here is the solution:</p>
<pre class="code"><span class="keyword">function</span> <span class="variable">findSequence</span>(<span class="variabledef">goal</span>) {
<span class="keyword">function</span> <span class="variabledef">find</span>(<span class="variabledef">start</span>, <span class="variabledef">history</span>) {
<span class="keyword">if</span> (<span class="localvariable">start</span> == <span class="localvariable">goal</span>)
<span class="keyword">return</span> <span class="localvariable">history</span>;
<span class="keyword">else</span> <span class="keyword">if</span> (<span class="localvariable">start</span> > <span class="localvariable">goal</span>)
<span class="keyword">return</span> <span class="atom">null</span>;
<span class="keyword">else</span>
<span class="keyword">return</span> <span class="localvariable">find</span>(<span class="localvariable">start</span> + <span class="atom">5</span>, <span class="string">"("</span> + <span class="localvariable">history</span> + <span class="string">" + 5)"</span>) ||
<span class="localvariable">find</span>(<span class="localvariable">start</span> * <span class="atom">3</span>, <span class="string">"("</span> + <span class="localvariable">history</span> + <span class="string">" * 3)"</span>);
}
<span class="keyword">return</span> <span class="localvariable">find</span>(<span class="atom">1</span>, <span class="string">"1"</span>);
}
<span class="variable">print</span>(<span class="variable">findSequence</span>(<span class="atom">24</span>));</pre>
<p>Note that it doesn't necessarily find the <em>shortest</em> sequence of operations, it is satisfied when it finds any sequence at all.</p>
<p>The inner <code>find</code> function, by calling itself in two different ways, explores both the possibility of adding 5 to the current number and of multiplying it by 3. When it finds the number, it returns the <code>history</code> string, which is used to record all the operators that were performed to get to this number. It also checks whether the current number is bigger than <code>goal</code>, because if it is, we should stop exploring this branch, it is not going to give us our number.</p>
<p>The use of the <code>||</code> operator in the example can be read as 'return the solution found by adding 5 to <code>start</code>, and if that fails, return the solution found by multiplying <code>start</code> by 3'. It could also have been written in a more wordy way like this:</p>
<pre class="code invalid"><span class="keyword">else</span> {
<span class="keyword">var</span> <span class="variable">found</span> = <span class="variable">find</span>(<span class="variable">start</span> + <span class="atom">5</span>, <span class="string">"("</span> + <span class="variable">history</span> + <span class="string">" + 5)"</span>);
<span class="keyword">if</span> (<span class="variable">found</span> == <span class="atom">null</span>)
<span class="variable">found</span> = <span class="variable">find</span>(<span class="variable">start</span> * <span class="atom">3</span>, <span class="variable">history</span> + <span class="string">" * 3"</span>);
<span class="keyword">return</span> <span class="variable">found</span>;
}</pre>
</div><hr/><div class="block">
<p>Even though function definitions occur as statements between the rest
of the program, they are not part of the same time-line:</p>
<pre class="code"><span class="variable">print</span>(<span class="string">"The future says: "</span>, <span class="variable">future</span>());
<span class="keyword">function</span> <span class="variable">future</span>() {
<span class="keyword">return</span> <span class="string">"We STILL have no flying cars."</span>;
}</pre>
<p>What is happening is that the computer looks up all function definitions, and stores the associated functions, <em>before</em> it starts executing the rest of the program. The same happens with functions that are defined inside other functions. When the outer function is called, the first thing that happens is that all inner functions are added to the new environment.</p>
</div><hr/><div class="block">
<p>There is another way to define function values, which more closely resembles the way other values are created. When the <code>function</code> keyword is used in a place where an expression is expected, it is treated as an expression producing a function value. Functions created in this way do not have to be given a name (though it is allowed to give them one).</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">add</span> = <span class="keyword">function</span>(<span class="variabledef">a</span>, <span class="variabledef">b</span>) {
<span class="keyword">return</span> <span class="localvariable">a</span> + <span class="localvariable">b</span>;
};
<span class="variable">show</span>(<span class="variable">add</span>(<span class="atom">5</span>, <span class="atom">5</span>));</pre>
<p>Note the semicolon after the definition of <code>add</code>. Normal function definitions do not need these, but this statement has the same general structure as <code>var add = 22;</code>, and thus requires the semicolon.</p>
<p>This kind of function value is called an <a name="key17"></a>anonymous function, because it does not have a name. Sometimes it is useless to give a function a name, like in the <code>makeAddFunction</code> example we saw earlier:</p>
<pre class="code"><span class="keyword">function</span> <span class="variable">makeAddFunction</span>(<span class="variabledef">amount</span>) {
<span class="keyword">return</span> <span class="keyword">function</span> (<span class="variabledef">number</span>) {
<span class="keyword">return</span> <span class="localvariable">number</span> + <span class="localvariable">amount</span>;
};
}</pre>
<p>Since the function named <code>add</code> in the first version of <code>makeAddFunction</code> was referred to only once, the name does not serve any purpose and we might as well directly return the function value.</p>
</div><hr/><div class="block">
<a name="exercise2"></a>
<div class="exercisenum">Ex. 3.2</div>
<div class="exercise">
<p>Write a function <code>greaterThan</code>, which takes one argument, a number, and returns a function that represents a test. When this returned function is called with a single number as argument, it returns a boolean: <code>true</code> if the given number is greater than the number that was used to create the test function, and <code>false</code> otherwise.</p>
</div>
<div class="solution">
<pre class="code"><span class="keyword">function</span> <span class="variable">greaterThan</span>(<span class="variabledef">x</span>) {
<span class="keyword">return</span> <span class="keyword">function</span>(<span class="variabledef">y</span>) {
<span class="keyword">return</span> <span class="localvariable">y</span> > <span class="localvariable">x</span>;
};
}
<span class="keyword">var</span> <span class="variable">greaterThanTen</span> = <span class="variable">greaterThan</span>(<span class="atom">10</span>);
<span class="variable">show</span>(<span class="variable">greaterThanTen</span>(<span class="atom">9</span>));</pre>
</div>
</div><hr/><div class="block">
<p>Try the following:</p>
<pre class="code"><span class="variable">alert</span>(<span class="string">"Hello"</span>, <span class="string">"Good Evening"</span>, <span class="string">"How do you do?"</span>, <span class="string">"Goodbye"</span>);</pre>
<p>The function <code>alert</code> officially only accepts one argument. Yet when you call it like this, the computer does not complain at all, but just ignores the other arguments.</p>
<pre class="code"><span class="variable">show</span>();</pre>
<p>You can, apparently, even get away with passing too few arguments. When an argument is not passed, its value inside the function is <code>undefined</code>.</p>
<p>In the next chapter, we will see a way in which a function body can get at the exact list of arguments that were passed to it. This can be useful, as it makes it possible to have a function accept any number of arguments. <code>print</code> makes use of this:</p>
<pre class="code"><span class="variable">print</span>(<span class="string">"R"</span>, <span class="atom">2</span>, <span class="string">"D"</span>, <span class="atom">2</span>);</pre>
<p>Of course, the downside of this is that it is also possible to accidentally pass the wrong number of arguments to functions that expect a fixed amount of them, like <code>alert</code>, and never be told about it.</p>
</div>
<ol class="footnotes"><li>
<a name="footnote1"></a>
Technically, this wouldn't have been necessary, but I suppose the designers of JavaScript felt it would clarify things if function bodies always had braces.
</li><li>
<a name="footnote2"></a>
Technically, a pure function can not use the value of any external variables. These values might change, and this could make the function return a different value for the same arguments. In practice, the programmer may consider some variables 'constant' ― they are not expected to change ― and consider functions that use only constant variables pure. Variables that contain a function value are often good examples of constant variables.
</li></ol>
<h1><span class="number">Chapitre 4 : </span>Structures de données : objets et tableaux</h1>
<div class="block">
<p>This chapter will be devoted to solving a few simple problems. In the process, we will discuss two new types of values, arrays and objects, and look at some techniques related to them.</p>
<p>Consider the following situation: Your crazy aunt Emily, who is rumoured to have over fifty cats living with her (you never managed to count them), regularly sends you e-mails to keep you up to date on her exploits. They usually look like this:</p>
<blockquote>Dear nephew,
<br/><br/>
Your mother told me you have taken up skydiving. Is this true? You watch yourself, young man! Remember what happened to my husband? And that was only from the second floor!
<br/><br/>
Anyway, things are very exciting here. I have spent all week trying to get the attention of Mr. Drake, the nice gentleman who moved in next door, but I think he is afraid of cats. Or allergic to them? I am going to try putting Fat Igor on his shoulder next time I see him, very curious what will happen.
<br/><br/>
Also, the scam I told you about is going better than expected. I have already gotten back five 'payments', and only one complaint. It is starting to make me feel a bit bad though. And you are right that it is probably illegal in some way.
<br/><br/>
(... etc ...)
<br/><br/>
Much love, Aunt Emily
<br/><br/>
died 27/04/2006: Black Leclère
<br/><br/>
born 05/04/2006 (mother Lady Penelope): Red Lion, Doctor Hobbles the 3rd, Little Iroquois</blockquote>
<p>To humour the old dear, you would like to keep track of the genealogy of her cats, so you can add things like "P.S. I hope Doctor Hobbles the 2nd enjoyed his birthday this Saturday!", or "How is old Lady Penelope doing? She's five years old now, isn't she?", preferably without accidentally asking about dead cats. You are in the possession of a large quantity of old e-mails from your aunt, and fortunately she is very consistent in always putting information about the cats' births and deaths at the end of her mails in precisely the same format.</p>
<p>You are hardly inclined to go through all those mails by hand. Fortunately, we were just in need of an example problem, so we will try to work out a program that does the work for us. For a start, we write a program that gives us a list of cats that are still alive after the last e-mail.</p>
<p>Before you ask, at the start of the correspondence, aunt Emily had only a single cat: Spot. (She was still rather conventional in those days.)</p>
</div><hr/><div class="block">
<div class="picture">
<img src="img/eyes.png"/>
</div>
</div><hr/><div class="block">
<p>It usually pays to have some kind of clue what one's program is going
to do before starting to type. Here's a plan:</p>
<ol><li>
Start with a set of cat names that has only "Spot" in it.
</li><li>
Go over every e-mail in our archive, in chronological order.
</li><li>
Look for paragraphs that start with "born" or "died".
</li><li>
Add the names from paragraphs that start with "born" to our set of names.
</li><li>
Remove the names from paragraphs that start with "died" from our set.
</li></ol>
<p>Where taking the names from a paragraph goes like this:</p>
<ol><li>
Find the colon in the paragraph.
</li><li>
Take the part after this colon.
</li><li>
Split this part into separate names by looking for commas.
</li></ol>
<p>It may require some suspension of disbelief to accept that aunt Emily always used this exact format, and that she never forgot or misspelled a name, but that is just how your aunt is.</p>
</div><hr/><div class="block">
<p>First, let me tell you about <a name="key1"></a>properties. A lot of JavaScript values have other values associated with them. These associations are called properties. Every string has a property called <a name="key2"></a><code>length</code>, which refers to a number, the amount of characters in that string.</p>
<p><a name="key3"></a>Properties can be accessed in two ways:</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">text</span> = <span class="string">"purple haze"</span>;
<span class="variable">show</span>(<span class="variable">text</span>[<span class="string">"length"</span>]);
<span class="variable">show</span>(<span class="variable">text</span>.<span class="property">length</span>);</pre>
<p>The second way is a shorthand for the first, and it only works when the name of the property would be a valid variable name ― when it doesn't have any spaces or symbols in it and does not start with a digit character.</p>
<p>The values <code>null</code> and <code>undefined</code> do not have any properties. Trying to read properties from such a value produces an error. Try the following code, if only to get an idea about the kind of error-message your browser produces in such a case (which, for some browsers, can be rather cryptic).</p>
<pre class="code invalid"><span class="keyword">var</span> <span class="variable">nothing</span> = <span class="atom">null</span>;
<span class="variable">show</span>(<span class="variable">nothing</span>.<span class="property">length</span>);</pre>
</div><hr/><div class="block">
<p>The properties of a string value can not be changed. There are quite a few more than just <code>length</code>, as we will see, but you are not allowed to add or remove any.</p>
<p>This is different with values of the type <a name="key4"></a>object. Their main role is to hold other values. They have, you could say, their own set of tentacles in the form of properties. You are free to modify these, remove them, or add new ones.</p>
<p><a name="key5"></a>An object can be written like this:</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">cat</span> = {<span class="property">colour</span>: <span class="string">"grey"</span>, <span class="property">name</span>: <span class="string">"Spot"</span>, <span class="property">size</span>: <span class="atom">46</span>};
<span class="variable">cat</span>.<span class="property">size</span> = <span class="atom">47</span>;
<span class="variable">show</span>(<span class="variable">cat</span>.<span class="property">size</span>);
<span class="keyword">delete</span> <span class="variable">cat</span>.<span class="property">size</span>;
<span class="variable">show</span>(<span class="variable">cat</span>.<span class="property">size</span>);
<span class="variable">show</span>(<span class="variable">cat</span>);</pre>
<p>Like variables, each property attached to an object is labelled by a string. The first statement creates an object in which the property <code>"colour"</code> holds the string <code>"grey"</code>, the property <code>"name"</code> is attached to the string <code>"Spot"</code>, and the property <code>"size"</code> refers to the number <code>46</code>. The second statement gives the property named <code>size</code> a new value, which is done in the same way as modifying a variable.</p>
<p>The keyword <a name="key6"></a><code>delete</code> cuts off properties. Trying to read a non-existent property gives the value <code>undefined</code>.</p>
<p>If a property that does not yet exist is set with the <a name="key7"></a><code>=</code> operator, it is added to the object.</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">empty</span> = {};
<span class="variable">empty</span>.<span class="property">notReally</span> = <span class="atom">1000</span>;
<span class="variable">show</span>(<span class="variable">empty</span>.<span class="property">notReally</span>);</pre>
<p>Properties whose names are not valid variable names have to be quoted when creating the object, and approached using brackets:</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">thing</span> = {<span class="string">"gabba gabba"</span>: <span class="string">"hey"</span>, <span class="string">"5"</span>: <span class="atom">10</span>};
<span class="variable">show</span>(<span class="variable">thing</span>[<span class="string">"5"</span>]);
<span class="variable">thing</span>[<span class="string">"5"</span>] = <span class="atom">20</span>;
<span class="variable">show</span>(<span class="variable">thing</span>[<span class="atom">2</span> + <span class="atom">3</span>]);
<span class="keyword">delete</span> <span class="variable">thing</span>[<span class="string">"gabba gabba"</span>];</pre>
<p>As you can see, the part between the brackets can be any expression. It is converted to a string to determine the property name it refers to. One can even use variables to name properties:</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">propertyName</span> = <span class="string">"length"</span>;
<span class="keyword">var</span> <span class="variable">text</span> = <span class="string">"mainline"</span>;
<span class="variable">show</span>(<span class="variable">text</span>[<span class="variable">propertyName</span>]);</pre>
<p>The operator <a name="key8"></a><code>in</code> can be used to test whether an object has a certain property. It produces a boolean.</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">chineseBox</span> = {};
<span class="variable">chineseBox</span>.<span class="property">content</span> = <span class="variable">chineseBox</span>;
<span class="variable">show</span>(<span class="string">"content"</span> in <span class="variable">chineseBox</span>);
<span class="variable">show</span>(<span class="string">"content"</span> in <span class="variable">chineseBox</span>.<span class="property">content</span>);</pre>
</div><hr/><div class="block">
<p>When object values are shown on the console, they can be clicked to inspect their properties. This changes the output window to an 'inspect' window. The little 'x' at the top-right can be used to return to the output window, and the left-arrow can be used to go back to the properties of the previously inspected object.</p>
<pre class="code"><span class="variable">show</span>(<span class="variable">chineseBox</span>);</pre>
</div><hr/><div class="block">
<a name="exercise1"></a>
<div class="exercisenum">Ex. 4.1</div>
<div class="exercise">
<p>The solution for the cat problem talks about a 'set' of names. A <a name="key9"></a>set is a collection of values in which no value may occur more than once. If names are strings, can you think of a way to use an object to represent a set of names?</p>
<p>Show how a name can be added to this set, how one can be removed, and how you can check whether a name occurs in it.</p>
</div>
<div class="solution">
<p>This can be done by storing the content of the set as the properties of an object. Adding a name is done by setting a property by that name to a value, any value. Removing a name is done by deleting this property. The <code>in</code> operator can be used to determine whether a certain name is part of the set<a class="footref" href="#footnote1">1</a>.</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">set</span> = {<span class="string">"Spot"</span>: <span class="atom">true</span>};
<span class="comment">// Add "White Fang" to the set</span>
<span class="variable">set</span>[<span class="string">"White Fang"</span>] = <span class="atom">true</span>;
<span class="comment">// Remove "Spot"</span>
<span class="keyword">delete</span> <span class="variable">set</span>[<span class="string">"Spot"</span>];
<span class="comment">// See if "Asoka" is in the set</span>
<span class="variable">show</span>(<span class="string">"Asoka"</span> in <span class="variable">set</span>);</pre>
</div>
</div><hr/><div class="block">
<p><a name="key10"></a>Object values, apparently, can change. The types of values discussed in <a href="chapter2.html">chapter 2</a> are all immutable, it is impossible to change an existing value of those types. You can combine them and derive new values from them, but when you take a specific string value, the text inside it can not change. With objects, on the other hand, the content of a value can be modified by changing its properties.</p>
<p>When we have two numbers, <code>120</code> and <code>120</code>, they can for all practical purposes be considered the precise same number. 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="code"><span class="keyword">var</span> <span class="variable">object1</span> = {<span class="property">value</span>: <span class="atom">10</span>};
<span class="keyword">var</span> <span class="variable">object2</span> = <span class="variable">object1</span>;
<span class="keyword">var</span> <span class="variable">object3</span> = {<span class="property">value</span>: <span class="atom">10</span>};
<span class="variable">show</span>(<span class="variable">object1</span> == <span class="variable">object2</span>);
<span class="variable">show</span>(<span class="variable">object1</span> == <span class="variable">object3</span>);
<span class="variable">object1</span>.<span class="property">value</span> = <span class="atom">15</span>;
<span class="variable">show</span>(<span class="variable">object2</span>.<span class="property">value</span>);
<span class="variable">show</span>(<span class="variable">object3</span>.<span class="property">value</span>);</pre>
<p><code>object1</code> and <code>object2</code> are two variables grasping the <em>same</em> value. There is only one actual object, which is why changing <code>object1</code> also changes the value of <code>object2</code>. The variable <code>object3</code> points to another object, which initially contains the same properties as <code>object1</code>, but lives a separate life.</p>
<p>JavaScript's <a name="key11"></a><code>==</code> operator, when comparing objects, will only return <code>true</code> if both values given to it are the precise same value. Comparing different objects with identical contents will give <code>false</code>. This is useful in some situations, but unpractical in others.</p>
</div><hr/><div class="block">
<p>Object values can play a lot of different roles. Behaving like a set is only one of those. We will see a few other roles in this chapter, and <a href="chapter8.html">chapter 8</a> shows another important way of using objects.</p>
<p>In the plan for the cat problem ― in fact, call it an <em>algorithm</em>, not a plan, that makes it sound like we know what we are talking about ― in the algorithm, it talks about going over all the e-mails in an archive. What does this archive look like? And where does it come from?</p>
<p>Do not worry about the second question for now. <a href="chapter14.html">Chapter 14</a> talks about some ways to import data into your programs, but for now you will find that the e-mails are just magically there. Some magic is really easy, inside computers.</p>
</div><hr/><div class="block">
<p>The way in which the archive is stored is still an interesting question. It contains a number of e-mails. An e-mail can be a string, that should be obvious. The whole archive could be put into one huge string, but that is hardly practical. What we want is a collection of separate strings.</p>
<p>Collections of things are what objects are used for. One could make an object like this:</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">mailArchive</span> = {<span class="string">"the first e-mail"</span>: <span class="string">"Dear nephew, ..."</span>,
<span class="string">"the second e-mail"</span>: <span class="string">"..."</span>
<span class="comment">/* and so on ... */</span>};</pre>
<p>But that makes it hard to go over the e-mails from start to end ― how
does the program guess the name of these properties? This can be
solved by more predictable property names:</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">mailArchive</span> = {<span class="atom">0</span>: <span class="string">"Dear nephew, ... (mail number 1)"</span>,
<span class="atom">1</span>: <span class="string">"(mail number 2)"</span>,
<span class="atom">2</span>: <span class="string">"(mail number 3)"</span>};
<span class="keyword">for</span> (<span class="keyword">var</span> <span class="variable">current</span> = <span class="atom">0</span>; <span class="variable">current</span> in <span class="variable">mailArchive</span>; <span class="variable">current</span>++)
<span class="variable">print</span>(<span class="string">"Processing e-mail #"</span>, <span class="variable">current</span>, <span class="string">": "</span>, <span class="variable">mailArchive</span>[<span class="variable">current</span>]);</pre>
<p>Luck has it that there is a special kind of objects specifically for this kind of use. They are called <a name="key12"></a>arrays, and they provide some conveniences, such as a <a name="key13"></a><code>length</code> property that contains the amount of values in the array, and a number of operations useful for this kind of collections.</p>
<p><a name="key14"></a>New arrays can be created using brackets (<code>[</code> and <code>]</code>):</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">mailArchive</span> = [<span class="string">"mail one"</span>, <span class="string">"mail two"</span>, <span class="string">"mail three"</span>];
<span class="keyword">for</span> (<span class="keyword">var</span> <span class="variable">current</span> = <span class="atom">0</span>; <span class="variable">current</span> < <span class="variable">mailArchive</span>.<span class="property">length</span>; <span class="variable">current</span>++)
<span class="variable">print</span>(<span class="string">"Processing e-mail #"</span>, <span class="variable">current</span>, <span class="string">": "</span>, <span class="variable">mailArchive</span>[<span class="variable">current</span>]);</pre>
<p>In this example, the numbers of the elements are not specified explicitly anymore. The first one automatically gets the number 0, the second the number 1, and so on.</p>
<p>Why start at 0? People tend to start counting from 1. As unintuitive as it seems, numbering the elements in a collection from 0 is often more practical. Just go with it for now, it will grow on you.</p>
<p>Starting at element 0 also means that in a collection with <code>X</code> elements, the last element can be found at position <code>X - 1</code>. This is why the <code>for</code> loop in the example checks for <code>current < mailArchive.length</code>. There is no element at position <code>mailArchive.length</code>, so as soon as <code>current</code> has that value, we stop looping.</p>
</div><hr/><div class="block">
<a name="exercise2"></a>
<div class="exercisenum">Ex. 4.2</div>
<div class="exercise">
<p>Write a function <code>range</code> that takes one argument, a positive number, and returns an array containing all numbers from 0 up to and including the given number.</p> <p>An empty array can be created by simply typing <code>[]</code>. Also remember that adding properties to an object, and thus also to an array, can be done by assigning them a value with the <code>=</code> operator. The <code>length</code> property is automatically updated when elements are added.</p>
</div>
<div class="solution">
<pre class="code"><span class="keyword">function</span> <span class="variable">range</span>(<span class="variabledef">upto</span>) {
<span class="keyword">var</span> <span class="variabledef">result</span> = [];
<span class="keyword">for</span> (<span class="keyword">var</span> <span class="variabledef">i</span> = <span class="atom">0</span>; <span class="localvariable">i</span> <= <span class="localvariable">upto</span>; <span class="localvariable">i</span>++)
<span class="localvariable">result</span>[<span class="localvariable">i</span>] = <span class="localvariable">i</span>;
<span class="keyword">return</span> <span class="localvariable">result</span>;
}
<span class="variable">show</span>(<span class="variable">range</span>(<span class="atom">4</span>));</pre>
<p>Instead of naming the loop variable <code>counter</code> or <code>current</code>, as I have been doing so far, it is now called simply <code>i</code>. Using single letters, usually <code>i</code>, <code>j</code>, or <code>k</code> for loop variables is a widely spread habit among programmers. It has its origin mostly in laziness: We'd rather type one character than seven, and names like <code>counter</code> and <code>current</code> do not really clarify the meaning of the variable much.</p>
<p>If a program uses too many meaningless single-letter variables, it can become unbelievably confusing. In my own programs, I try to only do this in a few common cases. Small loops are one of these cases. If the loop contains another loop, and that one also uses a variable named <code>i</code>, the inner loop will modify the variable that the outer loop is using, and everything will break. One could use <code>j</code> for the inner loop, but in general, when the body of a loop is big, you should come up with a variable name that has some clear meaning.</p>
</div>
</div><hr/><div class="block">
<p>Both string and array objects contain, in addition to the <code>length</code> property, a number of properties that refer to function values.</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">doh</span> = <span class="string">"Doh"</span>;
<span class="variable">print</span>(typeof <span class="variable">doh</span>.<span class="property">toUpperCase</span>);
<span class="variable">print</span>(<span class="variable">doh</span>.<span class="property">toUpperCase</span>());</pre>
<p>Every string has a <a name="key15"></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 <a name="key16"></a><code>toLowerCase</code>. Guess what that does.</p>
<p>Notice that, even though the call to <code>toUpperCase</code> does not pass any arguments, the function does somehow have access to the string <code>"Doh"</code>, the value of which it is a property. How this works precisely is described in <a href="chapter8.html">chapter 8</a>.</p>
<p>Properties that contain functions are generally called <a name="key17"></a>methods, as in '<code>toUpperCase</code> is a method of a string object'.</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">mack</span> = [];
<span class="variable">mack</span>.<span class="property">push</span>(<span class="string">"Mack"</span>);
<span class="variable">mack</span>.<span class="property">push</span>(<span class="string">"the"</span>);
<span class="variable">mack</span>.<span class="property">push</span>(<span class="string">"Knife"</span>);
<span class="variable">show</span>(<span class="variable">mack</span>.<span class="property">join</span>(<span class="string">" "</span>));
<span class="variable">show</span>(<span class="variable">mack</span>.<span class="property">pop</span>());
<span class="variable">show</span>(<span class="variable">mack</span>);</pre>
<p>The method <a name="key18"></a><code>push</code>, which is associated with arrays, can be used to add values to it. It could have been used in the last exercise, as an alternative to <code>result[i] = i</code>. Then there is <a name="key19"></a><code>pop</code>, the opposite of <code>push</code>: it takes off and returns the last value in the array. <a name="key20"></a><code>join</code> builds a single big string from an array of strings. The parameter it is given is pasted between the values in the array.</p>
</div><hr/><div class="block">
<p>Coming back to those cats, we now know that an array would be a good way to store the archive of e-mails. On this page, the function <code>retrieveMails</code> can be used to (magically) get hold of this array. Going over them to process them one after another is no rocket science anymore either:</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">mailArchive</span> = <span class="variable">retrieveMails</span>();
<span class="keyword">for</span> (<span class="keyword">var</span> <span class="variable">i</span> = <span class="atom">0</span>; <span class="variable">i</span> < <span class="variable">mailArchive</span>.<span class="property">length</span>; <span class="variable">i</span>++) {
<span class="keyword">var</span> <span class="variable">email</span> = <span class="variable">mailArchive</span>[<span class="variable">i</span>];
<span class="variable">print</span>(<span class="string">"Processing e-mail #"</span>, <span class="variable">i</span>);
<span class="comment">// Do more things...</span>
}</pre>
<p>We have also decided on a way to represent the set of cats that are alive. The next problem, then, is to find the paragraphs in an e-mail that start with <code>"born"</code> or <code>"died"</code>.</p>
</div><hr/><div class="block">
<p>The first question that comes up is what exactly a paragraph is. In this case, the string value itself can't help us much: JavaScript's concept of text does not go any deeper than the 'sequence of characters' idea, so we must define paragraphs in those terms.</p>
<p>Earlier, we saw that there is such a thing as a newline character. These are what most people use to split paragraphs. We consider a paragraph, then, to be a part of an e-mail that starts at a newline character or at the start of the content, and ends at the next newline character or at the end of the content.</p>
<p>And we don't even have to write the algorithm for splitting a string into paragraphs ourselves. Strings already have a method named <a name="key21"></a><code>split</code>, which is (almost) the opposite of the <code>join</code> method of arrays. It splits a string into an array, using the string given as its argument to determine in which places to cut.</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">words</span> = <span class="string">"Cities of the Interior"</span>;
<span class="variable">show</span>(<span class="variable">words</span>.<span class="property">split</span>(<span class="string">" "</span>));</pre>
<p>Thus, cutting on newlines (<code>"\n"</code>), can be used to split an e-mail into paragraphs.</p>
</div><hr/><div class="block">
<a name="exercise3"></a>
<div class="exercisenum">Ex. 4.3</div>
<div class="exercise">
<p><code>split</code> and <code>join</code> are not precisely each other's inverse. <code>string.split(x).join(x)</code> always produces the original value, but <code>array.join(x).split(x)</code> does not. Can you give an example of an array where <code>.join(" ").split(" ")</code> produces a different value?</p>
</div>
<div class="solution">
<pre class="code"><span class="keyword">var</span> <span class="variable">array</span> = [<span class="string">"a"</span>, <span class="string">"b"</span>, <span class="string">"c d"</span>];
<span class="variable">show</span>(<span class="variable">array</span>.<span class="property">join</span>(<span class="string">" "</span>).<span class="property">split</span>(<span class="string">" "</span>));</pre>
</div>
</div><hr/><div class="block">
<p>Paragraphs that do not start with either "born" or "died" can be ignored by the program. How do we test whether a string starts with a certain word? The method <a name="key22"></a><code>charAt</code> can be used to get a specific character from a string. <code>x.charAt(0)</code> gives the first character, <code>1</code> is the second one, and so on. One way to check whether a string starts with "born" is:</p>
<pre class="code"><span class="keyword">var</span> <span class="variable">paragraph</span> = <span class="string">"born 15-11-2003 (mother Spot): White Fang"</span>;
<span class="variable">show</span>(<span class="variable">paragraph</span>.<span class="property">charAt</span>(<span class="atom">0</span>) == <span class="string">"b"</span> && <span class="variable">paragraph</span>.<span class="property">charAt</span>(<span class="atom">1</span>) == <span class="string">"o"</span> &&
<span class="variable">paragraph</span>.<span class="property">charAt</span>(<span class="atom">2</span>) == <span class="string">"r"</span> && <span class="variable">paragraph</span>.<span class="property">charAt</span>(<span class="atom">3</span>) == <span class="string">"n"</span>);</pre>
<p>But that gets a bit clumsy ― imagine checking for a word of ten characters. There is something to be learned here though: when a line gets ridiculously long, it can be spread over multiple lines. The result can be made easier to read by lining up the start of the new line with the first element on the original line that plays a similar role.</p>
<p>Strings also have a method called <a name="key23"></a><code>slice</code>. It copies out a piece of the string, starting from the character at the position given by the first argument, and ending before (not including) the character at the position given by the second one. This allows the check to be written in a shorter way.</p>
<pre class="code"><span class="variable">show</span>(<span class="variable">paragraph</span>.<span class="property">slice</span>(<span class="atom">0</span>, <span class="atom">4</span>) == <span class="string">"born"</span>);</pre>
</div><hr/><div class="block">
<a name="exercise4"></a>
<div class="exercisenum">Ex. 4.4</div>