3. Los fundamentos de JavaScript
Nota: A partir de aquí, el término [JavaScript] se referirá siempre al estándar ECMAScript 6.
Dentro del proyecto JavaScript anterior, crea una carpeta llamada [bases]. Allí colocaremos los ejemplos de esta sección:

3.1. script [bases-01]
Para introducir los fundamentos de PHP7, utilizamos el siguiente código (ver párrafo enlazado):
1. <?php
2.
3. // this is a comment
4. // variable used without being declared
5. $name = "dupont";
6. // a screen display
7. print "name=$name\n";
8. // an array with elements of different types
9. $array = array("one", "two", 3, 4);
10. // its number of elements
11. $n = count($array);
12. // a loop
13. for ($i = 0; $i < $n; $i++) {
14. print "array[$i] = $array[$i]\n";
15. }
16. // Initializing 2 variables with the contents of an array
17. list($string1, $string2) = array("string1", "string2");
18. // concatenating the two strings
19. $string3 = $string1 . $string2;
20. // display result
21. print "[$string1,$string2,$string3]\n";
22. // function usage
23. display($string1);
24. // the type of a variable can be known
25. displayType("n", $n);
26. displayType("string1", $string1);
27. displayType("array", $array);
28. // the type of a variable can change during execution
29. $n = "has changed";
30. displayType("n", $n);
31. // a function can return a result
32. $res1 = f1(4);
33. print "res1=$res1\n";
34. // a function can return an array of values
35. list($res1, $res2, $res3) = f2();
36. print "(res1,res2,res3)=[$res1,$res2,$res3]\n";
37. // we could have retrieved these values into an array
38. $t = f2();
39. for ($i = 0; $i < count($t); $i++) {
40. print "t[$i]=$t[$i]\n";
41. }
42. // some tests
43. for ($i = 0; $i < count($t); $i++) {
44. // display only strings
45. if (getType($t[$i]) === "string") {
46. print "t[$i]=$t[$i]\n";
47. }
48. }
49. // comparison operators == and ===
50. if("2"==2){
51. print "With the == operator, the string 2 is equal to the integer 2\n";
52. }else{
53. print "with the == operator, the string 2 is not equal to the integer 2\n";
54. }
55. if("2"===2){
56. print "With the === operator, the string 2 is equal to the integer 2\n";
57. }
58. else{
59. print "with the === operator, the string 2 is not equal to the integer 2\n";
60. }
61. // other tests
62. for ($i = 0; $i < count($t); $i++) {
63. // only displays integers >10
64. if (getType($t[$i]) === "integer" and $t[$i] > 10) {
65. print "t[$i] = $t[$i]\n";
66. }
67. }
68. // a while loop
69. $t = [8, 5, 0, -2, 3, 4];
70. $i = 0;
71. $sum = 0;
72. while ($i < count($t) and $t[$i] > 0) {
73. print "t[$i]=$t[$i]\n";
74. $sum += $t[$i]; //$sum=$sum+$t[$i]
75. $i++; //$i=$i+1
76. }//while
77. print "sum=$sum\n";
78.
79. // end of program
80. exit;
81.
82. //----------------------------------
83. function display($string) {
84. // display $string
85. print "string=$string\n";
86. }
87.
88. //display
89. //----------------------------------
90. function displayType($name, $variable) {
91. // displays the type of $variable
92. print "type[variable $" . $name . "]=" . getType($variable) . "\n";
93. }
94.
95. //displayType
96. //----------------------------------
97. function f1($param) {
98. // add 10 to $param
99. return $param + 10;
100. }
101.
102. //----------------------------------
103. function f2() {
104. // returns 3 values
105. return array("one", 0, 100);
106. }
107. ?>
Traducido a JavaScript, el resultado es el siguiente código:
1. 'use strict';
2. // this is a comment
3. // constant
4. const name = "dupont";
5. // a screen display
6. console.log("name: ", name);
7. // an array with elements of different types
8. const array = ["one", "two", 3, 4];
9. // its number of elements
10. let n = array.length;
11. // a loop
12. for (let i = 0; i < n; i++) {
13. console.log("array[", i, "] = ", array[i]);
14. }
15. // Initializing 2 variables with the contents of an array
16. let [string1, string2] = ["string1", "string2"];
17. // concatenating the two strings
18. const string3 = string1 + string2;
19. // display result
20. console.log([string1, string2, string3]);
21. // using the function
22. display(string1);
23. // the type of a variable can be determined
24. displayType("n", n);
25. displayType("string1", string1);
26. displayType("array", array);
27. // the type of a variable can change during execution
28. n = "has changed";
29. afficheType("n", n);
30. // A function can return a result
31. let res1 = f1(4);
32. console.log("res1=", res1);
33. // a function can return an array of values
34. let res2, res3;
35. [res1, res2, res3] = f2();
36. console.log("(res1,res2,res3)=", [res1, res2, res3]);
37. // we could have retrieved these values in an array
38. let t = f2();
39. for (let i = 0; i < t.length; i++) {
40. console.log("t[i]=", t[i]);
41. }
42. // some tests
43. for (let i = 0; i < t.length; i++) {
44. // only displays strings
45. if (typeof (t[i]) === "string") {
46. console.log("t[i]=", t[i]);
47. }
48. }
49. // comparison operators == and ===
50. if ("2" == 2) {
51. console.log("With the == operator, the string 2 is equal to the integer 2");
52. } else {
53. console.log("with the == operator, the string 2 is not equal to the integer 2");
54. }
55. if ("2" === 2) {
56. console.log("With the === operator, the string 2 is equal to the integer 2");
57. } else {
58. console.log("With the === operator, the string '2' is not equal to the integer 2");
59. }
60. // other tests
61. for (let i = 0; i < t.length; i++) {
62. // displays only integers >10
63. if (typeof (t[i]) === "number" && Math.floor(t[i]) === t[i] && t[i] > 10) {
64. console.log("t[i]=", t[i]);
65. }
66. }
67. // a while loop
68. t = [8, 5, 0, -2, 3, 4];
69. let i = 0;
70. let sum = 0;
71. while (i < t.length && t[i] > 0) {
72. console.log("t[i]=", t[i]);
73. sum += t[i];
74. i++;
75. }
76. console.log("sum=", sum);
77.
78. // program terminates because there is no more executable code
79.
80. //display
81. //----------------------------------
82. function display(string) {
83. // displays string
84. console.log("string=", string);
85. }
86.
87. //displayType
88. //----------------------------------
89. function displayType(name, variable) {
90. // displays the variable type
91. console.log("type[variable ", name, "]=", typeof (variable));
92. }
93.
94. //----------------------------------
95. function f1(param) {
96. // adds 10 to param
97. return param + 10;
98. }
99.
100. //----------------------------------
101. function f2() {
102. // returns 3 values
103. return ["one", 0, 100];
104. }
Discutimos las diferencias entre el código PHP y ECMAScript 6 con la [use strict] declaración (línea 1):
- La primera diferencia es que en ECMAScript, las variables se declaran utilizando las siguientes palabras clave:
- [let] para declarar una variable cuyo valor puede cambiar durante la ejecución del código;
- [const] para declarar una variable cuyo valor no cambiará (es decir, una constante) durante la ejecución del código;
- También puedes utilizar la [var] palabra clave en lugar de [let]. Esta era la palabra clave utilizada en ECMAScript 5. No la usaremos en este curso;
- línea 6: el método [console.log] puede mostrar todo tipo de datos: cadenas, números, booleanos, matrices y objetos. El método PHP [print] no puede mostrar arrays y objetos de forma nativa. En la expresión [console.log] , [console] es un objeto y [log] es un método de ese objeto;
- línea 8: Las matrices de JavaScript son objetos referenciados por un puntero. Cuando escribimos:
const array = ["one", "two", 3, 4];
la variable [array] es un puntero al literal array ["uno", "dos", 3, 4]. La modificación del contenido de la matriz no cambia su puntero. Por lo tanto, un array se declara más a menudo con la [const] palabra clave. En PHP, un array no es referenciado por un puntero. Es un valor literal;
- Línea 12: La variable de bucle [i] se declara (let) dentro del bucle. La palabra clave [let] tiene alcance de bloque (código entre llaves). Por lo tanto, la variable [i] en la línea 12 sólo es accesible dentro del bucle;
- Línea 18: El operador de concatenación de cadenas es el operador + en JavaScript y el operador . en PHP. Una característica distintiva de este operador es que tiene precedencia sobre el operador de suma +. Así:
- en PHP, '1' + 2 da el número 3;
- en JavaScript, '1'+2 produce la cadena '12';
- línea 20: [console.log] puede mostrar matrices;
- línea 82: en JavaScript, no es posible especificar el tipo de los parámetros de una función;
- línea 91: el [typeof] operador permite determinar el tipo de un elemento de datos. Existen cuatro tipos: número, cadena, booleano y objeto. Tenga en cuenta que en JavaScript no hay [integer] tipo o [array] tipo. Como se ha mencionado, las matrices se manejan mediante punteros y entran en la categoría de objetos;
- líneas 50-59: Como en PHP, JavaScript tiene dos operadores de comparación, == y '===', con el mismo significado que en PHP. ESLint suele marcar el operador == como un error potencial. Usaremos consistentemente el operador '===';
- línea 79: podríamos haber incluido la [return] declaración, pero ESLint emite una advertencia de que [return] sólo debe utilizarse dentro de una función;
Ejecutamos este código:

Resultados de la ejecución:
1. [Running] C:\myprograms\laragon-lite\bin\nodejs\node-v10\node.exe "c:\Temp\19-09-01\javascript\bases\bases-01.js"
2. name: dupont
3. array[ 0 ] = one
4. array[ 1 ] = two
5. array[ 2 ] = 3
6. array[ 3 ] = 4
7. [ 'string1', 'string2', 'string1string2' ]
8. string = string1
9. type[variable n] = number
10. type[variable string1] = string
11. type[variable array] = object
12. type[variable n] = string
13. res1 = 14
14. (res1, res2, res3) = ['one', 0, 100]
15. t[0] = one
16. t[1] = 0
17. t[2] = 100
18. t[0] = one
19. With the == operator, the string 2 is equal to the integer 2
20. With the === operator, string 2 is not equal to the integer 2
21. t[ 2 ]= 100
22. t[ 0 ]= 8
23. t[ 1 ]= 5
24. sum= 13
25.
26. [Done] exited with code=0 in 0.316 seconds
En el código escrito, ESLint informa de dos errores:

- Cuando se pasa el ratón por encima de la línea roja de advertencia, se ve el mensaje de error [3]. Aquí, ESLint no reconoce que se están comparando dos constantes. Uno de los dos operandos debería ser una variable;
- en [4], una [Solución rápida] opción le permite descartar la advertencia si decide no corregir el error;

- en [5], puede desactivar la advertencia para la línea actual o para todo el archivo. Aquí elegimos esta última opción. La línea [6] se genera entonces al principio del fichero;
3.2. script [bases-02]
El [bases-02] script demuestra el uso de las [let] y [const] palabras clave:
1. 'use strict';
2. // To initialize a variable, use let or const
3. // let for variables
4. let x = 4;
5. x++;
6. console.log(x);
7. // const for constants
8. const y = 10;
9. x += y;
10. // not allowed
11. y++;
- La línea 11 provoca un error en tiempo de ejecución [1-2]. Es marcado por ESLint antes de la ejecución [3]:

3.3. script [bases-03]
El script [bases-03] examina el alcance de las variables en JavaScript:
1. 'use strict';
2. // variable scope
3. let count = 1;
4. function doSomething() {
5. // count is known here
6. console.log("count=", count);
7. }
8. // call
9. doSomething();
- la variable [count] declarada fuera de la función [doSomething] es sin embargo conocida dentro de esta función. Esta es una diferencia fundamental con respecto a PHP;
Ejecución
1. [Running] C:\myprograms\laragon-lite\bin\nodejs\node-v10\node.exe "c:\Temp\19-09-01\javascript\bases\bases-03.js"
2. count= 1
3.
4. [Done] exited with code=0 in 0.3 seconds
3.4. script [bases-04]
Una variable local oculta una variable global con el mismo nombre:
1. 'use strict';
2. // variable scope
3. const count = 1;
4. function doSomething() {
5. // the local variable hides the global variable
6. const count = 2;
7. console.log("count inside function=", count);
8. }
9. // global variable
10. console.log("count outside function=", count);
11. // local variable
12. doSomething();
Ejecución
1. [Running] C:\myprograms\laragon-lite\bin\nodejs\node-v10\node.exe "c:\Temp\19-09-01\javascript\bases\bases-04.js"
2. count outside function= 1
3. count inside function= 2
4.
5. [Done] exited with code=0 in 0.246 seconds
3.5. script [bases-05]
Una variable definida dentro de una función no se conoce fuera de ella:
1. 'use strict';
2. // variable scope
3. function doSomething() {
4. // variable local to the function
5. const count = 2;
6. console.log("count inside function=", count);
7. }
8. // Here, `count` is not defined
9. console.log("count outside function=", count);
10. doSomething();
ESLint informa de un error en la línea 9:

3.6. script [bases-06]
Las palabras clave [let] y [const] definen variables con [block] ámbito (código entre llaves), pero no la palabra clave [var]:
1. 'use strict';
2. // the [let] keyword allows you to define a block-scoped variable
3. {
4. // the variable [count] is only known within this block
5. let count = 1;
6. console.log("count=", count);
7. }
8. // Here, the variable [count] is not known
9. count++;
10.
11. // the keyword [const] allows you to define a block-scoped variable
12. {
13. // the variable [count2] is only known within this block
14. const count2 = 1;
15. console.log("count=", count2);
16. }
17. // here the variable [count2] is not known
18. count2++;
19.
20. // the keyword [var] does not allow defining a block-scoped variable
21. {
22. // the variable [count3] will be known globally
23. var count3 = 1;
24. console.log("count=", count3);
25. }
26. // here the variable [count3] is known
27. count3++;
Comentarios
- línea 5: la variable [count] sólo se conoce dentro del bloque de código en el que se declara (líneas 3-7);
- línea 14: la constante [count2] sólo se conoce dentro del bloque de código en el que se declara (líneas 12-16);
- línea 23: la variable [count3] se conoce fuera del bloque de código en el que se declara (líneas 21-25);
ESLint informa de los siguientes errores:

Por estas razones relacionadas con el ámbito de los bloques, a partir de ahora sólo utilizaremos las palabras clave [let] y [const] .
3.7. script [bases-07]
Tipos de datos en JavaScript:
1. 'use strict';
2.
3. // JavaScript data types
4. const var1 = 10;
5. const var2 = "abc";
6. const var3 = true;
7. const var4 = [1, 2, 3];
8. const var5 = {
9. name: 'axèle'
10. };
11. const var6 = function () {
12. return +3;
13. }
14. // Displaying types
15. console.log("typeof(var1)=", typeof(var1));
16. console.log("typeof(var2)=", typeof(var2));
17. console.log("typeof(var3)=", typeof (var3));
18. console.log("typeof(var4)=", typeof (var4));
19. console.log("typeof(var5)=", typeof(var5));
20. console.log("typeof(var6)=", typeof(var6));
Ejecución
1. [Running] C:\myprograms\laragon-lite\bin\nodejs\node-v10\node.exe "c:\Temp\19-09-01\javascript\bases\bases-07.js"
2. typeof(var1)= number
3. typeof(var2)= string
4. typeof(var3) = boolean
5. typeof(var4) = object
6. typeof(var5) = object
7. typeof(var6) = function
8.
9. [Done] exited with code=0 in 0.26 seconds
Comentarios
- línea 7 (código): un array es un objeto. Como tal, [var4] es un puntero al array, no el array en sí;
- línea 8 (código): [var5] es un puntero a un objeto literal. Veremos que los objetos literales de JavaScript se parecen mucho a las instancias de clase de PHP. Ellos también son referenciados a través de punteros;
- línea 11 (código): una variable puede ser de tipo [función] (línea 7 de los resultados);
3.8. script [bases-08]
Este script demuestra las posibles conversiones de tipo en JavaScript.
1. 'use strict';
2.
3. // implicit type conversions
4. // type --> bool
5. console.log("---------------[Implicit conversion to a boolean]------------------------------");
6. showBool("abcd");
7. showBool("");
8. showBool([1, 2, 3]);
9. showBool([]);
10. showBool(null);
11. showBool(0.0);
12. showBool(0);
13. showBool(4.6);
14. showBool({});
15. showBool(undefined);
16.
17. function showBool(data) {
18. // The conversion of data to a boolean is done automatically in the following test
19. console.log("[data=", data, "], [type(data)]=", typeof (data), "[boolean value(data)]=", data ? true : false);
20. }
21.
22. // Implicit type conversions to a numeric type
23. console.log("---------------[Implicit conversion to a number]------------------------------");
24. showNumber("12");
25. showNumber("45.67");
26. showNumber("abcd");
27.
28. function showNumber(data) {
29. // data + 1 doesn't work because JavaScript performs string concatenation instead of addition
30. const number = data * 1;
31. console.log("[data=", data, "], [type(data)]=", typeof (data), "[number]=", number, "[type(number)]=", typeof (number));
32. }
33.
34. // Explicit type conversions to a boolean
35. console.log("---------------[Explicit conversion to a boolean]------------------------------");
36. showBool2("abcd");
37. showBool2("");
38. showBool2([1, 2, 3]);
39. showBool2([]);
40. showBool2(null);
41. showBool2(0.0);
42. showBool2(0);
43. showBool2(4.6);
44. showBool2({});
45. showBool2(undefined);
46.
47. function showBool2(data) {
48. // The conversion of data to a boolean is done explicitly in the following test
49. console.log("[", data, "], [type(data)]=", typeof (data), "[boolean value(data)]=", Boolean(data));
50. }
51. // Explicit type conversions to Number
52. console.log("---------------[Explicit conversion to a number]------------------------------");
53. showNumber2("12.45");
54. showNumber2(67.8);
55. showNumber2(true);
56. showNumber2(null);
57.
58. function showNumber2(data) {
59. const number = Number(data);
60. console.log("[data=", data, "], [type(data)]=", typeof (data), "[number]=", number, "[type(number)]=", typeof (number));
61. }
62.
63. // to String
64. console.log("---------------[Explicit conversion to a string]------------------------------");
65. showString(5);
66. showString(6.7);
67. showString(false);
68. showString(null);
69.
70. function showString(data) {
71. const string = String(data);
72. console.log("[data=", data, "], [type(data)]=", typeof (data), "[string]=", string, "[type(string)]=", typeof (string));
73. }
74.
75. // some unexpected implicit conversions
76. console.log("---------------[Other cases]------------------------------");
77. const string1 = '1000.78';
78. // default string concatenation
79. const data1 = string1 + 1.034;
80. console.log("data1=", data1, "type=", typeof (data1));
81. const data2 = 1.034 + string1;
82. console.log("data2=", data2, "type=", typeof (data2));
83. // Explicit conversion to number
84. const data3 = Number(string1) + 1.034;
85. console.log("data3=", data3, "type=", typeof (data3));
86. // true is converted to the number 1
87. const data4 = true * 1.18;
88. console.log("data4=", data4, "type=", typeof (data4));
89. // false is converted to the number 0
90. const data5 = false * 1.18;
91. console.log("data5=", data5, "type=", typeof (data5));
Ejecución
1. [Running] C:\myprograms\laragon-lite\bin\nodejs\node-v10\node.exe "c:\Data\st-2019\dev\es6\javascript\bases\bases-08.js"
2. ---------------[Implicit conversion to a boolean]------------------------------
3. [data= abcd ], [type(data)]= string [boolean value(data)]= true
4. [data= ], [type(data)]= string [boolean value(data)]= false
5. [data= [ 1, 2, 3 ] ], [type(data)]= object [boolean value(data)]= true
6. [data= [] ], [type(data)]= object [boolean value(data)]= true
7. [data= null ], [type(data)]= object [boolean value(data)]= false
8. [data= 0 ], [type(data)]= number [boolean value(data)]= false
9. [data= 0 ], [type(data)]= number [boolean value(data)]= false
10. [data= 4.6 ], [type(data)]= number [boolean value(data)]= true
11. [data= {} ], [type(data)]= object [boolean value(data)]= true
12. [data= undefined ], [type(data)]= undefined [boolean value(data)]= false
13. ---------------[Implicit conversion to a number]------------------------------
14. [data= 12 ], [type(data)]= string [number]= 12 [type(number)]= number
15. [data= 45.67 ], [type(data)]= string [number]= 45.67 [type(number)]= number
16. [data= abcd ], [type(data)]= string [number]= NaN [type(number)]= number
17. ---------------[Explicit conversion to a Boolean]------------------------------
18. [ abcd ], [type(data)]= string [boolean value(data)]= true
19. [ ], [type(data)]= string [boolean value(data)]= false
20. [ [ 1, 2, 3 ] ], [type(data)]= object [boolean value(data)]= true
21. [ [] ], [type(data)]= object [boolean value(data)]= true
22. [ null ], [type(data)]= object [boolean value(data)]= false
23. [ 0 ], [type(data)]= number [boolean value(data)]= false
24. [ 0 ], [type(data)]= number [boolean value(data)]= false
25. [ 4.6 ], [type(data)]= number [boolean value(data)]= true
26. [ {} ], [type(data)]= object [boolean value(data)]= true
27. [undefined], [type(data)]= undefined [boolean value(data)]= false
28. ---------------[Explicit conversion to a number]------------------------------
29. [data= 12.45 ], [type(data)]= string [number]= 12.45 [type(number)]= number
30. [data= 67.8 ], [type(data)]= number [number]= 67.8 [type(number)]= number
31. [data= true ], [type(data)]= boolean [number]= 1 [type(number)]= number
32. [data= null ], [type(data)]= object [number]= 0 [type(number)]= number
33. ---------------[Explicit conversion to a string]------------------------------
34. [data= 5 ], [type(data)]= number [string]= 5 [type(string)]= string
35. [data= 6.7 ], [type(data)]= number [string]= 6.7 [type(string)]= string
36. [data= false ], [type(data)]= boolean [string]= false [type(string)]= string
37. [data= null ], [type(data)]= object [string]= null [type(string)]= string
38. ---------------[Other cases]------------------------------
39. data1= 1000.781.034 type= string
40. data2= 1.0341000.78 type= string
41. data3= 1001.814 type= number
42. data4= 1.18 type= number
43. data5= 0 type= number