You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This chapter briefly recaps the features of JavaScript that we've learned by now, paying special attention to subtle moments.
3
+
Este capítulo resume brevemente las características de JavaScript que hemos aprendido hasta ahora, prestando especial atención a los momentos sutiles.
4
4
5
-
## Code structure
5
+
## Estructura de Código
6
6
7
-
Statements are delimited with a semicolon:
7
+
Las declaraciones se delimitan con un punto y coma:
8
8
9
9
```js run no-beautify
10
-
alert('Hello'); alert('World');
10
+
alert('Hola'); alert('Mundo');
11
11
```
12
12
13
-
Usually, a line-break is also treated as a delimiter, so that would also work:
13
+
Usualmente, un salto de línea también se trata como un delimitador, por lo que también funcionaría:
14
14
15
15
```js run no-beautify
16
-
alert('Hello')
17
-
alert('World')
16
+
alert('Hola')
17
+
alert('Mundo')
18
18
```
19
19
20
-
That's called "automatic semicolon insertion". Sometimes it doesn't work, for instance:
20
+
Eso se llama "inserción automática de punto y coma". A veces no funciona, por ejemplo:
21
21
22
22
```js run
23
-
alert("There will be an error after this message")
23
+
alert("Habrá un error después de este mensaje.")
24
+
24
25
25
26
[1, 2].forEach(alert)
26
27
```
27
28
28
-
Most codestyle guides agree that we should put a semicolon after each statement.
29
+
La mayoría de las guías de estilo de código coinciden en que debemos poner un punto y coma después de cada declaración.
29
30
30
-
Semicolons are not required after code blocks `{...}`and syntax constructs with them like loops:
31
+
Los puntos y comas no son necesarios después los bloques de codigo `{...}`y los constructores de sintaxis como los bucles:
31
32
32
33
```js
33
34
functionf() {
34
-
// no semicolon needed after function declaration
35
+
// no se necesita punto y coma después de la declaración de función
35
36
}
36
37
37
38
for(;;) {
38
-
// no semicolon needed after the loop
39
+
// no se necesita punto y coma después del bucle
39
40
}
40
41
```
41
42
42
-
...But even if we can put an "extra" semicolon somewhere, that's not an error. It will be ignored.
43
+
...Pero incluso si colocasemos un punto y coma "extra" en alguna parte, eso no es un error. Solo sería ignorado.
43
44
44
-
More in: <info:structure>.
45
+
Más en: <info:structure>.
45
46
46
-
## Strict mode
47
+
## Modo estricto
47
48
48
-
To fully enable all features of modern JavaScript, we should start scripts with`"use strict"`.
49
+
Para habilitar completamente todas las características de JavaScript moderno, debemos comenzar los scripts con`"use strict"`.
49
50
50
51
```js
51
52
'use strict';
52
53
53
54
...
54
55
```
55
56
56
-
The directive must be at the top of a script or at the beginning of a function.
57
+
La directiva debe estar en la parte superior de un script o al comienzo de una función.
57
58
58
-
Without `"use strict"`, everything still works, but some features behave in the old-fashion, "compatible" way. We'd generally prefer the modern behavior.
59
+
Sin la directiva `"use strict"`, todo sigue funcionando, pero algunas características se comportan de la manera antigua y "compatible". Generalmente preferimos el comportamiento moderno.
59
60
60
-
Some modern features of the language (like classes that we'll study in the future) enable strict mode implicitly.
61
+
Algunas características modernas del lenguaje (como las clases que estudiaremos en el futuro) activan el modo estricto implícitamente.
61
62
62
-
More in: <info:strict-mode>.
63
+
Más en: <info:strict-mode>.
63
64
64
65
## Variables
65
66
66
-
Can be declared using:
67
+
Se pueden declarar usando:
67
68
68
69
-`let`
69
-
-`const` (constant, can't be changed)
70
-
-`var` (old-style, will see later)
70
+
-`const` (constante, no se puede cambiar)
71
+
-`var` (estilo antiguo, lo veremos más tarde)
72
+
71
73
72
-
A variable name can include:
73
-
-Letters and digits, but the first character may not be a digit.
74
-
-Characters `$`and`_`are normal, on par with letters.
75
-
-Non-Latin alphabets and hieroglyphs are also allowed, but commonly not used.
74
+
Un nombre de variable puede incluir:
75
+
-Letras y dígitos, pero el primer carácter puede no ser un dígito.
76
+
-Los caracteres `$`y`_`son normales, al igual que las letras.
77
+
-Los alfabetos y jeroglíficos no latinos también están permitidos, pero comúnmente no se usan.
76
78
77
-
Variables are dynamically typed. They can store any value:
79
+
Las variables se escriben dinámicamente. Pueden almacenar cualquier valor:
78
80
79
81
```js
80
82
let x =5;
81
83
x ="John";
82
84
```
83
85
84
-
There are 7 data types:
86
+
Hay 7 tipos de datos:
85
87
86
-
-`number`for both floating-point and integer numbers,
87
-
-`string`for strings,
88
-
-`boolean`for logical values: `true/false`,
89
-
-`null` -- a type with a single value`null`, meaning "empty" or "does not exist",
90
-
-`undefined` -- a type with a single value`undefined`, meaning "not assigned",
91
-
-`object`and`symbol` -- for complex data structures and unique identifiers, we haven't learnt them yet.
88
+
-`number`tanto para números de punto flotante como enteros,
89
+
-`string`para textos,
90
+
-`boolean`para valores lógicos: `true/false`,
91
+
-`null` -- un tipo con un solo valor`null`, que significa "vacío" o "no existe",
92
+
-`undefined` -- un tipo con un solo valor`undefined`, que significa "no asignado",
93
+
-`object`y`symbol` -- para estructuras de datos complejas e identificadores únicos, aún no los hemos aprendido.
92
94
93
-
The `typeof`operator returns the type for a value, with two exceptions:
95
+
El operador `typeof`devuelve el tipo de un valor, con dos excepciones:
94
96
```js
95
-
typeofnull=="object"// error in the language
96
-
typeoffunction(){} =="function"//functions are treated specially
97
+
typeofnull=="object"// error del lenguaje
98
+
typeoffunction(){} =="function"//las funciones son tratadas especialmente
97
99
```
98
100
99
-
More in: <info:variables>and<info:types>.
101
+
Más en: <info:variables>y<info:types>.
100
102
101
-
## Interaction
103
+
## Interacción
102
104
103
-
We're using a browser as a working environment, so basic UI functions will be:
105
+
Estamos utilizando un navegador como entorno de trabajo, por lo que las funciones básicas de la interfaz de usuario serán:
: Ask a `question`, and return either what the visitor entered or `null`if they pressed "cancel".
108
+
: Hace una pregunta `question`, y devuelve lo que ingresó el visitante o`null`si presionaron "cancelar".
107
109
108
110
[`confirm(question)`](mdn:api/Window/confirm)
109
-
: Ask a `question` and suggest to choose between Ok and Cancel. The choice is returned as`true/false`.
111
+
: Hace una pregunta `question`, y sugiere elegir entre Aceptar y Cancelar. La eleccion se devuelve como booleano`true/false`.
110
112
111
113
[`alert(message)`](mdn:api/Window/alert)
112
-
: Output a`message`.
114
+
: Muestra un`message`.
113
115
114
-
All these functions are *modal*, they pause the code execution and prevent the visitor from interacting with the page until they answer.
116
+
Todas estas funciones son *modales*, pausan la ejecución del código y evitan que el visitante interactúe con la página hasta que responda.
115
117
116
-
For instance:
118
+
Por ejemplo:
117
119
118
120
```js run
119
-
let userName =prompt("Your name?", "Alice");
120
-
let isTeaWanted =confirm("Do you want some tea?");
121
+
let userName =prompt("¿Su nombre?", "Alice");
122
+
let isTeaWanted =confirm("¿Quiere té?");
121
123
122
-
alert( "Visitor: "+ userName ); // Alice
123
-
alert( "Tea wanted: "+ isTeaWanted ); // true
124
+
alert( "Visitante: "+ userName ); // Alice
125
+
alert( "Quiere te: "+ isTeaWanted ); // true
124
126
```
125
127
126
-
More in: <info:alert-prompt-confirm>.
128
+
Más en: <info:alert-prompt-confirm>.
127
129
128
-
## Operators
130
+
## Operadores
129
131
130
-
JavaScript supports the following operators:
132
+
JavaScript soporta los siguientes operadores:
131
133
132
-
Arithmetical
133
-
: Regular: `* + - /`, also`%`for the remainder and`**`for power of a number.
134
+
Aritmeticos
135
+
: Regulares: `* + - /`, tambien`%`para los restos y`**`para aplicar potencia de un número.
134
136
135
-
The binary plus `+` concatenates strings. And if any of the operands is a string, the other one is converted to string too:
137
+
El binario más `+` concatena textos. Y si alguno de los operandos es un texto, el otro también se convierte en texto:
136
138
137
139
```js run
138
-
alert( '1' + 2 ); // '12', string
139
-
alert( 1 + '2' ); // '12', string
140
+
alert( '1' + 2 ); // '12', texto
141
+
alert( 1 + '2' ); // '12', texto
140
142
```
141
143
142
-
Assignments
143
-
: There is a simple assignment: `a = b`and combined ones like`a *= 2`.
144
+
Asignaciones
145
+
: He aqui una asignacion simple: `a = b`y una combinada`a *= 2`.
144
146
145
-
Bitwise
146
-
: Bitwise operators work with integers on bit-level: see the [docs](mdn:/JavaScript/Reference/Operators/Bitwise_Operators)when they are needed.
147
+
Operador bit a bit
148
+
: Los operadores bit a bit funcionan con enteros a nivel de bit: mire la [documentación](mdn:/JavaScript/Reference/Operators/Bitwise_Operators)cuando son necesarios.
147
149
148
-
Ternary
149
-
: The only operator with three parameters: `cond ? resultA : resultB`. If`cond`is truthy, returns`resultA`, otherwise`resultB`.
150
+
Ternarios
151
+
: El único operador con 3 parametros: `cond ? resultA : resultB`. Sí`cond`es verdadera, devuelve`resultA`, de lo contrario`resultB`.
150
152
151
-
Logical operators
152
-
: Logical AND `&&`and OR`||`perform short-circuit evaluation and then return the value where it stopped. Logical NOT `!`converts the operand to boolean type and returns the inverse value.
153
+
Operadores Lógicos
154
+
: Los operadores lógicos Y `&&`y Ó`||`realizan una evaluación de circuito corto y luego devuelven el valor donde se detuvo. El operador lógico NOT `!`convierte el operando a tipo booleano y devuelve el valor inverso.
153
155
154
-
Comparisons
155
-
: Equality check `==`for values of different types converts them to a number (except`null`and`undefined`that equal each other and nothing else), so these are equal:
156
+
Comparaciones
157
+
: Revision de igualdad `==`para valores de diferentes tipos los convierte en un número (excepto`null`y`undefined`que son iguales entre sí y nada más), por lo que son iguales:
156
158
157
159
```js run
158
160
alert( 0 == false ); // true
159
161
alert( 0 == '' ); // true
160
162
```
161
163
162
-
Other comparisons convert to a number as well.
164
+
Otras comparaciones también se convierten en un número.
163
165
164
-
The strict equality operator `===` doesn't do the conversion: different types always mean different values for it, so:
166
+
El operador de igualdad estricta `===` no realiza la conversión: diferentes tipos de valores siempre significan diferentes valores para ella, así que:
165
167
166
-
Values `null` and `undefined` are special: they equal `==` each other and don't equal anything else.
168
+
Valores `null` y `undefined` son especiales: son iguales `==` el uno al otro y no son iguales a nada más.
167
169
168
-
Greater/less comparisons compare strings character-by-character, other types are converted to a number.
170
+
Las comparaciones mayores / menores comparan las cadenas carácter por carácter, otros tipos de datos se convierten en un número.
169
171
170
-
Other operators
171
-
: There are few others, like a comma operator.
172
+
Otros operadores
173
+
: Hay algunos otros, como un operador de coma.
172
174
173
-
More in: <info:operators>, <info:comparison>, <info:logical-operators>.
175
+
Más en: <info:operators>, <info:comparison>, <info:logical-operators>.
174
176
175
-
## Loops
177
+
## Bucles
176
178
177
-
-We covered 3 types of loops:
179
+
-Cubrimos 3 tipos de bucles:
178
180
179
181
```js
180
182
// 1
@@ -193,42 +195,42 @@ More in: <info:operators>, <info:comparison>, <info:logical-operators>.
193
195
}
194
196
```
195
197
196
-
-The variable declared in`for(let...)`loop is visible only inside the loop. But we can also omit`let`and reuse an existing variable.
197
-
-Directives`break/continue`allow to exit the whole loop/current iteration. Uselabels to break nested loops.
198
+
-La variable declarada en el bucle `for(let...)`sólo es visible dentro del bucle. Pero también podemos omitir el`let`y reutilizar una variable existente.
199
+
-Directivas`break/continue`permiten salir de todo el ciclo/iteración actual. Useetiquetas para romper bucles anidados.
198
200
199
-
Details in:<info:while-for>.
201
+
Detalles en:<info:while-for>.
200
202
201
-
Later we'll study more types of loops to deal with objects.
203
+
Más adelante estudiaremos más tipos de bucles para tratar con objetos.
202
204
203
-
## The "switch" construct
205
+
## El constructo "switch"
204
206
205
-
The "switch" construct can replace multiple `if` checks. It uses `===` (strict equality) for comparisons.
207
+
El constructo "switch"puede reemplazar múltiples revisiones con `if`. Utiliza`===` (igualdad estricta) para comparar.
206
208
207
-
For instance:
209
+
Por ejemplo:
208
210
209
211
```js run
210
-
let age = prompt('Your age?', 18);
212
+
let age = prompt('¿Su Edad?', 18);
211
213
212
214
switch (age) {
213
215
case 18:
214
-
alert("Won't work"); // the result of prompt is a string, not a number
216
+
alert("No funciona"); // el resultado de la petición es un string, no un número
215
217
216
218
case "18":
217
-
alert("This works!");
219
+
alert("¡Funciona!");
218
220
break;
219
221
220
222
default:
221
-
alert("Any value not equal to one above");
223
+
alert("Cualquier valor no igual a uno arriba");
222
224
}
223
225
```
224
226
225
-
Details in: <info:switch>.
227
+
Detalles en:<info:switch>.
226
228
227
-
## Functions
229
+
## Funciones
228
230
229
-
We covered three ways to create a function in JavaScript:
231
+
Cubrimos tres formas de crear una función en JavaScript:
230
232
231
-
1. Function Declaration: the function in the main code flow
233
+
1. Declaración de función: la función en el flujo del código principal
232
234
233
235
```js
234
236
function sum(a, b) {
@@ -238,7 +240,7 @@ We covered three ways to create a function in JavaScript:
238
240
}
239
241
```
240
242
241
-
2. Function Expression: the function in the context of an expression
243
+
2.Expresión de función: la función en el contexto de una expresión
242
244
243
245
```js
244
246
let sum = function(a, b) {
@@ -247,10 +249,9 @@ We covered three ways to create a function in JavaScript:
247
249
return result;
248
250
}
249
251
```
252
+
Las expresiones de función pueden tener un nombre, como `sum = function name(a, b)`, pero ese `name` solo es visible dentro de esa función.
250
253
251
-
Function expressions can have a name, like `sum = function name(a, b)`, but that `name` is only visible inside that function.
252
-
253
-
3. Arrow functions:
254
+
3. Funciones de flecha:
254
255
255
256
```js
256
257
// expression at the right side
@@ -269,19 +270,18 @@ We covered three ways to create a function in JavaScript:
269
270
let double = n => n * 2;
270
271
```
271
272
272
-
273
-
- Functions may have local variables: those declared inside its body. Such variables are only visible inside the function.
274
-
- Parameters can have default values: `function sum(a = 1, b = 2) {...}`.
275
-
- Functions always return something. If there's no `return` statement, then the result is `undefined`.
273
+
- Las funciones pueden tener variables locales: aquellas declaradas dentro de su cuerpo. Estas variables solo son visibles dentro de la función.
274
+
- Los parámetros pueden tener valores predeterminados:`function sum(a = 1, b = 2) {...}`.
275
+
- Las funciones siempre devuelven algo. Si no hay `return`, entonces el resultado es `undefined`.
276
276
277
277
278
-
| Function Declaration | Function Expression |
278
+
|Declaración de funciones | Expresión de funciones|
279
279
|----------------------|---------------------|
280
-
| visible in the whole code block | created when the execution reaches it |
281
-
| - | can have a name, visible only inside the function |
280
+
| visible en todo el bloque de código | creado cuando la ejecución lo alcanza|
281
+
|-|puede tener un nombre, visible solo dentro de la función|
282
282
283
-
More: see <info:function-basics>, <info:function-expressions-arrows>.
That was a brief list of JavaScript features. As of now we've studied only basics. Further in the tutorial you'll find more specials and advanced features of JavaScript.
287
+
Esa fue una breve lista de características de JavaScript. Por ahora solo hemos estudiado lo básico. Más adelante en el tutorial encontrará más características especiales y avanzadas de JavaScript.
0 commit comments