Repository navigation
Expand file tree
/
Copy path02_program_structure.txt
More file actions
1024 lines (829 loc) · 38.3 KB
/
Copy path02_program_structure.txt
File metadata and controls
1024 lines (829 loc) · 38.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
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
:chap_num: 2
:prev_link: 01_values
:next_link: 03_functions
= Estructura del Programa =
[chapterquote="true"]
[quote, _why, Why's (Poignant) Guide to Ruby]
____
Y mi corazón brilla rojo debajo de mi
delgada, translúcida piel y tienen que administrarme 10cc de JavaScript
para hacerme regresar (respondo bien a las toxinas en la sangre). ¡Hombre,
esa cosa te sacará de tus casillas!
____
(((why)))(((Poignant Guide)))En este capítulo, vamos a empezar a hacer
cosas que realmente pueden ser llamadas _programación_. Vamos a ampliar
nuestro conocimiento del lenguaje JavaScript, más allá de los sustantivos
y fragmentos de oraciones que hemos visto hasta ahora,
hasta el punto en que podamos expresar alguna prosa significativa.
== Expresiones y declaraciones ==
(((gramática)))(((sintaxis)))(((código,
estructura de)))(((gramática)))(((JavaScript,sintaxis)))En el
link:01_values.html#values[Capítulo 1], creamos algunos valores y después
les aplicamos operadores para obtener nuevos valores. Crear valores de esta forma
es una parte esencial de cada programa de JavaScript, pero esto es sólo
una parte.
(((expresión literal)))Un fragmento de código que produce un valor es
llamado una _((expresión))_. Cada valor que se escribe literalmente
(tal como `22` o `"psicoanálisis"`) es una expresión. Una expresión
entre ((paréntesis)) es también una expresión, como un ((operador
binario)) aplicado a dos expresiones o un operador unario aplicado a
una expresion.
(((anidado de instrucciones)))(((lenguage humano)))Esto muestra parte de la
belleza de una interfaz basada en el lenguaje. Las expresiones se pueden anidar
en una forma muy similar a la forma de sub-frases en la que las lenguas humanas
son anidadas, y las sub-frases pueden contener sus propias sub-frases, etc.
Esto nos permite combinar expresiones para expresar cálculos
arbitrariamente complejos.
(((declaración)))(((punto y coma)))(((programa)))Si una expresión
corresponde a un fragmento de frase, una _declaración_ en JavaScript
corresponde a una frase completa en un lenguaje humano. Un programa es
simplemente una lista de declaraciones.
(((syntax)))El tipo más simple de declaración es una expresión con un
punto y coma después de ella. Esto es un programa:
[source,javascript]
----
1;
!false;
----
Es un programa inútil, sin embargo. Una ((expresión)) puede estar presente para
sólo producir un valor, que puede entonces ser utilizado por la expresión que
la contiene. Una ((declaración)) existe por sí sola y que equivale a algo
sólo si afecta al mundo. Podría mostrar algo en la
pantalla -que cuenta como cambiar el mundo_ o podría cambiar el
estado interno de la máquina de estados de manera que afectará las
declaraciones que vienen despues de ella. Estos cambios se
llaman _((efectos colaterale))s_. Las declaraciones en el ejemplo anterior solo
producen los valores `1` y `verdadero` y los desechan inmediatamente.
Esto no deja ningún cambio en el mundo en absoluto. Al ejecutar el programa,
nada observable sucede.
(((estilos de programación)))(((inserción automática de punto
y coma)))(((punto y coma)))En algunos casos, JavaScript te permite
omitir el punto y coma al final de una declaración. En otros casos, tiene que
estar allí, o la siguiente ((linea)) será tratada como parte de la misma
declaración. Las reglas para cuando se puede omitir con seguridad son algo
complejas y propensas a errores. En este libro, cada declaración que necesite un
punto y coma siempre será terminada por un punto y coma4. Te recomiendo que hagas lo
mismo en tus propios programas, al menos hasta que hayas aprendido más sobre
sutilezas involucradas en omitir el punto y coma.
== Variables ==
(((sintaxis)))(((variable, definición)))(((efecto secundario)))(((memoria))) ¿Cómo
mantiene un programa su ((estado)) interno? ¿Cómo recuerda algo?
Hemos visto cómo producir nuevos valores de viejos valores, pero
esto no cambia los valores antiguos, y el nuevo valor tiene que ser
inmediatamente utilizado o se disipará de nuevo. Para atrapar y mantener los valores,
JavaScript proporciona una cosa llamada _variable_.
[source,javascript]
----
var atrapado = 5 * 5;
----
(((palabra clave var)))Y eso nos da nuestra segunda clase de ((declaración)).
La palabra especial(_((palabra clave))_ o _((keyword))_) `var` indica que
esta frase va a definir una variable. Es seguida por el nombre de la variable
y, si queremos dar de inmediato un valor, con un operador de `=` y
una expresión.
La declaración anterior crea una variable llamada `atrapado` y se usa
para retener el número que se produce al multiplicar 5 por 5.
Después de que una variable se ha definido, su nombre puede ser usado como una
((expresión)). El valor de esa expresión es el valor que la
variable alberga actualmente. He aquí un ejemplo:
[source,javascript]
----
var diez = 10;
console.log(diez * diez);
// → 100
----
(((carácter guión bajo)))(((signo de
dólar)))(((variable,naming)))Los nombres de variables pueden ser cualquier
palabra que no sea una palabra clave (tal como `var`). Estos no pueden incluir
espacios. Los dígitos también pueden ser parte de la variable nombre —`catch22`
es un nombre válido, por ejemplo-, pero el nombre no debe comenzar con un dígito.
Un nombre de variable no puede incluir puntuación, a excepción de los caracteres
`$` y `_`.
(((operador =)))(((asignación)))(((variable,asiganción))Cuando una
variable apunta a un valor, eso no quiere decir que está ligada a ese
valor para siempre. El operador `=` se puede utilizar en cualquier momento
en variables existentes para desconectarlas de su valor actual y apuntarlas
a uno nuevo.
[source,javascript]
----
var tono = "claro";
console.log(tono);
// → claro
tono = "oscuro";
console.log(tono);
// → oscuro
----
(((variable,modelo de)))(((tentáculo (analogía)))) Podrías
imaginar las variables como tentáculos, en lugar de la cajas. Estas no
_contienen_ valores; los _agarran_; dos variables pueden referirse al
mismo valor. Un programa puede acceder sólo los valores que todavía mantiene detenidos.
Cuando necesitas recordar algo, haces crecer un tentáculo para
agarrarlo o cambias unos de tus tentáculos existentes para agarrarlo.
image::img/octopus.jpg[alt="Variables as tentacles"]
Veamos un ejemplo. Para recordar el número de dólares que Luigi
aún te debe, se crea una variable. Y luego, cuando te paga $35,
le das a esta variable un valor nuevo.
[source,javascript]
----
var deudaDeLuigi = 140;
deudaDeLuigi = deudaDeLuigi - 35;
console.log(deudaDeLuigi);
// → 105
----
(((indefinido)))Cuando se define una variable sin darle un valor,
el tentáculo no tiene nada que sostener, por lo que termina en el aire. Si preguntas
por el valor de una variable vacía, obtendrás el valor `undefined` (indefinido).
(((var keyword)))Una sola declaración `var` puede definir múltiples
variables. Las definiciones deben estar separadas por comas.
[source,javascript]
----
var uno = 1, dos = 2;
console.log(uno + dos);
// → 3
----
== Palabras clave y palabras reservadas ==
(((sintaxis)))(((implements (palabra reservada))))(((interface (palabra
reservada))))(((let (palabra reservada))))(((package (palabra reservada))))(((private
(palabra reservada))))(((protected (palabra reservada))))(((public (palabra
reservada))))(((static (palabra reservada))))(((operador vacío)))(((yield
(palabra reservada))))(((palabra reservada)))(((variable, nombrado)))Palabras con
un significado especial, como `var`, son _((palabras clave))_, y no pueden ser
utilizadas como nombres de variables. También hay un número de palabras que son
“reservadas para uso” en ((futuras)) versiones de JavaScript. Estas también
están oficialmente no permitidas como nombres de variables, aunque algunos
entornos de JavaScript las permiten. La lista completa de palabras clave y
palabras reservadas es bastante larga.
[source,text/plain]
----
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
----
No te preocupes por memorizarlas, pero recuerda que esto podría ser
el problema cuando una definición de variable no funcione como se esperaba.
== El entorno ==
(((entorno estándar)))La colección de variables y sus valores
que existe en un momento dado se llama el _((entorno))_. Cuando un
programa se pone en marcha, este entorno no está vacío. Siempre contiene
variables que forman parte del lenguaje ((estándar)), y la mayoría del
tiempo, contiene variables que proporcionan formas de interactuar con el
sistema que lo contiene. Por ejemplo, en un ((navegador)), existen variables
y funciones para inspeccionar e influir en la página web cargada en ese momento
y leer entrada del ((ratón)) y del ((teclado)).
== Funciones ==
indexsee:[aplicación (de funciones),función de aplicación]
indexsee:[invocación (de funciones),función de aplicación]
indexsee:[llamado (de funciones),función de aplicación]
(((salida)))(((función)))(((función,aplicación)))(((función
alert)))(((caja de mensaje)))Una gran cantidad de los valores proporcionados en el
entorno por defecto tienen el tipo _((function))_. Una función(function) es un
pedazo de programa encerrado en un valor. Tales valores pueden ser _aplicados_ con
el fin de ejecutar el programa envuelto. Por ejemplo, en un entorno de
((navegador)), la variable `alert` contiene una función que muestra un pequeño
((cuadro de diálogo)) con un mensaje. Se utiliza como sigue:
[source,javascript]
----
alert("¡Good Morning!");
----
image::img/alert.png[alt="An alert dialog",width="8cm"]
(((parametro)))(((función,aplicación)))La ejecución de una función es denominada
_invocar_, _llamar_, o _aplicar_ la función. Puedes llamar a una
función poniendo ((paréntesis)) después de una expresión que produce un
valor de la función. Por lo general, se usa directamente el nombre de la variable
que contiene la función. Los valores entre paréntesis se le pasan a
el programa dentro de la función. En el ejemplo, la función `alert`
utiliza la cadena que le damos como el texto que se mostrará en el cuadro de diálogo.
Los valores dados a las funciones se denominan _((argumento))s_. La función `alert`
necesita solo uno, pero otras funciones pueden necesitar un
número diferente o diferentes tipos de argumentos.
== La función console.log ==
(((consola de JavaScript)))(((developer
tools)))(((Node.js)))(((console.log)))(((salida)))(((output)))La función `alert`
puede ser útil para imprimir cuando estamos experimentando, pero quitar del camino
todas esas pequeñas ventanas puede desesperarte. En ejemplos pasados, hemos usado
`console.log` para devolver valores. La mayoría sistemas JavaScript (incluyendo a
todos los ((navegador))es web modernos y a Node.js) nos dan una función `console.log`
que imprime sus argumentos en _algún_ dispositivo de salida de texto. En los navegadores
la salida queda en la ((consola de JavaScript)). Esta parte del navegador está
escondida por defecto, pero la mayoría de los navegadores la abren cuando presionas
F12 o, en Mac, cuando presionas Command-Option-I. Si esto no funciona, busca en los
menús un item llamado "Consola Web" o "Herramientas de Desarrollador".
ifdef::interactive_target[]
Cuando corras los ejemplos, o tu propio código, en las páginas de este libro,
la salida de `console.log` será mostrada después del ejemplo, en vez de en la
consola de JavaScript del navegador.
endif::interactive_target[]
[source,javascript]
----
var x = 30;
console.log("el valor de x es", x);
// → el valor de x es 30
----
(((objeto)))Aunque los nombres de ((variable)) no pueden contener
el ((caracter punto)), `console.log` claramente tiene uno. Esto es
porque `console.log` no es una variable simple. Es en realidad una
expresión que trae la propiedad `log` del valor mantenido por la
variable `console`. Veremos que significa exactamente en el
link:04_data.html#properties[Capítulo 4].
[[return_values]]
== Valores de Retorno ==
(((comparación,de números)))(((valor de retorno)))(((función
Math.max)))(((máximo)))Mostrar un cuadro de diálogo o escribir texto
en la pantalla es un _((efecto secundario))_. Muchas funciones son útiles porque
producen valores, y en ese caso, no necesitan tener un efecto secundario para
ser útiles. Por ejemplo, la función `Math.max` toma un número indeterminado de
números y regresa el más grande.
[source,javascript]
----
console.log(Math.max(2, 4));
// → 4
----
(((función,aplicación)))(((minimo)))(((función
Math.min))) Cuando una función produce un valor, se dice que _regresa_
ese valor. Cualquier cosa que produce un valor es una ((expresión)) en
JavaScript, lo que significa que puede ser usada dentro de expresiones
más grandes. Aquí, una llamada a `Math.min`, que es lo opuesto a
`Math.max`, es usada como entrada de un operador de suma:
[source,javascript]
----
console.log(Math.min(2, 4) + 100);
// → 102
----
El link:03_functions.html#functions[próximo capítulo] explica como escribir
tus propias funciones.
== Pedir información y confirmar ==
(((cuadro de diálogo)))(((entrada)))(((navegador)))(((función confirm)))Los
entornos de navegador tienen otras funciones más allá de `alert` para mostrar
ventanas. Puedes preguntar al usuario una cuestión estilo OK/Cancelar usando
`confirm`. Esto regresa un Booleano: `true` si el usuario hace click en OK y
`false` si el usuario presiona en Cancelar.
[source,javascript]
----
confirm("¿Entonces, deberíamos?");
----
image::img/confirm.png[alt="A confirm dialog",width="8cm"]
(((entrada)))(((función prompt)))(((entrada de texto)))La función `prompt`
puede ser usada para hacer una pregunta "abierta". El primer argumento
es la pregunta, el segundo es un texto con el que usuario inicia. Se puede
escribir una línea de texto en el cuadro de diálogo, y la función regresará
este texto como una cadena.
[source,javascript]
----
prompt("Tell me everything you know.", "...");
----
image::img/prompt.png[alt="An prompt dialog",width="8cm"]
Estas dos funciones no son usadas mucho en la programación web moderna,
principalmente porque no tienes control sobre la forma en que las ventanas
resultantes se verán, pero son útiles para programas de prueba y experimentos.
== Control de flujo ==
(((orden de ejecución)))(((programa)))(((control de flujo)))Cuando tu
programa contiene más de una ((sentencia)), las sentencias son ejecutadas (fácil de predecir), de arriba hacia abajo. Como un ejemplo básico, este programa
tiene dos sentencias. La primera le pide un número al usuario, y la
segunda, que se ejecuta después, muestra el ((cuadrado)) de ese número
[source,javascript]
----
var elNumero = Number(prompt("Dame un número", ""));
alert("Tú número es la raíz cuadrada de " +
elNumero * elNumero);
----
(((number,conversión a)))(((conversión de tipos)))(((función
Number)))(((función String)))(((función Boolean)))(((Boolean,
conversión a))) La función `Numero` convierte un valor a un número.
Necesitamos esa conversión porque el resultado de `prompt` es un valor
de cadena de texto (string), y queremos un número. Hay funciones similares
llamadas `String` y `Boolean` que convierten valores a estos tipos.
Aquí está la trivial representación esquemática de un flojo de control recto.
image::img/controlflow-straight.svg[alt="Trivial control flow",width="4cm"]
== Ejecución Condicional ==
(((Booleano)))(((flujo de control)))Ejecutar sentencia en línea recta no es
la íunica opción que tenemos. Una alternativa es la _((ejecución condicional))_,
en dondne escogemos entre dos rutas diferentes basados en un valor Booleano,
como el siguiente:
image::img/controlflow-if.svg[alt="Conditional control flow",width="4cm"]
(((sintaxis)))(((función Number)))(((if, palabra clave)))La ejecución condicional
se escribe con la palabra clave `if` en JavaScript. En el caso sencillo,
queremos que algo de código se ejecute si, y sólo si, cierta condición se cumple.
Por ejemplo, en el programa previo, podríamos querer mostrar el cuadrado de
la entrada sólo si la entrada es un número.
[source,javascript]
----
var elNumero = Number(prompt("Dame un número", ""));
if (!isNaN(elNumero))
alert("Tu número es la raíz cuadrada de " +
elNumero * elNumero);
----
Con esta modificación, si le das "queso", no se mostrará ninguna salida.
La palbra clave `if` ejecuta o salta una sentencia dependiendo del valor
de una expresión Booleana. La expresión de decisión se escribe después de
la palbra clave, entre ((parántesis)), seguida por una sentencia a ejecutar.
(((función isNaN)))La función `inNaN` es una función estándar de JavaScript
que regresa `true` sólo si el argumento que le diste es `NaN`. Resulta que
la función Number regresa `NaN` cuando le das una cadena que no
“a menos que `elNumero` no sea un número, has esto”.
(((palabra clave else)))A menudo no sólo tendrás código que se ejecute cuando
una condición sea verdadera, sino también que maneje el otro caso. Este camino
alternativo es representado por la segunda flecha en el diagrama. La palabra
clave `else` puede ser usada, junto con `if`, para crear dos rutas de ejecución
separadas y alternativas.
[source,javascript]
----
var elNumero = Number(prompt("Dame un número", ""));
if (!isNaN(elNumero))
alert("Tu número es la raíz cuadrada de " +
elNumero * elNumero);
else
alert("Hey. ¿Por qué no me diste un número?");
----
(((palabra clave if ,encadenado)))Si tenemos más de dos caminos a escoger,
varios pares de `if`/`else` pueden ser "encadenados". Aquí hay un ejemplo:
[source,javascript]
----
var num = Number(prompt("Dame un número", "0"));
if (num < 10)
alert("Chico");
else if (num < 100)
alert("Mediano");
else
alert("Grande");
----
El programa primero checará sí `num` es menor que 10. Si lo es, escoge
ese camino, muestra `"Chico"` y termina. Si no lo es, toma el el branch
`else`, que en sí mismo contiene un segundo `if`. Si la segunda condición
(`< 100`) se cumple, significa que el número está entre 10 y 100, y se
muestra `"Mediano"`. Si no lo es, el segundo y último `else` es escogido.
El diagrama de flujo para este programa es algo así:
image::img/controlflow-nested-if.svg[alt="Nested if control flow",width="4cm"]
[[bucles]]
== bucles while y do ==
(((número par)))Piensa en un programa que imprima todos
los números primos del 1 al 12. Una manera de escribirlo
sería como sigue:
[source,javascript]
----
console.log(0);
console.log(2);
console.log(4);
console.log(6);
console.log(8);
console.log(10);
console.log(12);
----
(((control de flujo)))Eso funciona, pero la idea de escribir un programa es
trabajar _menos_, no más. Si necesitamos todos los números menores que
1,000, lo anterior sería imposible de trabajar. Lo que necesitamos es una
forma de repetir algo de código. Esta forma de control de flujo es llamada _((bucle))_:
image::img/controlflow-loop.svg[alt="Loop control flow",width="4cm"]
(((syntax)))(((counter variable)))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:
[source,javascript]
----
var number = 0;
while (number <= 12) {
console.log(number);
number = number + 2;
}
// → 0
// → 2
// … etcetera
----
(((while loop)))(((Boolean)))A ((statement)) starting with the
keyword `while` creates a loop. The word `while` is followed by an
((expression)) in ((parentheses)) and then a statement, much like `if`.
The loop executes that statement as long as the expression produces a
value that is `true` when converted to Boolean type.
(((grouping)))((({} (block))))(((block)))In this loop, we want to both
print the current number and add two to our variable. Whenever we need
to execute multiple ((statement))s inside a loop, we wrap them in
((curly braces)) (`{` and `}`). 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 _block_.
(((programming style)))Many JavaScript programmers wrap every single
loop or `if` 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.
(((comparison)))(((state)))The variable `number` demonstrates the way
a ((variable)) can track the progress of a program. Every time the
loop repeats, `number` is incremented by `2`. Then, at the beginning
of every repetition, it is compared with the number `12` to decide
whether the program has done all the work it intended to do.
(((exponentiation)))As an example that actually does something useful,
we can now write a program that calculates and shows the value of
2^10^ (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.
[source,javascript]
----
var result = 1;
var counter = 0;
while (counter < 10) {
result = result * 2;
counter = counter + 1;
}
console.log(result);
// → 1024
----
The counter could also start at `1` and check for `<= 10`, but, for
reasons that will become apparent in
link:04_data.html#array_indexing[Chapter 4], it is a good idea to get
used to counting from 0.
(((loop body)))(((do loop)))(((control flow)))The `do` loop is a
control structure similar to the `while` loop. It differs only on one
point: a `do` 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:
[source,javascript]
----
do {
var yourName = prompt("Who are you?");
} while (!yourName);
console.log(yourName);
----
(((Boolean,conversion to)))(((! operator)))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 `!` operator will
convert a value to Boolean type before negating it, and all strings
except `""` convert to `true`. This means the loop continues going round
until you provide a name that is not the empty string.
== Indenting Code ==
(((block)))(((code structure)))(((whitespace)))(((programming
style)))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 character))s.
== for loops ==
(((syntax)))(((while loop)))(((counter variable)))Many loops follow
the pattern seen in the previous `while` examples. First, a “counter”
variable is created to track the progress of the loop. Then comes a
`while` 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.
(((for loop)))(((loop)))Because this pattern is so common, JavaScript and
similar languages provide a slightly shorter and more comprehensive
form, the `for` loop.
[source,javascript]
----
for (var number = 0; number <= 12; number = number + 2)
console.log(number);
// → 0
// → 2
// … etcetera
----
(((control flow)))(((state)))This program is exactly equivalent to the
link:02_program_structure.html#loops[earlier] even-number-printing
example. The only change is that all the ((statement))s that are
related to the “state” of the loop are now grouped together.
The ((parentheses)) after a `for` keyword must contain two
((semicolon))s. The part before the first semicolon _initializes_ the
loop, usually by defining a ((variable)). The second part is the
((expression)) that _checks_ whether the loop must continue. The final
part _updates_ the state of the loop after every iteration. In most
cases, this is shorter and clearer than a `while` construct.
(((exponentiation)))Here is the code that computes 2^10^, using `for`
instead of `while`:
[source,javascript]
----
var result = 1;
for (var counter = 0; counter < 10; counter = counter + 1)
result = result * 2;
console.log(result);
// → 1024
----
(((programming style)))(((indentation)))Note that even though no block
is opened with a `{`, the statement in the loop is still indented two
spaces to make it clear that it “belongs” to the line before it.
== Breaking Out of a Loop ==
(((loop,termination of)))(((break keyword)))Having the loop's
condition produce `false` is not the only way a loop can finish. There
is a special statement called `break` that has the effect of
immediately jumping out of the enclosing loop.
This program illustrates the `break` statement. It finds the first number
that is both greater than or equal to 20 and divisible by 7.
[source,javascript]
----
for (var current = 20; ; current++) {
if (current % 7 == 0)
break;
}
console.log(current);
// → 21
----
(((remainder operator)))(((% operator)))Using the remainder
(`%`) 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.
(((for loop)))The `for` 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 `break` statement inside is executed.
If you were to leave out that `break` statement or accidentally write
a condition that always produces `true`, your program would get stuck
in an _((infinite loop))_. A program stuck in an infinite loop will
never finish running, which is usually a bad thing.
ifdef::interactive_target[]
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.
endif::interactive_target[]
(((continue keyword)))The `continue` keyword is similar to `break`, in
that it influences the progress of a loop. When `continue` is
encountered in a loop body, control jumps out of the body and
continues with the loop's next iteration.
== Updating variables succinctly ==
(((assignment)))(((+= operator)))(((-= operator)))(((/=
operator)))(((*= operator)))(((state)))(((side effect)))Especially
when looping, a program often needs to “update” a variable to hold a
value based on that variable's previous value.
// test: no
[source,javascript]
----
counter = counter + 1;
----
JavaScript provides a shortcut for this:
// test: no
[source,javascript]
----
counter += 1;
----
Similar shortcuts work for many other operators, such as `result *= 2` to
double `result` or `counter -= 1` to count downward.
This allows us to shorten our counting example a little more.
[source,javascript]
----
for (var number = 0; number <= 12; number += 2)
console.log(number);
----
(((++ operator)))(((-- operator)))For `counter += 1` and `counter -=
1`, there are even shorter equivalents: `counter++` and `counter--`.
== Dispatching on a value with switch ==
(((syntax)))(((conditional execution)))(((dispatching)))(((if
keyword,chaining)))It is common for code to look like this:
// test: no
[source,javascript]
----
if (variable == "value1") action1();
else if (variable == "value2") action2();
else if (variable == "value3") action3();
else defaultAction();
----
(((colon character)))(((switch keyword)))There is a construct called
`switch` 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 `if` statements often looks better. Here is an
example:
[source,javascript]
----
switch (prompt("What is the weather like?")) {
case "rainy":
console.log("Remember to bring an umbrella.");
break;
case "sunny":
console.log("Dress lightly.");
case "cloudy":
console.log("Go outside.");
break;
default:
console.log("Unknown weather type!");
break;
}
----
(((fallthrough)))(((comparison)))(((break keyword)))(((case
keyword)))(((default keyword)))You may put any number of `case` labels
inside the block opened by `switch`. The program will jump to the
label that corresponds to the value that `switch` was given or to
`default` if no matching value is found. It starts executing
statements there, even if they're under another label, until it
reaches a `break` statement. In some cases, such as the `"sunny"` 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 `break`, which will cause the
program to execute code you do not want executed.
== Capitalization ==
(((capitalization)))(((variable,naming)))(((whitespace)))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:
----
fuzzylittleturtle
fuzzy_little_turtle
FuzzyLittleTurtle
fuzzyLittleTurtle
----
(((camel case)))(((programming style)))(((underscore character)))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)).
(((Number function)))(((constructor)))In a few cases, such as the
`Number` 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
link:06_object.html#constructors[Chapter 6]. For now, the important
thing is not to be bothered by this apparent lack of ((consistency)).
== Comments ==
(((readability)))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 _((comment))s_ are for.
(((slash character)))(((line comment)))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 (`//`) and then the comment
text after it.
// test: no
[source,javascript]
----
var accountBalance = calculateBalance(account);
// It's a green hollow where a river sings
accountBalance.adjust();
// Madly catching white tatters in the grass.
var report = new Report();
// Where the sun on the proud mountain rings:
addToReport(accountBalance, report);
// It's a little valley, foaming like light in a glass.
----
(((block comment)))A `//` comment goes only to the end of the line. A
section of text between `/*` and `*/` 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.
[source,javascript]
----
/*
I first found this number scrawled on the back of one of
my notebooks a few years ago. Since then, it has often
dropped by, showing up in phone numbers and the serial
numbers of products that I've bought. It obviously likes
me, so I've decided to keep it.
*/
var myNumber = 11213;
----
== Summary ==
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.
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 (`if`, `else`, and `switch`) and
looping (`while`, `do`, and `for`) statements.
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.
Functions are special values that encapsulate a piece of program. You
can invoke them by writing `functionName(argument1, argument2)`. Such
a function call is an expression, and may produce a value.
== Exercises ==
(((exercises)))If you are unsure how to try your solutions to
exercises, refer to the link:00_intro.html#intro[introduction].
Each exercise starts with a problem description. Read that and try to
solve the exercise. If you run into problems, consider reading the
hints (!interactive after the exercise!)(!book at the link:hints.html#hints[end of the book]!).
Full solutions to the exercises are not included in this
book, but you can find them online at
http://eloquentjavascript.net/code[_eloquentjavascript.net/code_].
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.
=== Looping a triangle ===
(((triangle (exercise))))Write a ((loop)) that makes seven calls to
`console.log` to output the following triangle:
----
#
##
###
####
#####
######
#######
----
It may be useful to know that you can find the length of a string by
writing `.length` after it.
[source,javascript]
----
var abc = "abc";
console.log(abc.length);
// → 3
----
ifdef::interactive_target[]
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.
[source,javascript]
----
// Your code here.
----
endif::interactive_target[]
!!hint!!
(((triangle (exercise))))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
link:02_program_structure.html#loops[even number printing example]
given earlier in the chapter, where the `for` loop was introduced.
Now consider the equivalence between numbers and strings of hash
characters. You can go from 1 to 2 by adding 1 (`+= 1`). You can go
from `"#"` to `"##"` by adding a character (`+= "#"`). Thus, your
solution can closely follow the number-printing program.
!!hint!!
=== FizzBuzz ===
(((FizzBuzz (exercise))))(((loop)))(((conditional execution)))Write a
program that uses `console.log` to print all the numbers from 1 to
100, with two exceptions. For numbers divisible by 3, print `"Fizz"`
instead of the number, and for numbers divisible by 5 (and not 3),
print `"Buzz"` instead.
When you have that working, modify your program to print `"FizzBuzz"`,
for numbers that are divisible by both 3 and 5 (and still print
`"Fizz"` or `"Buzz"` for numbers divisible by only one of those).
(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.)
ifdef::interactive_target[]
[source,javascript]
----
// Your code here.
----
endif::interactive_target[]
!!hint!!
(((FizzBuzz (exercise))))(((remainder operator)))(((% operator)))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 (`%`) operator for checking whether a number is divisible by
another number (has a remainder of zero).
In the first version, there are three possible outcomes for every
number, so you'll have to create an `if`/`else if`/`else` chain.
(((|| operator)))(((if keyword,chaining)))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 `||` operator.
!!hint!!
=== Chess board ===
(((chess board (exercise))))(((loop)))(((nesting,of loops)))(((newline
character)))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.
Passing this string to `console.log` should show something like this:
----
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
----
When you have a program that generates this pattern, define a
((variable)) `size = 8` and change the program so that it works for
any `size`, outputting a grid of the given width and height.
ifdef::interactive_target[]
[source,javascript]
----
// Your code here.
----
endif::interactive_target[]
!!hint!!