Skip to content

Commit af3f637

Browse files
authored
Merge pull request #229 from vplentinax/Giorgosaud
JavaScript specials
2 parents e94892d + 53a98fd commit af3f637

File tree

1 file changed

+108
-108
lines changed
  • 1-js/02-first-steps/18-javascript-specials

1 file changed

+108
-108
lines changed
Lines changed: 108 additions & 108 deletions
Original file line numberDiff line numberDiff line change
@@ -1,180 +1,182 @@
1-
# JavaScript specials
1+
# Especiales JavaScript
22

3-
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.
44

5-
## Code structure
5+
## Estructura de Código
66

7-
Statements are delimited with a semicolon:
7+
Las declaraciones se delimitan con un punto y coma:
88

99
```js run no-beautify
10-
alert('Hello'); alert('World');
10+
alert('Hola'); alert('Mundo');
1111
```
1212

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:
1414

1515
```js run no-beautify
16-
alert('Hello')
17-
alert('World')
16+
alert('Hola')
17+
alert('Mundo')
1818
```
1919

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:
2121

2222
```js run
23-
alert("There will be an error after this message")
23+
alert("Habrá un error después de este mensaje.")
24+
2425

2526
[1, 2].forEach(alert)
2627
```
2728

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.
2930

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:
3132

3233
```js
3334
function f() {
34-
// no semicolon needed after function declaration
35+
// no se necesita punto y coma después de la declaración de función
3536
}
3637

3738
for(;;) {
38-
// no semicolon needed after the loop
39+
// no se necesita punto y coma después del bucle
3940
}
4041
```
4142

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.
4344

44-
More in: <info:structure>.
45+
Más en: <info:structure>.
4546

46-
## Strict mode
47+
## Modo estricto
4748

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"`.
4950

5051
```js
5152
'use strict';
5253

5354
...
5455
```
5556

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.
5758

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.
5960

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.
6162

62-
More in: <info:strict-mode>.
63+
Más en: <info:strict-mode>.
6364

6465
## Variables
6566

66-
Can be declared using:
67+
Se pueden declarar usando:
6768

6869
- `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+
7173

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.
7678

77-
Variables are dynamically typed. They can store any value:
79+
Las variables se escriben dinámicamente. Pueden almacenar cualquier valor:
7880

7981
```js
8082
let x = 5;
8183
x = "John";
8284
```
8385

84-
There are 7 data types:
86+
Hay 7 tipos de datos:
8587

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.
9294

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:
9496
```js
95-
typeof null == "object" // error in the language
96-
typeof function(){} == "function" // functions are treated specially
97+
typeof null == "object" // error del lenguaje
98+
typeof function(){} == "function" // las funciones son tratadas especialmente
9799
```
98100

99-
More in: <info:variables> and <info:types>.
101+
Más en: <info:variables> y <info:types>.
100102

101-
## Interaction
103+
## Interacción
102104

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:
104106

105107
[`prompt(question, [default])`](mdn:api/Window/prompt)
106-
: 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".
107109

108110
[`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`.
110112

111113
[`alert(message)`](mdn:api/Window/alert)
112-
: Output a `message`.
114+
: Muestra un `message`.
113115

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.
115117

116-
For instance:
118+
Por ejemplo:
117119

118120
```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é?");
121123

122-
alert( "Visitor: " + userName ); // Alice
123-
alert( "Tea wanted: " + isTeaWanted ); // true
124+
alert( "Visitante: " + userName ); // Alice
125+
alert( "Quiere te: " + isTeaWanted ); // true
124126
```
125127

126-
More in: <info:alert-prompt-confirm>.
128+
Más en: <info:alert-prompt-confirm>.
127129

128-
## Operators
130+
## Operadores
129131

130-
JavaScript supports the following operators:
132+
JavaScript soporta los siguientes operadores:
131133

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.
134136

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:
136138

137139
```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
140142
```
141143

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`.
144146

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.
147149

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`. `cond` es verdadera, devuelve `resultA`, de lo contrario `resultB`.
150152

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.
153155

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:
156158

157159
```js run
158160
alert( 0 == false ); // true
159161
alert( 0 == '' ); // true
160162
```
161163

162-
Other comparisons convert to a number as well.
164+
Otras comparaciones también se convierten en un número.
163165

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:
165167

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.
167169

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.
169171

170-
Other operators
171-
: There are few others, like a comma operator.
172+
Otros operadores
173+
: Hay algunos otros, como un operador de coma.
172174

173-
More in: <info:operators>, <info:comparison>, <info:logical-operators>.
175+
Más en: <info:operators>, <info:comparison>, <info:logical-operators>.
174176

175-
## Loops
177+
## Bucles
176178

177-
- We covered 3 types of loops:
179+
- Cubrimos 3 tipos de bucles:
178180

179181
```js
180182
// 1
@@ -193,42 +195,42 @@ More in: <info:operators>, <info:comparison>, <info:logical-operators>.
193195
}
194196
```
195197

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. Use labels 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. Use etiquetas para romper bucles anidados.
198200

199-
Details in: <info:while-for>.
201+
Detalles en: <info:while-for>.
200202

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.
202204

203-
## The "switch" construct
205+
## El constructo "switch"
204206

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.
206208

207-
For instance:
209+
Por ejemplo:
208210

209211
```js run
210-
let age = prompt('Your age?', 18);
212+
let age = prompt('¿Su Edad?', 18);
211213
212214
switch (age) {
213215
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
215217
216218
case "18":
217-
alert("This works!");
219+
alert("¡Funciona!");
218220
break;
219221
220222
default:
221-
alert("Any value not equal to one above");
223+
alert("Cualquier valor no igual a uno arriba");
222224
}
223225
```
224226

225-
Details in: <info:switch>.
227+
Detalles en: <info:switch>.
226228

227-
## Functions
229+
## Funciones
228230

229-
We covered three ways to create a function in JavaScript:
231+
Cubrimos tres formas de crear una función en JavaScript:
230232

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
232234

233235
```js
234236
function sum(a, b) {
@@ -238,7 +240,7 @@ We covered three ways to create a function in JavaScript:
238240
}
239241
```
240242

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
242244

243245
```js
244246
let sum = function(a, b) {
@@ -247,10 +249,9 @@ We covered three ways to create a function in JavaScript:
247249
return result;
248250
}
249251
```
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.
250253

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:
254255

255256
```js
256257
// expression at the right side
@@ -269,19 +270,18 @@ We covered three ways to create a function in JavaScript:
269270
let double = n => n * 2;
270271
```
271272

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`.
276276

277277

278-
| Function Declaration | Function Expression |
278+
| Declaración de funciones | Expresión de funciones |
279279
|----------------------|---------------------|
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 |
282282

283-
More: see <info:function-basics>, <info:function-expressions-arrows>.
283+
Más: ver <info:function-basics>, <info:function-expressions-arrows>.
284284

285-
## More to come
285+
## Más por venir
286286

287-
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

Comments
 (0)