-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbook.txt
11513 lines (9456 loc) · 445 KB
/
book.txt
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
====================
Introduction / intro
====================
When personal computers were first introduced, most of them came
equipped with a simple programming language, usually a variant of
_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.
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.
That is what this (hyper-)book tries to do.
---
| 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.
|
| -- Confucius
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 *art*.
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.
---
| 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.
|
| -- Joseph Weizenbaum, *Computer Power and Human Reason*
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.
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.
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.
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.
---
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 *bad* programmers.
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).
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.
---
In the beginning, at the birth of computing, there were no programming
languages. Programs looked something like this:
] 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
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.
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.
Each line of the program contains a single instruction. It could be
written in English like this:
1. Store the number 0 in memory location 0
2. Store the number 1 in memory location 1
3. Store the value of memory location 1 in memory location 2
4. Subtract the number 11 from the value in memory location 2
5. If the value in memory location 2 is the number 0, continue with instruction 9
6. Add the value of memory location 1 to memory location 0
7. Add the number 1 to the value of memory location 1
8. Continue with instruction 3
9. Output the value of memory location 0
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:
] 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'
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: |total| will be used to build up the result of the program,
and |count| keeps track of the number that we are currently looking
at. The lines using |compare| are probably the weirdest ones. What the
program wants to do is see if |count| 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 |compare| to
compute the value of |count - 11|, and makes a decision based on that
value. The next two lines add the value of |count| to the result, and
increment |count| by one every time the program has decided that it is
not 11 yet.
Here is the same program in JavaScript:
> var total = 0, count = 1;
> while (count <= 10) {
> total += count;
> count += 1;
> }
> print(total);
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 |while| takes care of that. It continues
executing the lines below it as long as the condition it was given
holds: |count <= 10|, which means '|count| is less than or equal
to |10|'. 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.
Finally, here is what the program could look like if we happened to
have the convenient operations |range| and |sum| available, which
respectively create a collection of numbers within a range and compute
the sum of a collection of numbers:
> print(sum(range(1, 10)));
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: |print| the |sum| of the |range| of numbers from |1|
to |10|. (We will see in later chapters how to build things like |sum|
and |range|.)
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 |while| construct),
and, most of the time, allows the programmer to add building blocks
himself (such as the |sum| and |range| operations).
---
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 [people |
http://steve-yegge.blogspot.com/2007/02/next-big-language.html] 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.
There are those who will say *terrible* 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.
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 *like* this language.
---
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.
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.
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.
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.
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.
---
Most chapters in this book contain quite a lot of code##. 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.
## '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'.
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 *very* 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.
---
To allow you to try out programs, both the examples and the code you
write yourself, this book makes use of something called 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.
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
|wrong!|, 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.
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' button to open a new, empty buffer. When there is more
than one open buffer, 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 buffer.
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:
> var total = 0, count = 1;
> while (count <= 10) {
> total += count;
> count += 1;
> }
> print(total);
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 |while| never becomes false, for example if you
choose to add |0| instead of |1| to the count variable. Now the
program will run forever.
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.
---
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).
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.
---
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.
==============================================================
Basic JavaScript: values, variables, and control flow / basics
==============================================================
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##, 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 _value_s. 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.
## Bits are any kinds of two-valued things, usually described as |0|s
and |1|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.
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 *woosh*, 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.
---
Values of the type _number_ are, as you might have deduced, numeric
values. They are written the way numbers are usually written:
>> 144
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.
This is what |144| looks like in bits##:
## If you were expecting something like |10010000| here -- good call,
but read on. JavaScript's numbers are not stored as integers.
] 0100000001100010000000000000000000000000000000000000000000000000
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^3 = 1000 different
numbers. With 64 binary digits, 2^64 different numbers can be written.
This is a lot, more than 10^19 (a one with nineteen zeroes).
Not all whole numbers below 10^19 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.
That leaves 52 bits##. Any whole number less than 2^52, which is over
10^15, 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 *do* need a terrible lot of them to
get anything done. When at all possible, it is more pleasant to deal
with bigger things.
## 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.
Fractional numbers are written by using a dot.
>> 9.81
For very big or very small numbers, one can also use 'scientific'
notation by adding an |e|, followed by the exponent of the number:
>> 2.998e8
Which is 2.998 * 10^8 = 299800000.
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. The same way that π (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.
---
The main thing to do with numbers is arithmetic. Arithmetic operations
such as addition or multiplication take two number values and produce
a new number from them. Here is what they look like in JavaScript:
>> 100 + 4 * 11
The _|+|_ and _|*|_ symbols are called operators. The first stands for
addition, and the second for multiplication. Putting an operator
between two values will @_applying_apply it to those values, and
produce a new value.
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@_|()|_:
>> (100 + 4) * 11
For subtraction, there is the _|-|_ operator, and division can be done
with _|/|_. When operators appear together without parentheses, the
order in which they are applied is determined by the _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 (|1 - 1 + 1|) they are
applied left-to-right.
Try to figure out what value this produces, and then run it to see if
you were correct...
>> 115 * 4 - 4 + 88 / 2
These rules of precedence are not something you should worry about.
When in doubt, just add parentheses.
There is one more arithmetic operator which is probably less familiar
to you. The _|%|_ symbol is used to represent the _remainder_ operation.
|X % Y| is the remainder of dividing |X| by |Y|. For example
|314 % 100| is |14|, |10 % 3| is |1|, and |144 % 12| is |0|. Remainder
has the same precedence as multiplication and division.
---
The next data type is the _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:
>> "Patch my boat with chewing gum."
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,
@_newline_the things you get when you press enter, can also not be put
between quotes, the string has to stay on a single line.
To be able to have such characters in a string, the following trick is
used: Whenever a backslash ('|\|') 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 '|n|' character occurs after a backslash, it is
interpreted as a newline. Similarly, a '|t|' after a backslash means a
tab character##.
## 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 |print("a\nb")|
-- why this works, we will see in a moment.
>> "This is the first line\nAnd this is the second"
Note that if you type this into the console, it'll display it back in
'source' form, with the quotes and backslash escapes. To see only the
actual text, you can type |print("a\nb")|. What that does precisely
will be clarified a little further on.
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:
>> "A newline character is written like \"\\n\"."
---
Strings can not be divided, multiplied, or subtracted. The _|+|_
operator *can* be used on them. It does not add, but it concatenates,
it glues two strings together.
>> "con" + "cat" + "e" + "nate"
There are more ways of manipulating strings, but these are discussed
later.
---
Not all operators are symbols, some are written as words. For example,
the _|typeof|_ operator, which produces a string value naming the type
of the value you give it.
>> typeof 4.5
The other operators we saw all operated on two values, |typeof| takes
only one. Operators that use two values are called _binary operator_s,
while those that take one are called _unary operator_s. The
@_|-|_minus operator can be used both as a binary and a unary
operator:
>> - (10 - 2)
---
Then there are values of the _boolean_ type. There are only two of
these: _|true|_ and _|false|_. Here is one way to produce a |true|
value:
>> 3 > 2
And |false| can be produced like this:
>> 3 < 2
I hope you have seen the _|>|_ and _|<|_ 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.
Strings can be compared in the same way:
>> "Aardvark" < "Zoroaster"
The way strings are ordered is more or less alphabetic. More or
less... Uppercase letters are always 'less' than lowercase ones, so
|"Z" < "a"| (upper-case Z, lower-case a) is |true|, and non-alphabetic
characters ('|!|', '|@|', etc) are also included in the ordering. The
actual way in which the comparison is done is based on the _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.
Other similar operators are _|>=|_ ('is greater than or equal to'),
_|<=|_ (is less than or equal to), _|==|_ ('is equal to'), and _|!=|_
('is not equal to').
>> "Itchy" != "Scratchy"
>> 5e2 == 500
---
There are also some useful operations that can be applied to boolean
values themselves. JavaScript supports three logical operators: *and*,
*or*, and *not*. These can be used to 'reason' about booleans.
The _|&&|_ operator represents logical *and*. It is a binary operator,
and its result is only |true| if both of the values given to it are
|true|.
>> true && false
_||||_ is the logical *or*, it is |true| if either of the values given
to it is |true|:
>> true || false
*Not* is written as an exclamation mark, _|!|_, it is a unary operator
that flips the value given to it, |!true| is |false|, and |!false| is
|true|.
***
>> ((4 >= 6) || ("grass" != "green")) &&
>> !(((12 * 2) == 144) && true)
Is this true? For readability, there are a lot of unnecessary
parentheses in there. This simple version means the same thing:
>> (4 >= 6 || "grass" != "green") &&
>> !(12 * 2 == 144 && true)
///
Yes, it is |true|. You can reduce it step by step like this:
>> (false || true) && !(false && true)
>> true && !false
>> true
I hope you noticed that |"grass" != "green"| is |true|. Grass may be
green, but it is not equal to green.
---
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, |||| has the lowest precedence, then comes |&&|, then the
comparison operators (|>|, |==|, etcetera), and then the rest. This
has been chosen in such a way that, in simple cases, as few
parentheses as possible are necessary.
---
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 _expression_. Every value that is
written directly (such as |22| or |"psychoanalysis"|) 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.
There are a few more ways of building expressions, which will be
revealed when the time is ripe.
There exists a unit that is bigger than an expression. It is called a
_statement_. A program is built as a list of statements. Most
statements end with a _semicolon_ (|;|). The simplest kind of
statement is an expression with a semicolon after it. This is a
program:
> 1;
> !false;
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 '_side effect_s'. The statements in
the example above just produce the values |1| and |true|, and then
immediately throw them into the bit bucket##. This leaves no
impression on the world at all, and is not a side effect.
## 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.
---
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 _variable_.
> var caught = 5 * 5;
A variable always has a name, and it can point at a value, holding on
to it. The statement above creates a variable called |caught| and uses
it to grab hold of the number that is produced by multiplying |5| by
|5|.
After running the above program, you can type the word |caught| into
the console, and it will retrieve the value |25| for you. The name of
a variable is used to fetch its value. |caught + 1| also works. A
variable name can be used as an expression, and thus can be part of
bigger expressions.
The word _|var|_ is used to create a new variable. After |var|, 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,
|catch22| is a valid name, but the name must not start with one. The
characters '|$|' and '|_|' can be used in names as if they were
letters, so |$_$| is a correct variable name.
If you want the new variable to immediately capture a value, which is
often the case, the _|=|_ operator can be used to give it the value of
some expression.
When a variable points at a value, that does not mean it is tied to
that value forever. At any time, the |=| operator can be used on
existing variables to yank them away from their current value and make
them point to a new one.
> caught = 4 * 4;
---
You should imagine variables as tentacles, rather than boxes. They do
not *contain* values, they *grasp* 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...
> var luigiDebt = 140;
Then, every time Luigi pays something back, this amount can be
decremented by giving the variable a new number:
> luigiDebt = luigiDebt - 35;
The collection of variables and their values that exist at a given
time is called the _environment_. When a program starts up, this
environment is not empty. It always contains 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.
---
A lot of the values provided by the standard environment have the type
'_function_'. A function is a piece of program wrapped in a value.
Generally, this piece of program does something useful, which can be
invoked using the function value that contains it. In a browser
environment, the variable _|alert|_ holds a function that shows a
little dialog window with a message. It is used like this:
> alert("Also, your hair is on fire.");
@_|()|_Executing the code in a function is called _invoking_, calling,
or _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 _parameter_s or
_argument_s. |alert| needs only one of them, but other functions might
need a different number.
---
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
_|Math.max|_, which takes two arguments and gives back the biggest of
the two:
> alert(Math.max(2, 4));
@_|Math.min|_When a function produces a value, it is said to _return_
it. Because things that produce values are always expressions in
JavaScript, function calls can be used as a part of bigger
expressions:
> alert(Math.min(2, 4) + 100);
\\Cfunctions discusses writing your own functions.
---
As the previous examples show, |alert| 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 _|print|_, which does not pop up a window,
but just writes a value to the output area of the console. |print| 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.
> print("N");
A similar function, also provided on these pages, is |show|. While
|print| will display its argument as flat text, _|show|_ 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 |show|:
> show("N");
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 _|confirm|_. This returns a boolean, |true| if the user
presses 'OK', and |false| if he presses 'Cancel'.
> show(confirm("Shall we, then?"));
_|prompt|_ 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.
> show(prompt("Tell us everything you know.", "..."));
---
It is possible to give almost every variable in the environment a new
value. This can be useful, but also dangerous. If you give |print| the
value |8|, 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.
---
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.
> var theNumber = Number(prompt("Pick a number", ""));
> print("Your number is the square root of " +
> (theNumber * theNumber));
The function _|Number|_ converts a value to a number, which is needed
in this case because the result of |prompt| is a string value. There
are similar functions called _|String|_ and _|Boolean|_ which convert
values to those types.
---
Consider a program that prints out all even numbers from 0 to 12. One
way to write this is:
> print(0);
> print(2);
> print(4);
> print(6);
> print(8);
> print(10);
> print(12);
That works, but the idea of writing a program is to make something
*less* 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.
> var currentNumber = 0;
> while (currentNumber <= 12) {
> print(currentNumber);
> currentNumber = currentNumber + 2;
> }
You may have seen _|while|_ in the introduction chapter. A statement
starting with the word |while| creates 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 |while|
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 |true|, 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.
The variable |currentNumber| demonstrates the way a variable can track
the progress of a program. Every time the loop repeats, it is
incremented by |2|, and at the beginning of every repetition, it is
compared with the number |12| to decide whether to keep on looping.
The third part of a |while| statement is another statement. This is
the _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:
> var currentNumber = 0;
> while (currentNumber <= 12)
> currentNumber = currentNumber + 2;
Here, |currentNumber = currentNumber + 2;| 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. @_|{}|_Braces
(|{| and |}|) are used to group statements into _block_s. 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 |print|
and the statement that updates |currentNumber|.
*** power2
Use the techniques shown so far to write a program that calculates and
shows the value of 2^10 (2 to the 10th power). You are, obviously, not
allowed to use a cheap trick like just writing |2 * 2 * ...|.
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 |while| 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.
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.
///
> var result = 1;
> var counter = 0;
> while (counter < 10) {
> result = result * 2;
> counter = counter + 1;
> }
> show(result);
The counter could also start at |1| and check for |<= 10|, but, for
reasons that will become apparent later on, it is a good idea to get
used to counting from 0.
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.
***
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'.