-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path02_program_structure.html
More file actions
723 lines (720 loc) · 60.7 KB
/
02_program_structure.html
File metadata and controls
723 lines (720 loc) · 60.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
<!doctype html>
<head>
<meta charset="utf-8">
<title>Program Structure :: Eloquent JavaScript</title>
<link rel=stylesheet href="js/node_modules/codemirror/lib/codemirror.css">
<script src="js/acorn_codemirror.js"></script>
<link rel=stylesheet href="css/ejs.css">
<script src="js/sandbox.js"></script>
<script src="js/ejs.js"></script>
<script>var chapNum = 2;</script>
</head>
<article>
<nav>
<a href="01_values.html" title="previous chapter">◀</a>
<a href="index.html" title="cover">◆</a>
<a href="03_functions.html" title="next chapter">▶</a>
</nav>
<h1><div class=chap_num>Chapter 2</div>Program Structure</h1>
<blockquote>
<p><a class=p_ident id="p_J/zCYrllfQ" href="#p_J/zCYrllfQ"></a>And my heart glows bright red under my
filmy, translucent skin and they have to administer 10cc of JavaScript
to get me to come back. (I respond well to toxins in the blood.) Man,
that stuff will kick the peaches right out your gills!</p>
<footer>_why, <cite>Why's (Poignant) Guide to Ruby</cite></footer>
</blockquote>
<p><a class=p_ident id="p_x4mfX9d1CF" href="#p_x4mfX9d1CF"></a>In this chapter, we will start to do
things that can actually be called <em>programming</em>. We will expand our
command of the JavaScript language beyond the nouns and sentence
fragments we’ve seen so far, to the point where we can
express some meaningful prose.</p>
<h2><a class=h_ident id="h_5fUOQZwwHx" href="#h_5fUOQZwwHx"></a>Expressions and statements</h2>
<p><a class=p_ident id="p_EuyWCUdM/0" href="#p_EuyWCUdM/0"></a>In
<a href="01_values.html#values">Chapter 1</a>, we made some values and then
applied 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.</p>
<p><a class=p_ident id="p_8CCep1TQ8b" href="#p_8CCep1TQ8b"></a>A fragment of code that produces a value is
called an <em>expression</em>. Every value that is written literally
(such as <code>22</code> or <code>"psychoanalysis"</code>) is an expression. An expression
between parentheses is also an expression, as is a binary operator applied to two expressions or a unary operator applied to
one.</p>
<p><a class=p_ident id="p_QXQG3kVSFh" href="#p_QXQG3kVSFh"></a>This shows part of the
beauty of a language-based interface. Expressions can nest in a way
very similar to the way subsentences in human languages are nested—a
subsentence can contain its own subsentences, and so on. This allows
us to combine expressions to express arbitrarily complex computations.</p>
<p><a class=p_ident id="p_K6OJ6JuFaH" href="#p_K6OJ6JuFaH"></a>If an expression
corresponds to a sentence fragment, a JavaScript <em>statement</em>
corresponds to a full sentence in a human language. A program is
simply a list of statements.</p>
<p><a class=p_ident id="p_NAzxo1M6WC" href="#p_NAzxo1M6WC"></a>The simplest kind of statement is an expression with a
semicolon after it. This is a program:</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_ShAmL4Xddd" href="#c_ShAmL4Xddd"></a><span class="cm-number">1</span>;
<span class="cm-operator">!</span><span class="cm-atom">false</span>;</pre>
<p><a class=p_ident id="p_dj4UvUmws0" href="#p_dj4UvUmws0"></a>It is a useless program, though. An expression can be content to
just produce a value, which can then be used by the enclosing
expression. A statement stands on its own and amounts to something
only if it affects the world. It could display something on the
screen—that counts as changing the world—or it could change the
internal state of the machine in a way that will affect the statements
that come after it. These changes are called <em>side effects</em>. The
statements in the previous example just produce the values <code>1</code> and
<code>true</code> and then immediately throw them away. This leaves no impression
on the world at all. When executing the program, nothing observable
happens.</p>
<p><a class=p_ident id="p_neJqLsvK+g" href="#p_neJqLsvK+g"></a>In some cases, JavaScript allows you to
omit the semicolon at the end of a statement. In other cases, it has
to be there, or the next line will be treated as part of the same
statement. The rules for when it can be safely omitted are somewhat
complex and error-prone. In this book, every statement that needs a
semicolon will always be terminated by one. I recommend you do the
same in your own programs, at least until you’ve learned more about
subtleties involved in leaving out semicolons.</p>
<h2><a class=h_ident id="h_rAGNsfewCX" href="#h_rAGNsfewCX"></a>Variables</h2>
<p><a class=p_ident id="p_i0lKsEoj6z" href="#p_i0lKsEoj6z"></a>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 <em>variable</em>.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_eDAXp+U+Cr" href="#c_eDAXp+U+Cr"></a><span class="cm-keyword">var</span> <span class="cm-variable">caught</span> <span class="cm-operator">=</span> <span class="cm-number">5</span> <span class="cm-operator">*</span> <span class="cm-number">5</span>;</pre>
<p><a class=p_ident id="p_Jhk5gi+tgk" href="#p_Jhk5gi+tgk"></a>And that gives us our second kind of statement.
The special word (<em>keyword</em>) <code>var</code> indicates that this sentence is
going to define a variable. It is followed by the name of the variable
and, if we want to immediately give it a value, by an <code>=</code> operator and
an expression.</p>
<p><a class=p_ident id="p_EkxlfkTaWl" href="#p_EkxlfkTaWl"></a>The previous statement creates a variable called <code>caught</code> and uses it
to grab hold of the number that is produced by multiplying 5 by 5.</p>
<p><a class=p_ident id="p_Fh873D6aQC" href="#p_Fh873D6aQC"></a>After a variable has been defined, its name can be used as an
expression. The value of such an expression is the value the
variable currently holds. Here’s an example:</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_v1fZTgCdHj" href="#c_v1fZTgCdHj"></a><span class="cm-keyword">var</span> <span class="cm-variable">ten</span> <span class="cm-operator">=</span> <span class="cm-number">10</span>;
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">ten</span> <span class="cm-operator">*</span> <span class="cm-variable">ten</span>);
<span class="cm-comment">// → 100</span></pre>
<p><a class=p_ident id="p_TPVvmRq49D" href="#p_TPVvmRq49D"></a>Variable names can be any word that isn’t
a reserved word (such as <code>var</code>). They may not include spaces.
Digits can also be part of variable names—<code>catch22</code> is a valid name,
for example—but the name must not start with a digit. A variable name
cannot include punctuation, except for the characters <code>$</code> and <code>_</code>.</p>
<p><a class=p_ident id="p_ew9BThyy9D" href="#p_ew9BThyy9D"></a>When a
variable points at a value, that does not mean it is tied to that
value forever. The <code>=</code> operator can be used at any time on existing
variables to disconnect them from their current value and have them
point to a new one.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_DgDcf/xkZV" href="#c_DgDcf/xkZV"></a><span class="cm-keyword">var</span> <span class="cm-variable">mood</span> <span class="cm-operator">=</span> <span class="cm-string">"light"</span>;
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">mood</span>);
<span class="cm-comment">// → light</span>
<span class="cm-variable">mood</span> <span class="cm-operator">=</span> <span class="cm-string">"dark"</span>;
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">mood</span>);
<span class="cm-comment">// → dark</span></pre>
<p><a class=p_ident id="p_tdX1rrdcPQ" href="#p_tdX1rrdcPQ"></a>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. A program can access only the values that it still has a
hold on. When you need to remember something, you grow a tentacle to
hold on to it or you reattach one of your existing tentacles to it.</p>
<div class="image">
<img src="img/octopus.jpg" alt="Variables as tentacles">
</div>
<p><a class=p_ident id="p_bJwHD1AmQW" href="#p_bJwHD1AmQW"></a>Let’s look at an example. To remember the number of dollars that Luigi
still owes you, you create a variable. And then when he pays back $35,
you give this variable a new value.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_kgxqlrIFy2" href="#c_kgxqlrIFy2"></a><span class="cm-keyword">var</span> <span class="cm-variable">luigisDebt</span> <span class="cm-operator">=</span> <span class="cm-number">140</span>;
<span class="cm-variable">luigisDebt</span> <span class="cm-operator">=</span> <span class="cm-variable">luigisDebt</span> <span class="cm-operator">-</span> <span class="cm-number">35</span>;
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">luigisDebt</span>);
<span class="cm-comment">// → 105</span></pre>
<p><a class=p_ident id="p_Kti5/Q6NH3" href="#p_Kti5/Q6NH3"></a>When you define a variable without giving it a value,
the tentacle has nothing to grasp, so it ends in thin air. If you ask
for the value of an empty variable, you’ll get the value <code>undefined</code>.</p>
<p><a class=p_ident id="p_/AKSyKwnu0" href="#p_/AKSyKwnu0"></a>A single <code>var</code> statement may define multiple
variables. The definitions must be separated by commas.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_3ZOoKK6DZQ" href="#c_3ZOoKK6DZQ"></a><span class="cm-keyword">var</span> <span class="cm-variable">one</span> <span class="cm-operator">=</span> <span class="cm-number">1</span>, <span class="cm-variable">two</span> <span class="cm-operator">=</span> <span class="cm-number">2</span>;
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">one</span> <span class="cm-operator">+</span> <span class="cm-variable">two</span>);
<span class="cm-comment">// → 3</span></pre>
<h2><a class=h_ident id="h_ko4pqLOTdI" href="#h_ko4pqLOTdI"></a>Keywords and reserved words</h2>
<p><a class=p_ident id="p_GioEDRc+dl" href="#p_GioEDRc+dl"></a>Words with
a special meaning, such as <code>var</code>, are <em>keywords</em>, and they may not
be used as variable names. There are also a number of words that are
“reserved for use” in future versions of JavaScript. These are also
officially not allowed to be used as variable names, though some
JavaScript environments do allow them. The full list of keywords and
reserved words is rather long.</p>
<pre data-language="text/plain" class="snippet cm-s-default"><a class=c_ident id="c_DsAGZZBb8k" href="#c_DsAGZZBb8k"></a>break case catch class const continue debugger
default delete do else enum export extends false
finally for function if implements import in
instanceof interface let new null package private
protected public return static super switch this
throw true try typeof var void while with yield</pre>
<p><a class=p_ident id="p_0pDQHpgrM3" href="#p_0pDQHpgrM3"></a>Don’t worry about memorizing these, but remember that this might be
the problem when a variable definition does not work as expected.</p>
<h2><a class=h_ident id="h_2Tc54fkIgF" href="#h_2Tc54fkIgF"></a>The environment</h2>
<p><a class=p_ident id="p_tJKFexJV/j" href="#p_tJKFexJV/j"></a>The collection of variables and their values
that exist at a given time is called the <em>environment</em>. When a
program starts up, this environment is not empty. It always contains
variables that are part of the language standard, and most of the
time, it has variables that provide ways to interact with the
surrounding system. For example, in a browser, there are variables
and functions to inspect and influence the currently loaded website
and to read mouse and keyboard input.</p>
<h2><a class=h_ident id="h_K5Yd6h3Axg" href="#h_K5Yd6h3Axg"></a>Functions</h2>
<p><a class=p_ident id="p_S7KjMy3yAl" href="#p_S7KjMy3yAl"></a>A lot of the values provided in the
default environment have the type <em>function</em>. A function is a
piece of program wrapped in a value. Such values can be <em>applied</em> in
order to run the wrapped program. For example, in a browser
environment, the variable <code>alert</code> holds a function that shows a little
dialog box with a message. It is used like this:</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_/bha8x/lU5" href="#c_/bha8x/lU5"></a><span class="cm-variable">alert</span>(<span class="cm-string">"Good morning!"</span>);</pre>
<div class="image">
<img src="img/alert.png" alt="An alert dialog">
</div>
<p><a class=p_ident id="p_9qu6Ki2/lH" href="#p_9qu6Ki2/lH"></a>Executing a function is
called <em>invoking</em>, <em>calling</em>, or <em>applying</em> it. You can call a
function by putting parentheses after an expression that produces a
function value. Usually you’ll directly use the name of the variable
that holds the function. The values between the parentheses are given to
the program inside the function. In the example, the <code>alert</code> function
uses the string that we give it as the text to show in the dialog box.
Values given to functions are called <em>arguments</em>. The <code>alert</code>
function needs only one of them, but other functions might need a
different number or different types of arguments.</p>
<h2><a class=h_ident id="h_6+Vb3XQoaa" href="#h_6+Vb3XQoaa"></a>The console.log function</h2>
<p><a class=p_ident id="p_HDjV1sA8vQ" href="#p_HDjV1sA8vQ"></a>The <code>alert</code> function
can be useful as an output device when experimenting, but clicking
away all those little windows will get on your nerves. In past
examples, we’ve used <code>console.log</code> to output values. Most JavaScript
systems (including all modern web browsers and Node.js) provide a
<code>console.log</code> function that writes out its arguments to <em>some</em> text
output device. In browsers, the output lands in the JavaScript console. This part of the browser interface is hidden by default,
but most browsers open it when you press F12 or, on Mac, when you
press Command-Option-I. If that does not work, search through the
menus for an item named “web console” or “developer tools”.</p>
<p><a class=p_ident id="p_bTfrhpuIIt" href="#p_bTfrhpuIIt"></a>When running the examples, or your own code, on the pages of this
book, <code>console.log</code> output will be shown after the example, instead of
in the browser’s JavaScript console.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_X1fO5elRqd" href="#c_X1fO5elRqd"></a><span class="cm-keyword">var</span> <span class="cm-variable">x</span> <span class="cm-operator">=</span> <span class="cm-number">30</span>;
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"the value of x is"</span>, <span class="cm-variable">x</span>);
<span class="cm-comment">// → the value of x is 30</span></pre>
<p><a class=p_ident id="p_lKC7MRhfz2" href="#p_lKC7MRhfz2"></a>Though variable names cannot contain period characters, <code>console.log</code> clearly has one. This is because
<code>console.log</code> isn’t a simple variable. It is actually an expression
that retrieves the <code>log</code> property from the value held by the
<code>console</code> variable. We will find out exactly what this means in
<a href="04_data.html#properties">Chapter 4</a>.</p>
<h2 id="return_values"><a class=h_ident id="h_nULi9znEdr" href="#h_nULi9znEdr"></a>Return values</h2>
<p><a class=p_ident id="p_cJD1JUU5+H" href="#p_cJD1JUU5+H"></a>Showing a dialog box or writing text to
the screen is a <em>side effect</em>. A lot of functions are useful
because of the side effects they produce. Functions may also produce
values, and in that case, they don’t need to have a side effect to be
useful. For example, the function <code>Math.max</code> takes any number of
number values and gives back the greatest.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_KDqbDlOaSI" href="#c_KDqbDlOaSI"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">Math</span>.<span class="cm-property">max</span>(<span class="cm-number">2</span>, <span class="cm-number">4</span>));
<span class="cm-comment">// → 4</span></pre>
<p><a class=p_ident id="p_n4ne85oslE" href="#p_n4ne85oslE"></a>When a function produces a value, it is said to <em>return</em>
that value. Anything that produces a value is an expression in
JavaScript, which means function calls can be used within larger
expressions. Here a call to <code>Math.min</code>, which is the opposite of
<code>Math.max</code>, is used as an input to the plus operator:</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_huNtX2skdz" href="#c_huNtX2skdz"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">Math</span>.<span class="cm-property">min</span>(<span class="cm-number">2</span>, <span class="cm-number">4</span>) <span class="cm-operator">+</span> <span class="cm-number">100</span>);
<span class="cm-comment">// → 102</span></pre>
<p><a class=p_ident id="p_bhFVJn8rDc" href="#p_bhFVJn8rDc"></a>The <a href="03_functions.html#functions">next chapter</a> explains how to
write your own functions.</p>
<h2><a class=h_ident id="h_1nddjRgQ5+" href="#h_1nddjRgQ5+"></a>prompt and confirm</h2>
<p><a class=p_ident id="p_tJIGQUSpum" href="#p_tJIGQUSpum"></a>Browser
environments contain other functions besides <code>alert</code> for popping up
windows. You can ask the user an OK/Cancel question using
<code>confirm</code>. This returns a Boolean: <code>true</code> if the user clicks OK and
<code>false</code> if the user clicks Cancel.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_8+qosPEiZf" href="#c_8+qosPEiZf"></a><span class="cm-variable">confirm</span>(<span class="cm-string">"Shall we, then?"</span>);</pre>
<div class="image">
<img src="img/confirm.png" alt="A confirm dialog">
</div>
<p><a class=p_ident id="p_+abQLgqQ+O" href="#p_+abQLgqQ+O"></a>The <code>prompt</code> function
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 dialog window, and the function will
return this text as a string.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_zvjwz8HPIq" href="#c_zvjwz8HPIq"></a><span class="cm-variable">prompt</span>(<span class="cm-string">"Tell me everything you know."</span>, <span class="cm-string">"..."</span>);</pre>
<div class="image">
<img src="img/prompt.png" alt="An prompt dialog">
</div>
<p><a class=p_ident id="p_mGjwXljToy" href="#p_mGjwXljToy"></a>These two functions aren’t used much in modern web programming, mostly
because you have no control over the way the resulting windows look,
but they are useful for toy programs and experiments.</p>
<h2><a class=h_ident id="h_rDxYNPd65Z" href="#h_rDxYNPd65Z"></a>Control flow</h2>
<p><a class=p_ident id="p_QdCrOXOgYy" href="#p_QdCrOXOgYy"></a>When your program
contains more than one statement, the statements are executed,
predictably, from top to bottom. As a basic example, this program has
two statements. The first one asks the user for a number, and the
second, which is executed afterward, shows the square of that
number.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_vMmSZhI46K" href="#c_vMmSZhI46K"></a><span class="cm-keyword">var</span> <span class="cm-variable">theNumber</span> <span class="cm-operator">=</span> <span class="cm-variable">Number</span>(<span class="cm-variable">prompt</span>(<span class="cm-string">"Pick a number"</span>, <span class="cm-string">""</span>));
<span class="cm-variable">alert</span>(<span class="cm-string">"Your number is the square root of "</span> <span class="cm-operator">+</span>
<span class="cm-variable">theNumber</span> <span class="cm-operator">*</span> <span class="cm-variable">theNumber</span>);</pre>
<p><a class=p_ident id="p_aq3OoDkq71" href="#p_aq3OoDkq71"></a>The function <code>Number</code> converts a
value to a number. We need that conversion because the result of
<code>prompt</code> is a string value, and we want a number. There are similar
functions called <code>String</code> and <code>Boolean</code> that convert values to those
types.</p>
<p><a class=p_ident id="p_M37XqCwh0I" href="#p_M37XqCwh0I"></a>Here is the rather trivial schematic representation of straight
control flow:</p>
<div class="image">
<img src="img/controlflow-straight.svg" alt="Trivial control flow">
</div>
<h2><a class=h_ident id="h_wpz5oi2dy7" href="#h_wpz5oi2dy7"></a>Conditional execution</h2>
<p><a class=p_ident id="p_u+xpyPmLV8" href="#p_u+xpyPmLV8"></a>Executing statements in straight-line
order isn’t the only option we have. An alternative is <em>conditional execution</em>, where we choose between two different routes based on a
Boolean value, like this:</p>
<div class="image">
<img src="img/controlflow-if.svg" alt="Conditional control flow">
</div>
<p><a class=p_ident id="p_+kdDcK9eLo" href="#p_+kdDcK9eLo"></a>Conditional execution
is written with the <code>if</code> keyword in JavaScript. In the simple case, we
just want some code to be executed if, and only if, a certain
condition holds. For example, in the previous program, we might want
to show the square of the input only if the input is actually a
number.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_DPOOzOEZf+" href="#c_DPOOzOEZf+"></a><span class="cm-keyword">var</span> <span class="cm-variable">theNumber</span> <span class="cm-operator">=</span> <span class="cm-variable">Number</span>(<span class="cm-variable">prompt</span>(<span class="cm-string">"Pick a number"</span>, <span class="cm-string">""</span>));
<span class="cm-keyword">if</span> (<span class="cm-operator">!</span><span class="cm-variable">isNaN</span>(<span class="cm-variable">theNumber</span>))
<span class="cm-variable">alert</span>(<span class="cm-string">"Your number is the square root of "</span> <span class="cm-operator">+</span>
<span class="cm-variable">theNumber</span> <span class="cm-operator">*</span> <span class="cm-variable">theNumber</span>);</pre>
<p><a class=p_ident id="p_d0Z3YQB6e1" href="#p_d0Z3YQB6e1"></a>With this modification, if you enter “cheese”, no output will be shown.</p>
<p><a class=p_ident id="p_QqE0pn6CUK" href="#p_QqE0pn6CUK"></a>The keyword <code>if</code> executes or skips a statement depending on the value
of a Boolean expression. The deciding expression is written after the
keyword, between parentheses, followed by the statement to execute.</p>
<p><a class=p_ident id="p_nJcsWbCJmU" href="#p_nJcsWbCJmU"></a>The <code>isNaN</code> function is a standard JavaScript
function that returns <code>true</code> only if the argument it is given is
<code>NaN</code>. The <code>Number</code> function happens to return <code>NaN</code> when you give it
a string that doesn’t represent a valid number. Thus, the condition
translates to “unless <code>theNumber</code> is not-a-number, do this”.</p>
<p><a class=p_ident id="p_l1EGERvXxU" href="#p_l1EGERvXxU"></a>You often won’t just have code that executes when a
condition holds true, but also code that handles the other case. This
alternate path is represented by the second arrow in the
diagram. The <code>else</code> keyword can be used, together with <code>if</code>, to create
two separate, alternative execution paths.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_2BC2dE/U8L" href="#c_2BC2dE/U8L"></a><span class="cm-keyword">var</span> <span class="cm-variable">theNumber</span> <span class="cm-operator">=</span> <span class="cm-variable">Number</span>(<span class="cm-variable">prompt</span>(<span class="cm-string">"Pick a number"</span>, <span class="cm-string">""</span>));
<span class="cm-keyword">if</span> (<span class="cm-operator">!</span><span class="cm-variable">isNaN</span>(<span class="cm-variable">theNumber</span>))
<span class="cm-variable">alert</span>(<span class="cm-string">"Your number is the square root of "</span> <span class="cm-operator">+</span>
<span class="cm-variable">theNumber</span> <span class="cm-operator">*</span> <span class="cm-variable">theNumber</span>);
<span class="cm-keyword">else</span>
<span class="cm-variable">alert</span>(<span class="cm-string">"Hey. Why didn't you give me a number?"</span>);</pre>
<p><a class=p_ident id="p_ZmJjq4NvCB" href="#p_ZmJjq4NvCB"></a>If we have more than two paths to choose
from, multiple <code>if</code>/<code>else</code> pairs can be “chained” together. Here’s an
example:</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_9aykimugCx" href="#c_9aykimugCx"></a><span class="cm-keyword">var</span> <span class="cm-variable">num</span> <span class="cm-operator">=</span> <span class="cm-variable">Number</span>(<span class="cm-variable">prompt</span>(<span class="cm-string">"Pick a number"</span>, <span class="cm-string">"0"</span>));
<span class="cm-keyword">if</span> (<span class="cm-variable">num</span> <span class="cm-operator"><</span> <span class="cm-number">10</span>)
<span class="cm-variable">alert</span>(<span class="cm-string">"Small"</span>);
<span class="cm-keyword">else</span> <span class="cm-keyword">if</span> (<span class="cm-variable">num</span> <span class="cm-operator"><</span> <span class="cm-number">100</span>)
<span class="cm-variable">alert</span>(<span class="cm-string">"Medium"</span>);
<span class="cm-keyword">else</span>
<span class="cm-variable">alert</span>(<span class="cm-string">"Large"</span>);</pre>
<p><a class=p_ident id="p_6w2546HxbK" href="#p_6w2546HxbK"></a>The program will first check whether <code>num</code> is less than 10. If it is,
it chooses that branch, shows <code>"Small"</code>, and is done. If it isn’t, it
takes the <code>else</code> branch, which itself contains a second <code>if</code>. If the
second condition (<code>< 100</code>) holds, that means the number is between 10
and 100, and <code>"Medium"</code> is shown. If it doesn’t, the second, and last,
<code>else</code> branch is chosen.</p>
<p><a class=p_ident id="p_JniuPPdJZD" href="#p_JniuPPdJZD"></a>The flow chart for this program looks something like this:</p>
<div class="image">
<img src="img/controlflow-nested-if.svg" alt="Nested if control flow">
</div>
<h2 id="loops"><a class=h_ident id="h_FaGGgUI+MM" href="#h_FaGGgUI+MM"></a>while and do loops</h2>
<p><a class=p_ident id="p_FIHE6k56BA" href="#p_FIHE6k56BA"></a>Consider a program that prints all even numbers from
0 to 12. One way to write this is as follows:</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_ciaCwGgFZR" href="#c_ciaCwGgFZR"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-number">0</span>);
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-number">2</span>);
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-number">4</span>);
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-number">6</span>);
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-number">8</span>);
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-number">10</span>);
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-number">12</span>);</pre>
<p><a class=p_ident id="p_r1EVilCb9Y" href="#p_r1EVilCb9Y"></a>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
less than 1,000, the previous would be unworkable. What we need is a
way to repeat some code. This form of control flow is called a
<em>loop</em>:</p>
<div class="image">
<img src="img/controlflow-loop.svg" alt="Loop control flow">
</div>
<p><a class=p_ident id="p_1PXG58nhBq" href="#p_1PXG58nhBq"></a>Looping control flow allows us to go
back to some point in the program where we were before and repeat it
with our current program state. If we combine this with a variable
that counts, we can do something like this:</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_VdVRvg/hoC" href="#c_VdVRvg/hoC"></a><span class="cm-keyword">var</span> <span class="cm-variable">number</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>;
<span class="cm-keyword">while</span> (<span class="cm-variable">number</span> <span class="cm-operator"><=</span> <span class="cm-number">12</span>) {
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">number</span>);
<span class="cm-variable">number</span> <span class="cm-operator">=</span> <span class="cm-variable">number</span> <span class="cm-operator">+</span> <span class="cm-number">2</span>;
}
<span class="cm-comment">// → 0</span>
<span class="cm-comment">// → 2</span>
<span class="cm-comment">// … etcetera</span></pre>
<p><a class=p_ident id="p_tCSkGQTO9J" href="#p_tCSkGQTO9J"></a>A statement starting with the
keyword <code>while</code> creates a loop. The word <code>while</code> is followed by an
expression in parentheses and then a statement, much like <code>if</code>.
The loop executes that statement as long as the expression produces a
value that is <code>true</code> when converted to Boolean type.</p>
<p><a class=p_ident id="p_iwEcAR3f0a" href="#p_iwEcAR3f0a"></a>In this loop, we want to both
print the current number and add two to our variable. Whenever we need
to execute multiple statements inside a loop, we wrap them in
curly braces (<code>{</code> and <code>}</code>). Braces do for statements what
parentheses do for expressions: they group them together, making
them count as a single statement. A sequence of statements wrapped in
braces is called a <em>block</em>.</p>
<p><a class=p_ident id="p_UxO2K/wbSG" href="#p_UxO2K/wbSG"></a>Many JavaScript programmers wrap every single
loop or <code>if</code> body in braces. They do this both for the sake of
consistency and to avoid having to add or remove braces when changing
the number of statements in the body later. In this book, I will write
most single-statement bodies without braces, since I value brevity.
You are free to go with whichever style you prefer.</p>
<p><a class=p_ident id="p_5AsEqW7qSx" href="#p_5AsEqW7qSx"></a>The variable <code>number</code> demonstrates the way
a variable can track the progress of a program. Every time the
loop repeats, <code>number</code> is incremented by <code>2</code>. Then, at the beginning
of every repetition, it is compared with the number <code>12</code> to decide
whether the program has done all the work it intended to do.</p>
<p><a class=p_ident id="p_eimxKSJFYF" href="#p_eimxKSJFYF"></a>As an example that actually does something useful,
we can now write a program that calculates and shows the value of
2<sup>10</sup> (2 to the 10th power). We use two variables: one to keep
track of our result and one to count how often we have multiplied this
result by 2. The loop tests whether the second variable has reached 10
yet and then updates both variables.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_Ec0TnYkpCa" href="#c_Ec0TnYkpCa"></a><span class="cm-keyword">var</span> <span class="cm-variable">result</span> <span class="cm-operator">=</span> <span class="cm-number">1</span>;
<span class="cm-keyword">var</span> <span class="cm-variable">counter</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>;
<span class="cm-keyword">while</span> (<span class="cm-variable">counter</span> <span class="cm-operator"><</span> <span class="cm-number">10</span>) {
<span class="cm-variable">result</span> <span class="cm-operator">=</span> <span class="cm-variable">result</span> <span class="cm-operator">*</span> <span class="cm-number">2</span>;
<span class="cm-variable">counter</span> <span class="cm-operator">=</span> <span class="cm-variable">counter</span> <span class="cm-operator">+</span> <span class="cm-number">1</span>;
}
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">result</span>);
<span class="cm-comment">// → 1024</span></pre>
<p><a class=p_ident id="p_MERlXZu4+T" href="#p_MERlXZu4+T"></a>The counter could also start at <code>1</code> and check for <code><= 10</code>, but, for
reasons that will become apparent in
<a href="04_data.html#array_indexing">Chapter 4</a>, it is a good idea to get
used to counting from 0.</p>
<p><a class=p_ident id="p_vrOESKfZl/" href="#p_vrOESKfZl/"></a>The <code>do</code> loop is a
control structure similar to the <code>while</code> loop. It differs only on one
point: a <code>do</code> loop always executes its body at least once, and it
starts testing whether it should stop only after that first execution.
To reflect this, the test appears after the body of the loop:</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_WhNPkjCnm1" href="#c_WhNPkjCnm1"></a><span class="cm-keyword">do</span> {
<span class="cm-keyword">var</span> <span class="cm-variable">yourName</span> <span class="cm-operator">=</span> <span class="cm-variable">prompt</span>(<span class="cm-string">"Who are you?"</span>);
} <span class="cm-keyword">while</span> (<span class="cm-operator">!</span><span class="cm-variable">yourName</span>);
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">yourName</span>);</pre>
<p><a class=p_ident id="p_gpU7uCWE2q" href="#p_gpU7uCWE2q"></a>This program will
force you to enter a name. It will ask again and again until it gets
something that is not an empty string. Applying the <code>!</code> operator will
convert a value to Boolean type before negating it, and all strings
except <code>""</code> convert to <code>true</code>. This means the loop continues going round
until you provide a name that is not the empty string.</p>
<h2><a class=h_ident id="h_3I0M2f1Cmh" href="#h_3I0M2f1Cmh"></a>Indenting Code</h2>
<p><a class=p_ident id="p_GLz5olRt8V" href="#p_GLz5olRt8V"></a>You’ve probably noticed the spaces I put in front of some
statements. In JavaScript, 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 a program as a single
long line if you felt like it. The role of the indentation inside
blocks is to make the structure of the code stand out. In complex
code, where new blocks are opened inside other blocks, it can become
hard to see where one block ends and another begins. With proper
indentation, the visual shape of a program corresponds to the shape of
the blocks inside it. I like to use two spaces for every open block,
but tastes differ—some people use four spaces, and some people use
tab characters.</p>
<h2><a class=h_ident id="h_oupMC+5FKN" href="#h_oupMC+5FKN"></a>for loops</h2>
<p><a class=p_ident id="p_t55fBgZ9ww" href="#p_t55fBgZ9ww"></a>Many loops follow
the pattern seen in the previous <code>while</code> examples. First, a “counter”
variable is created to track the progress of the loop. Then comes a
<code>while</code> loop, whose test expression usually checks whether the counter
has reached some boundary yet. At the end of the loop body, the
counter is updated to track progress.</p>
<p><a class=p_ident id="p_i8KoivP+MV" href="#p_i8KoivP+MV"></a>Because this pattern is so common, JavaScript and
similar languages provide a slightly shorter and more comprehensive
form, the <code>for</code> loop.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_3Azuln38qw" href="#c_3Azuln38qw"></a><span class="cm-keyword">for</span> (<span class="cm-keyword">var</span> <span class="cm-variable">number</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>; <span class="cm-variable">number</span> <span class="cm-operator"><=</span> <span class="cm-number">12</span>; <span class="cm-variable">number</span> <span class="cm-operator">=</span> <span class="cm-variable">number</span> <span class="cm-operator">+</span> <span class="cm-number">2</span>)
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">number</span>);
<span class="cm-comment">// → 0</span>
<span class="cm-comment">// → 2</span>
<span class="cm-comment">// … etcetera</span></pre>
<p><a class=p_ident id="p_dGpYwDLcUj" href="#p_dGpYwDLcUj"></a>This program is exactly equivalent to the
<a href="02_program_structure.html#loops">earlier</a> even-number-printing
example. The only change is that all the statements that are
related to the “state” of the loop are now grouped together.</p>
<p><a class=p_ident id="p_LW20YJQoF9" href="#p_LW20YJQoF9"></a>The parentheses after a <code>for</code> keyword must contain two
semicolons. The part before the first semicolon <em>initializes</em> the
loop, usually by defining a variable. The second part is the
expression that <em>checks</em> whether the loop must continue. The final
part <em>updates</em> the state of the loop after every iteration. In most
cases, this is shorter and clearer than a <code>while</code> construct.</p>
<p><a class=p_ident id="p_Rst5RlpePZ" href="#p_Rst5RlpePZ"></a>Here is the code that computes 2<sup>10</sup>, using <code>for</code>
instead of <code>while</code>:</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_0irNU0p0MR" href="#c_0irNU0p0MR"></a><span class="cm-keyword">var</span> <span class="cm-variable">result</span> <span class="cm-operator">=</span> <span class="cm-number">1</span>;
<span class="cm-keyword">for</span> (<span class="cm-keyword">var</span> <span class="cm-variable">counter</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>; <span class="cm-variable">counter</span> <span class="cm-operator"><</span> <span class="cm-number">10</span>; <span class="cm-variable">counter</span> <span class="cm-operator">=</span> <span class="cm-variable">counter</span> <span class="cm-operator">+</span> <span class="cm-number">1</span>)
<span class="cm-variable">result</span> <span class="cm-operator">=</span> <span class="cm-variable">result</span> <span class="cm-operator">*</span> <span class="cm-number">2</span>;
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">result</span>);
<span class="cm-comment">// → 1024</span></pre>
<p><a class=p_ident id="p_pNim3UxKW2" href="#p_pNim3UxKW2"></a>Note that even though 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 before it.</p>
<h2><a class=h_ident id="h_WWKAoSPJ47" href="#h_WWKAoSPJ47"></a>Breaking Out of a Loop</h2>
<p><a class=p_ident id="p_ct/RAqWly8" href="#p_ct/RAqWly8"></a>Having the loop’s
condition produce <code>false</code> is not the only way a loop can finish. There
is a special statement called <code>break</code> that has the effect of
immediately jumping out of the enclosing loop.</p>
<p><a class=p_ident id="p_Vnm45Nv5hS" href="#p_Vnm45Nv5hS"></a>This program illustrates the <code>break</code> statement. It finds the first number
that is both greater than or equal to 20 and divisible by 7.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_7paajfWUVm" href="#c_7paajfWUVm"></a><span class="cm-keyword">for</span> (<span class="cm-keyword">var</span> <span class="cm-variable">current</span> <span class="cm-operator">=</span> <span class="cm-number">20</span>; ; <span class="cm-variable">current</span><span class="cm-operator">++</span>) {
<span class="cm-keyword">if</span> (<span class="cm-variable">current</span> <span class="cm-operator">%</span> <span class="cm-number">7</span> <span class="cm-operator">==</span> <span class="cm-number">0</span>)
<span class="cm-keyword">break</span>;
}
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">current</span>);
<span class="cm-comment">// → 21</span></pre>
<p><a class=p_ident id="p_6KpM9sBZ2r" href="#p_6KpM9sBZ2r"></a>Using the remainder
(<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 is zero.</p>
<p><a class=p_ident id="p_3UnZkFW7lj" href="#p_3UnZkFW7lj"></a>The <code>for</code> construct in the example does not have a part
that checks for the end of the loop. This means that the loop will
never stop unless the <code>break</code> statement inside is executed.</p>
<p><a class=p_ident id="p_2mGltrXORo" href="#p_2mGltrXORo"></a>If you were to leave out that <code>break</code> statement or accidentally write
a condition that always produces <code>true</code>, your program would get stuck
in an <em>infinite loop</em>. A program stuck in an infinite loop will
never finish running, which is usually a bad thing.</p>
<p><a class=p_ident id="p_0F9xH2r4jT" href="#p_0F9xH2r4jT"></a>If you create an infinite loop in one of the examples on these pages,
you’ll usually be asked whether you want to stop the script after a
few seconds. If that fails, you will have to close the tab that you’re
working in, or on some browsers close your whole browser, in order to
recover.</p>
<p><a class=p_ident id="p_f7LsUmJq1I" href="#p_f7LsUmJq1I"></a>The <code>continue</code> keyword is similar to <code>break</code>, in
that it influences the progress of a loop. When <code>continue</code> is
encountered in a loop body, control jumps out of the body and
continues with the loop’s next iteration.</p>
<h2><a class=h_ident id="h_TGUhwjSkqm" href="#h_TGUhwjSkqm"></a>Updating variables succinctly</h2>
<p><a class=p_ident id="p_4XaFXVHI9b" href="#p_4XaFXVHI9b"></a>Especially
when looping, a program often needs to “update” a variable to hold a
value based on that variable’s previous value.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_2I9qAKEFto" href="#c_2I9qAKEFto"></a><span class="cm-variable">counter</span> <span class="cm-operator">=</span> <span class="cm-variable">counter</span> <span class="cm-operator">+</span> <span class="cm-number">1</span>;</pre>
<p><a class=p_ident id="p_n9PMtWEgzN" href="#p_n9PMtWEgzN"></a>JavaScript provides a shortcut for this:</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_+5YpCv/iKG" href="#c_+5YpCv/iKG"></a><span class="cm-variable">counter</span> <span class="cm-operator">+=</span> <span class="cm-number">1</span>;</pre>
<p><a class=p_ident id="p_3IlWnnMlMo" href="#p_3IlWnnMlMo"></a>Similar shortcuts work for many other operators, such as <code>result *= 2</code> to
double <code>result</code> or <code>counter -= 1</code> to count downward.</p>
<p><a class=p_ident id="p_+odXBLNKvV" href="#p_+odXBLNKvV"></a>This allows us to shorten our counting example a little more.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_tBGVwznf7K" href="#c_tBGVwznf7K"></a><span class="cm-keyword">for</span> (<span class="cm-keyword">var</span> <span class="cm-variable">number</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>; <span class="cm-variable">number</span> <span class="cm-operator"><=</span> <span class="cm-number">12</span>; <span class="cm-variable">number</span> <span class="cm-operator">+=</span> <span class="cm-number">2</span>)
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">number</span>);</pre>
<p><a class=p_ident id="p_jpGEbhH1GX" href="#p_jpGEbhH1GX"></a>For <code>counter += 1</code> and <code>counter -=
1</code>, there are even shorter equivalents: <code>counter++</code> and <code>counter--</code>.</p>
<h2><a class=h_ident id="h_jMKsa0SXdL" href="#h_jMKsa0SXdL"></a>Dispatching on a value with switch</h2>
<p><a class=p_ident id="p_t3Fw/3tp0F" href="#p_t3Fw/3tp0F"></a>It is common for code to look like this:</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_A9TwfNNqCW" href="#c_A9TwfNNqCW"></a><span class="cm-keyword">if</span> (<span class="cm-variable">variable</span> <span class="cm-operator">==</span> <span class="cm-string">"value1"</span>) <span class="cm-variable">action1</span>();
<span class="cm-keyword">else</span> <span class="cm-keyword">if</span> (<span class="cm-variable">variable</span> <span class="cm-operator">==</span> <span class="cm-string">"value2"</span>) <span class="cm-variable">action2</span>();
<span class="cm-keyword">else</span> <span class="cm-keyword">if</span> (<span class="cm-variable">variable</span> <span class="cm-operator">==</span> <span class="cm-string">"value3"</span>) <span class="cm-variable">action3</span>();
<span class="cm-keyword">else</span> <span class="cm-variable">defaultAction</span>();</pre>
<p><a class=p_ident id="p_NAtglzdIez" href="#p_NAtglzdIez"></a>There is a construct called
<code>switch</code> that is intended to solve such a “dispatch” in a more direct
way. Unfortunately, the syntax JavaScript uses for this (which it
inherited from the C/Java line of programming languages) is somewhat
awkward—a chain of <code>if</code> statements often looks better. Here is an
example:</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_algpo6jq8U" href="#c_algpo6jq8U"></a><span class="cm-keyword">switch</span> (<span class="cm-variable">prompt</span>(<span class="cm-string">"What is the weather like?"</span>)) {
<span class="cm-keyword">case</span> <span class="cm-string">"rainy"</span>:
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"Remember to bring an umbrella."</span>);
<span class="cm-keyword">break</span>;
<span class="cm-keyword">case</span> <span class="cm-string">"sunny"</span>:
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"Dress lightly."</span>);
<span class="cm-keyword">case</span> <span class="cm-string">"cloudy"</span>:
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"Go outside."</span>);
<span class="cm-keyword">break</span>;
<span class="cm-keyword">default</span>:
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"Unknown weather type!"</span>);
<span class="cm-keyword">break</span>;
}</pre>
<p><a class=p_ident id="p_25X42G30Nq" href="#p_25X42G30Nq"></a>You may put any number of <code>case</code> labels
inside the block opened by <code>switch</code>. The program will jump to the
label that corresponds to the value that <code>switch</code> was given or to
<code>default</code> if no matching value is found. It starts executing
statements there, even if they’re under another label, until it
reaches a <code>break</code> statement. In some cases, such as the <code>"sunny"</code> case
in the example, this can be used to share some code between cases (it
recommends going outside for both sunny and cloudy weather). But
beware: it is easy to forget such a <code>break</code>, which will cause the
program to execute code you do not want executed.</p>
<h2><a class=h_ident id="h_t54vuASjLD" href="#h_t54vuASjLD"></a>Capitalization</h2>
<p><a class=p_ident id="p_3D9T5AdSU0" href="#p_3D9T5AdSU0"></a>Variable
names may not contain spaces, yet it is often helpful to use multiple
words to clearly describe what the variable represents. These are
pretty much your choices for writing a variable name with several
words in it:</p>
<pre>fuzzylittleturtle
fuzzy_little_turtle
FuzzyLittleTurtle
fuzzyLittleTurtle</pre>
<p><a class=p_ident id="p_iHeX2bOrpK" href="#p_iHeX2bOrpK"></a>The
first style can be hard to read. Personally, I like the look of the
underscores, though that style is a little painful to type. The
standard JavaScript functions, and most JavaScript programmers,
follow the bottom style—they capitalize every word except the first.
It is not hard to get used to little things like that, and code with
mixed naming styles can be jarring to read, so we will just follow
this convention.</p>
<p><a class=p_ident id="p_zMlRK/pymj" href="#p_zMlRK/pymj"></a>In a few cases, such as the
<code>Number</code> function, the first letter of a variable is also capitalized.
This was done to mark this function as a constructor. What a
constructor is will become clear in
<a href="06_object.html#constructors">Chapter 6</a>. For now, the important
thing is not to be bothered by this apparent lack of consistency.</p>
<h2><a class=h_ident id="h_/OBuIOX390" href="#h_/OBuIOX390"></a>Comments</h2>
<p><a class=p_ident id="p_0/Ms9AYRwI" href="#p_0/Ms9AYRwI"></a>Often, raw code does not convey all the information
you want a program to convey to human readers, or it conveys it in
such a cryptic way that people might not understand it. At other
times, you might just feel poetic or want to include some thoughts as
part of your program. This is what <em>comments</em> are for.</p>
<p><a class=p_ident id="p_c5N0ebF2ts" href="#p_c5N0ebF2ts"></a>A comment is a piece of text
that is part of a program but is completely ignored by the computer.
JavaScript has two ways of writing comments. To write a single-line
comment, you can use two slash characters (<code>//</code>) and then the comment
text after it.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_0ZikuiZ4zg" href="#c_0ZikuiZ4zg"></a><span class="cm-keyword">var</span> <span class="cm-variable">accountBalance</span> <span class="cm-operator">=</span> <span class="cm-variable">calculateBalance</span>(<span class="cm-variable">account</span>);
<span class="cm-comment">// It's a green hollow where a river sings</span>
<span class="cm-variable">accountBalance</span>.<span class="cm-property">adjust</span>();
<span class="cm-comment">// Madly catching white tatters in the grass.</span>
<span class="cm-keyword">var</span> <span class="cm-variable">report</span> <span class="cm-operator">=</span> <span class="cm-keyword">new</span> <span class="cm-variable">Report</span>();
<span class="cm-comment">// Where the sun on the proud mountain rings:</span>
<span class="cm-variable">addToReport</span>(<span class="cm-variable">accountBalance</span>, <span class="cm-variable">report</span>);
<span class="cm-comment">// It's a little valley, foaming like light in a glass.</span></pre>
<p><a class=p_ident id="p_UD6DcJKN/S" href="#p_UD6DcJKN/S"></a>A <code>//</code> comment goes only to the end of the line. A
section of text between <code>/*</code> and <code>*/</code> will be ignored, regardless of
whether it contains line breaks. This is often useful for adding
blocks of information about a file or a chunk of program.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_qmmXe1V0mf" href="#c_qmmXe1V0mf"></a><span class="cm-comment">/*</span>
<span class="cm-comment"> I first found this number scrawled on the back of one of</span>
<span class="cm-comment"> my notebooks a few years ago. Since then, it has often</span>
<span class="cm-comment"> dropped by, showing up in phone numbers and the serial</span>
<span class="cm-comment"> numbers of products that I've bought. It obviously likes</span>
<span class="cm-comment"> me, so I've decided to keep it.</span>
<span class="cm-comment">*/</span>
<span class="cm-keyword">var</span> <span class="cm-variable">myNumber</span> <span class="cm-operator">=</span> <span class="cm-number">11213</span>;</pre>
<h2><a class=h_ident id="h_ErccPg/l98" href="#h_ErccPg/l98"></a>Summary</h2>
<p><a class=p_ident id="p_qenTzu+nvg" href="#p_qenTzu+nvg"></a>You now know that a program is built out of statements, which
themselves sometimes contain more statements. Statements tend to
contain expressions, which themselves can be built out of smaller
expressions.</p>
<p><a class=p_ident id="p_KbysBfaBh4" href="#p_KbysBfaBh4"></a>Putting statements after one another gives you a program that is
executed from top to bottom. You can introduce disturbances in the
flow of control by using conditional (<code>if</code>, <code>else</code>, and <code>switch</code>) and
looping (<code>while</code>, <code>do</code>, and <code>for</code>) statements.</p>
<p><a class=p_ident id="p_cDVCQB0d+r" href="#p_cDVCQB0d+r"></a>Variables can be used to file pieces of data under a name, and they
are useful for tracking state in your program. The environment is the
set of variables that are defined. JavaScript systems
always put a number of useful standard variables into your
environment.</p>
<p><a class=p_ident id="p_zgNEy0za9M" href="#p_zgNEy0za9M"></a>Functions are special values that encapsulate a piece of program. You
can invoke them by writing <code>functionName(argument1, argument2)</code>. Such
a function call is an expression, and may produce a value.</p>
<h2><a class=h_ident id="h_TcUD2vzyMe" href="#h_TcUD2vzyMe"></a>Exercises</h2>
<p><a class=p_ident id="p_Uj/Ehlt+c3" href="#p_Uj/Ehlt+c3"></a>If you are unsure how to try your solutions to
exercises, refer to the <a href="00_intro.html#intro">introduction</a>.</p>
<p><a class=p_ident id="p_VR0+805/R0" href="#p_VR0+805/R0"></a>Each exercise starts with a problem description. Read that and try to
solve the exercise. If you run into problems, consider reading the
hints after the exercise.
Full solutions to the exercises are not included in this
book, but you can find them online at
<a href="http://eloquentjavascript.net/code"><em>eloquentjavascript.net/code</em></a>.
If you want to learn something from the exercises, I recommend looking
at the solutions only after you’ve solved the exercise, or at least
after you’ve attacked it long and hard enough to have a slight
headache.</p>
<h3><a class=h_ident id="h_umoXp9u0e7" href="#h_umoXp9u0e7"></a>Looping a triangle</h3>
<p><a class=p_ident id="p_pP646YLlGy" href="#p_pP646YLlGy"></a>Write a loop that makes seven calls to
<code>console.log</code> to output the following triangle:</p>
<pre>#
##
###
####
#####
######
#######</pre>
<p><a class=p_ident id="p_hwij+BD/vz" href="#p_hwij+BD/vz"></a>It may be useful to know that you can find the length of a string by
writing <code>.length</code> after it.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_UHjV4GXoBw" href="#c_UHjV4GXoBw"></a><span class="cm-keyword">var</span> <span class="cm-variable">abc</span> <span class="cm-operator">=</span> <span class="cm-string">"abc"</span>;
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">abc</span>.<span class="cm-property">length</span>);
<span class="cm-comment">// → 3</span></pre>
<p><a class=p_ident id="p_hzLkQ7lBb5" href="#p_hzLkQ7lBb5"></a>Most exercises contain a piece of code that you can modify to solve
the exercise. Remember that you can click code blocks to edit them.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_CfkOp8tkUe" href="#c_CfkOp8tkUe"></a><span class="cm-comment">// Your code here.</span></pre>
<div class=solution><div class=solution-text>
<p><a class=p_ident id="p_4G9czVhC4S" href="#p_4G9czVhC4S"></a>You can start with a program that simply
prints out the numbers 1 to 7, which you can derive by making a few
modifications to the
<a href="02_program_structure.html#loops">even number printing example</a>
given earlier in the chapter, where the <code>for</code> loop was introduced.</p>
<p><a class=p_ident id="p_Cfhk1uLlnS" href="#p_Cfhk1uLlnS"></a>Now consider the equivalence between numbers and strings of hash
characters. You can go from 1 to 2 by adding 1 (<code>+= 1</code>). You can go
from <code>"#"</code> to <code>"##"</code> by adding a character (<code>+= "#"</code>). Thus, your
solution can closely follow the number-printing program.</p>
</div></div>
<h3><a class=h_ident id="h_rebKE3gdjV" href="#h_rebKE3gdjV"></a>FizzBuzz</h3>
<p><a class=p_ident id="p_i0Cvwf75cQ" href="#p_i0Cvwf75cQ"></a>Write a
program that uses <code>console.log</code> to print all the numbers from 1 to
100, with two exceptions. For numbers divisible by 3, print <code>"Fizz"</code>
instead of the number, and for numbers divisible by 5 (and not 3),
print <code>"Buzz"</code> instead.</p>
<p><a class=p_ident id="p_fJ/4Bt0n0A" href="#p_fJ/4Bt0n0A"></a>When you have that working, modify your program to print <code>"FizzBuzz"</code>,
for numbers that are divisible by both 3 and 5 (and still print
<code>"Fizz"</code> or <code>"Buzz"</code> for numbers divisible by only one of those).</p>
<p><a class=p_ident id="p_ixkJ0lwGKY" href="#p_ixkJ0lwGKY"></a>(This is actually an interview question that has been claimed to
weed out a significant percentage of programmer candidates. So if you
solved it, you’re now allowed to feel good about yourself.)</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_CfkOp8tkUe" href="#c_CfkOp8tkUe"></a><span class="cm-comment">// Your code here.</span></pre>
<div class=solution><div class=solution-text>
<p><a class=p_ident id="p_eChcRqNQtZ" href="#p_eChcRqNQtZ"></a>Going
over the numbers is clearly a looping job, and selecting what to print
is a matter of conditional execution. Remember the trick of using the
remainder (<code>%</code>) operator for checking whether a number is divisible by
another number (has a remainder of zero).</p>
<p><a class=p_ident id="p_6QvPT/yNQ2" href="#p_6QvPT/yNQ2"></a>In the first version, there are three possible outcomes for every
number, so you’ll have to create an <code>if</code>/<code>else if</code>/<code>else</code> chain.</p>
<p><a class=p_ident id="p_Oma/sCzEw+" href="#p_Oma/sCzEw+"></a>The second version of the
program has a straightforward solution and a clever one. The simple
way is to add another “branch” to precisely test the given condition.
For the clever method, build up a string containing the word or words
to output, and print either this word or the number if there is no
word, potentially by making elegant use of the <code>||</code> operator.</p>
</div></div>
<h3><a class=h_ident id="h_5Hz2kiaaXp" href="#h_5Hz2kiaaXp"></a>Chess board</h3>
<p><a class=p_ident id="p_uH3DV6RVnV" href="#p_uH3DV6RVnV"></a>Write a program that creates a string that represents an
8×8 grid, using newline characters to separate lines. At each position
of the grid there is either a space or a “#” character. The characters
should form a chess board.</p>
<p><a class=p_ident id="p_9kgrie1A2f" href="#p_9kgrie1A2f"></a>Passing this string to <code>console.log</code> should show something like this:</p>
<pre> # # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #</pre>
<p><a class=p_ident id="p_8n1E0bRGiW" href="#p_8n1E0bRGiW"></a>When you have a program that generates this pattern, define a
variable <code>size = 8</code> and change the program so that it works for
any <code>size</code>, outputting a grid of the given width and height.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_CfkOp8tkUe" href="#c_CfkOp8tkUe"></a><span class="cm-comment">// Your code here.</span></pre>
<div class=solution><div class=solution-text>
<p><a class=p_ident id="p_+7IWmz4GNn" href="#p_+7IWmz4GNn"></a>The string can be built by starting with
an empty one (<code>""</code>) and repeatedly adding characters. A newline
character is written <code>"\n"</code>.</p>
<p><a class=p_ident id="p_d+ioCL2/4t" href="#p_d+ioCL2/4t"></a>Use <code>console.log</code> to inspect the output of your program.</p>
<p><a class=p_ident id="p_8UZmClB+c6" href="#p_8UZmClB+c6"></a>To work with two dimensions, you will need a
loop inside of a loop. Put curly braces around the bodies of
both loops to make it easy to see where they start and end. Try to
properly indent these bodies. The order of the loops must follow the
order in which we build up the string (line by line, left to right,
top to bottom). So the outer loop handles the lines and the inner loop
handles the characters on a line.</p>
<p><a class=p_ident id="p_rEz9p9ipPK" href="#p_rEz9p9ipPK"></a>You’ll
need two variables to track your progress. To know whether to put a
space or a hash sign at a given position, you could test whether the
sum of the two counters is even (<code>% 2</code>).</p>
<p><a class=p_ident id="p_9FaUCRZviB" href="#p_9FaUCRZviB"></a>Terminating a line by adding a newline character happens after the
line has been built up, so do this after the inner loop but inside of
the outer loop.</p>
</div></div>
<nav>
<a href="01_values.html" title="previous chapter">◀</a>
<a href="index.html" title="cover">◆</a>
<a href="03_functions.html" title="next chapter">▶</a>
</nav>
</article>