forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path00_intro.txt
420 lines (357 loc) · 17.9 KB
/
00_intro.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
:next_link: 01_values
:load_files: ["js/00_intro.js"]
= Introduction =
This book is about talking to computers, one of
the fundamental tools of our time. Being able to harness them
effectively is an immensely useful skill. With the right mindset, it
can also be very entertaining.
There is something of an inherent gap between us, squishy biological
organisms with a talent for social and spatial reasoning, and the
computer, a straightforward manipulator of meaningless data with none
of our biases and instincts. Fortunately, there has been great
progress in bridging this gap in the past sixty years.
The history of human-computer interaction has been one of moving away
from the cold, reductionist world view of the computer by layering
more human-friendly analogies on top of it. The two most important
ideas in this process have been the use of computer languages, which
map well to our brain because they resemble the languages we use to
talk to each other, and graphical point-and-click (or tap) interfaces,
which we understand easily because they imitate the tangible world
outside of the machine.
Graphical interfaces tend to be easier to figure out than
language-based ones—spotting a button is quicker than learning a
grammar. For this reason, they have become the dominant way to
interact with consumer-oriented systems. Compare today's phones, where
you can accomplish all kinds of tasks by tapping and swiping the
elements that appear on the screen, with the ((Commodore 64)) of 1982,
the device that introduced me to computing, where all you get is a
blinking cursor, and you're supposed to take it from there by typing
commands.
Obviously, the touchscreen phone is more accessible, and it is
entirely appropriate that such devices use a graphical interface. But
language-based interfaces have another advantage—once you learn
their language, they tend to be more expressive, by making it easy to
compose the functionality provided by the system in new ways, and even
to create your own building blocks.
(((programming language))) With the Commodore 64, almost every task in
the system was accomplished by giving commands in the machine's
built-in language (a dialect of the ((BASIC)) programming language).
This allowed users to gradually progress from simply using the
computer (loading programs) to actually programming it themselves.
You were _in_ a programming environment from the start, rather than
having to actively look for one.
indexsee:[web browser,browser]
(((JavaScript,availability of)))(((browser))) This has been mostly
lost with the shift towards graphical user interfaces. But the
language-based interfaces, in the form of programming languages, are
still there, on every machine, largely hidden from the casual user.
One such language, JavaScript, is available on just about every
consumer device as part of a web browser.
This book intends to make you familiar enough with this language to be
able to make a computer do what you want.
== On programming ==
[quote, Confucius]
____
(((Confucius)))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.
____
(((programming,difficulty of)))Besides explaining JavaScript, I also
want to introduce the basic principles of programming. Programming, it
turns out, is hard. The fundamental rules are typically simple and
clear. But programs, built on top of these basic rules, tend to become
complex enough to introduce their own rules and complexity. You're
building your own maze, in a way, and might just get lost in it.
To get something out of this book, more than just passive reading is
required. Try to stay sharp, make an effort to understand the example
code, and only continue when you are reasonably sure you understand
the material that came before.
[quote, Joseph Weizenbaum, Computer Power and Human Reason]
____
(((Weizenbaum, Joseph)))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.
____
(((program,nature of)))(((data))) 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. A superficially fitting one is that of a
machine—lots of separate parts tend to be involved, and to make the
whole thing tick we have to consider the ways in which these parts
interconnect and contribute to the operation of the whole.
(((computer)))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 ingeniously
combine enormous numbers of these simple actions in order to do very
complicated things.
(((programming,joy of)))To some of us, writing computer programs is a
fascinating game. A program is a building of thought. It is costless
to build, it is weightless, and it grows easily under our typing
hands.
If we are not careful, its size and complexity will grow out of
control, confusing even the person who created it. This is the main
problem of programming: keeping programs under control. 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.
Some 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 (_“best practices”_) prescribing the form
programs should have, and the more zealous among them will consider
those that go outside of this little safe zone to be _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, and still largely
unexplored. It is certainly dangerous going, luring the inexperienced
programmer into all kinds of confusion, but that only means you should
proceed with caution and keep your wits about you. As you learn, there
will always be new challenges and new territory to explore.
Programmers who refuse to keep exploring will stagnate, forget their
joy, and get bored with their craft.
== Why language matters ==
(((programming language)))(((binary)))In the beginning, at the birth
of computing, there were no programming languages. Programs looked
something like this:
[source,text/plain]
----
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
----
(((programming,history of)))That is a program to add the numbers from
1 to 10 together and print out the result `(1 + 2 + ... + 10 = 55)`.
It could run on a very simple, hypothetical machine. 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.
(((bit)))(((wizard (mighty))))Of course, manually entering these
arcane patterns of bits (the ones and zeros) did give the programmer
a profound sense of being a mighty wizard. And that has to be worth
something in terms of job satisfaction.
(((memory)))Each line of the program above contains a single instruction. It
could be written in English like this:
[source,text/plain]
----
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.
----
(((naming)))(((variable)))Although that is already more readable than
the soup of bits, it is still rather unpleasant. It might help to use
names instead of numbers for the instructions and memory locations:
[source,text/plain]
----
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
computation, 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 whether `count` is
equal to 11 in order to decide whether it can stop yet. Because our
hypothetical machine is rather primitive, it can only test whether a
number is zero and make a decision (jump) based on that. So, it uses
the memory location labeled `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 1 every
time the program has decided that it is not 11 yet.
Here is the same program in JavaScript:
[source,javascript]
----
var total = 0, count = 1;
while (count <= 10) {
total += count;
count += 1;
}
console.log(total);
// → 55
----
(((while loop)))(((looping)))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 any more. The `while` language
construct takes care of that. It continues executing the block
(wrapped in braces) below it as long as the condition it was given
holds: `count <= 10`, which means “`count` is less than or equal to
10”. We no longer have to create a temporary value and compare that
to zero. This was an uninteresting detail, and the power of
programming languages is that they take care of uninteresting details
for us.
At the end of the program, after the `while` has finished, the
`console.log` operation is applied to the result in order to write it
as output.
(((abstraction)))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:
[source,javascript]
----
console.log(sum(range(1, 10)));
// → 55
----
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: `log` 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`.)
(((programming language,power of)))A good programming language helps
the programmer by allowing them to talk about the actions that the
computer has to perform on a higher level. It helps leave
uninteresting details implicit, it provides convenient building blocks
(such as `while` and `console.log`), allows you to define your own
building blocks (such as `sum` and `range`), and makes it easy to
compose these blocks.
== What is JavaScript? ==
indexsee:[WWW,World Wide Web]
indexsee:[web,World Wide Web]
(((JavaScript)))(((JavaScript,history of)))(((World Wide Web)))
JavaScript was introduced in 1995, as a way to add programs to web
pages in the Netscape Navigator browser. The language has since been
adapted by all other major graphical web browsers. It has made the
current generation of web applications possible—browser-based email
clients, maps, and social networks—and is also used in more
traditional sites to provide various forms of interactivity and
cleverness.
(((Java)))It is important to note that JavaScript has almost nothing
to do with the programming language Java. The similar name was
inspired by marketing considerations, rather than good judgment. When
JavaScript was being introduced, the Java language was being heavily
marketed and was gaining in popularity. Someone thought it a good idea
to try to ride along on this success. Now we are stuck with the name.
(((ECMAScript)))After its adoption outside of Netscape, a standard
document was written to describe the way the language should work, in
an effort to make sure the various pieces of software that claimed to
support JavaScript were actually talking about the same language. This
is called the ECMAScript standard, after the organization that did the
standardization. In practice, the terms ECMAScript and JavaScript can
be used interchangeably—they are two names for the same language.
(((JavaScript,weaknesses of)))There are those who will say _terrible_
things about the JavaScript language. Many of these things are true.
When I was required to write something in JavaScript for the first
time, I quickly came to despise it—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, of course, but there is 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.
(((JavaScript,flexibility of)))This flexibility also has its
advantages, though. It leaves space for a lot of techniques that are
impossible in more rigid languages, and, as we will see in later
chapters, it can be used to overcome some of JavaScript's
shortcomings. After learning it properly and working with it for a
while, I have learned to really _like_ this language.
(((JavaScript,versions of)))There have been several _versions_ of
JavaScript. ECMAScript version 3 was the dominant, widely supported
version in the time of JavaScript's ascent to dominance, roughly
between 2000 and 2010. During this time, work was underway on an
ambitious version 4, which planned a number of radical improvements
and extensions to the language. Changing a living, widely used
language in such a radical way turned out to be politically difficult,
and work on the 4th edition was abandoned in 2008, leading to the much
less ambitious 5th edition coming out in 2009. We're now just reaching
the point where all major browsers support this 5th edition, which is
the language version that this book will be focusing on. Work on a 6th
edition is underway. (FIXME ES6 is likely to be out when the book goes
to press)
(((JavaScript,uses of)))Web browsers are not the only platforms on
which JavaScript is used. Some databases, such as MongoDB and CouchDB,
use JavaScript as their scripting and query language. Several
platforms for desktop and server programming, most notably the
_((node.js))_ project, the subject of chapter (FIXME), are providing a
powerful environment for programming JavaScript outside of the
browser.
== Code, and what to do with it ==
Code is the text that makes up programs. 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 the examples, read them attentively and understand them.
This can be slow and confusing at first, but I promise that 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.
I recommend to try out your solutions to exercises in an actual
JavaScript interpreter, to get immediate feedback on whether what you
are doing is working or not, and, hopefully, to be tempted to
experiment and go beyond the exercises.
ifdef::html_target[]
When reading this book in your browser, you can edit (and run) the
example programs by clicking on them.
endif::html_target[]
ifdef::tex_target[]
Most of the example code in this book can be found on the book's
website, at `eloquentjavascript.net/code`, which also provides
an easy way to run the programs and experiment with writing your own
code.
endif::tex_target[]
(((JavaScript,console)))Running JavaScript programs outside of this
book's sandbox is also possible. You can opt to install node.js, and
read enough of its documentation to figure out how to use it to
evaluate text files that contain programs. Or you can use your
browser's developer console (typically found somewhere under a “tools”
or “developer” menu) and play around in there. In chapter (FIXME), the
way in which JavaScript programs are embedded in web pages (HTML
files) is explained. In the meantime, you could head over to
`http://jsbin.com` for another friendly interface for running
JavaScript code in a browser.
== Typographic conventions ==
In this book, text written in a `monospaced` font should be understood
to represent elements of programs—sometimes they are self-sufficient
fragments, and sometimes they just refer to part of a nearby program.
Programs (of which you have already seen a few), are written as
follows:
[source,javascript]
----
function fac(n) {
if (n == 0)
return 1;
else
return fac(n - 1) * n;
}
----
Sometimes, in order to show the output that a program produces, the
expected output is written below it, with two slashes and an arrow in
front:
[source,javascript]
----
console.log(fac(8));
// → 40320
----
Good luck!