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
```smart header="This article is for understanding old scripts"
5
-
The information in this article is useful for understanding old scripts.
4
+
```smart header="Este artículo es para entender código antiguo"
5
+
La información en este artículo es útil para entender código antiguo.
6
6
7
-
That's not how we write a new code.
7
+
Así no es como escribimos código moderno.
8
8
```
9
9
10
-
In the very first chapter about[variables](info:variables), we mentioned three ways of variable declaration:
10
+
En el primer capítulo acerca de[variables](info:variables), mencionamos tres formas de declarar una variable:
11
11
12
12
1.`let`
13
13
2.`const`
14
14
3.`var`
15
15
16
-
The `var`declaration is similar to`let`. Most of the time we can replace `let`by`var`or vice-versa and expect things to work:
16
+
La declaración `var`es similar a`let`. Casi siempre podemos reemplazar `let`por`var`o viceversa y esperar que las cosas funcionen:
17
17
18
18
```js run
19
-
var message ="Hi";
20
-
alert(message); //Hi
19
+
var message ="Hola";
20
+
alert(message); //Hola
21
21
```
22
22
23
-
But internally`var`is a very different beast, that originates from very old times. It's generally not used in modern scripts, but still lurks in the old ones.
23
+
Pero internamente`var`es una bestia diferente, originaria de muy viejas épocas. Generalmente no se usa en código moderno pero aún habita en el antiguo.
24
24
25
-
If you don't plan on meeting such scripts you may even skip this chapter or postpone it.
25
+
Si no planeas encontrarte con tal código bien puedes saltar este capítulo o posponerlo, pero hay posibilidades de que esta bestia pueda morderte más tarde.
26
26
27
-
On the other hand, it's important to understand differences when migrating old scripts from `var`to`let`, to avoid odd errors.
27
+
Por otro lado, es importante entender las diferencias cuando se migra antiguo código de `var`a`let` para evitar extraños errores.
28
28
29
-
## "var" has no block scope
29
+
## "var" no tiene alcance (visibilidad) de bloque.
30
30
31
-
Variables, declared with `var`, are either function-wide or global. They are visible through blocks.
31
+
Las variables declaradas con `var` pueden: tener a la función como entorno de visibilidad, o bien ser globales. Su visibilidad atraviesa los bloques.
32
32
33
-
For instance:
33
+
Por ejemplo:
34
34
35
35
```js run
36
36
if (true) {
37
-
var test =true; //use "var" instead of "let"
37
+
var test =true; //uso de "var" en lugar de "let"
38
38
}
39
39
40
40
*!*
41
-
alert(test); // true, the variable lives after if
41
+
alert(test); // true, la variable vive después del if
42
42
*/!*
43
43
```
44
44
45
-
As`var`ignores code blocks, we've got a global variable `test`.
45
+
Como`var`ignora los bloques de código, tenemos una variable global `test`.
46
46
47
-
If we used `let test`instead of `var test`, then the variable would only be visible inside`if`:
47
+
Si usáramos `let test`en vez de `var test`, la variable sería visible solamente dentro del`if`:
48
48
49
49
```js run
50
50
if (true) {
51
-
let test =true; //use "let"
51
+
let test =true; //uso de "let"
52
52
}
53
53
54
54
*!*
55
-
alert(test); // Error: test is not defined
55
+
alert(test); // Error: test no está definido
56
56
*/!*
57
57
```
58
58
59
-
The same thing for loops: `var`cannot be block- or loop-local:
59
+
Lo mismo para los bucles: `var`no puede ser local en los bloques ni en los bucles:
60
60
61
61
```js
62
62
for (var i =0; i <10; i++) {
63
63
// ...
64
64
}
65
65
66
66
*!*
67
-
alert(i); // 10, "i" is visible after loop, it's a global variable
67
+
alert(i); // 10, "i" es visible después del bucle, es una variable global
68
68
*/!*
69
69
```
70
70
71
-
If a code block is inside a function, then `var`becomes a function-level variable:
71
+
Si un bloque de código está dentro de una función, `var`se vuelve una variable a nivel de función:
72
72
73
73
```js run
74
74
functionsayHi() {
75
75
if (true) {
76
76
var phrase ="Hello";
77
77
}
78
78
79
-
alert(phrase); //works
79
+
alert(phrase); //funciona
80
80
}
81
81
82
82
sayHi();
83
-
alert(phrase); // Error: phrase is not defined (Check the Developer Console)
83
+
alert(phrase); // Error: phrase no está definida (Revise consola de desarrollador)
84
84
```
85
85
86
-
As we can see, `var`pierces through `if`, `for`or other code blocks. That's because a long time ago in JavaScript blocks had no Lexical Environments. And`var`is a remnant of that.
86
+
Como podemos ver, `var`atraviesa `if`, `for`u otros bloques. Esto es porque mucho tiempo atrás los bloques en JavaScript no tenían ambientes léxicos. Y`var`es un remanente de aquello.
87
87
88
-
## "var" tolerates redeclarations
88
+
## "var" tolera redeclaraciones
89
89
90
-
If we declare the same variable with`let`twice in the same scope, that's an error:
90
+
Declarar la misma variable con`let`dos veces en el mismo entorno es un error:
91
91
92
92
```js run
93
93
let user;
94
-
let user; // SyntaxError: 'user' has already been declared
94
+
let user; // SyntaxError: 'user' ya fue declarado
95
95
```
96
96
97
-
With`var`, we can redeclare a variable any number of times. If we use `var`with an already-declared variable, it's just ignored:
97
+
Con`var` podemos redeclarar una variable muchas veces. Si usamos `var`con una variable ya declarada, simplemente se ignora:
98
98
99
99
```js run
100
100
var user ="Pete";
101
101
102
-
var user ="John"; //this "var" does nothing (already declared)
103
-
// ...it doesn't trigger an error
102
+
var user ="John"; //este "var" no hace nada (ya estaba declarado)
103
+
// ...no dispara ningún error
104
104
105
105
alert(user); // John
106
106
```
107
107
108
-
## "var" variables can be declared below their use
108
+
## Las variables "var" pueden ser declaradas debajo del lugar en donde se usan
109
109
110
-
`var`declarations are processed when the function starts (or script starts for globals).
110
+
Las declaraciones `var`son procesadas cuando se inicia la función (o se inicia el script para las globales).
111
111
112
-
In other words, `var`variables are defined from the beginning of the function, no matter where the definition is (assuming that the definition is not in the nested function).
112
+
En otras palabras, las variables `var`son definidas desde el inicio de la función, no importa dónde esté tal definición (asumiendo que la definición no está en una función anidada).
113
113
114
-
So this code:
114
+
Entonces el código:
115
115
116
116
```js run
117
117
functionsayHi() {
@@ -126,7 +126,7 @@ function sayHi() {
126
126
sayHi();
127
127
```
128
128
129
-
...Is technically the same as this (moved `var phrase`above):
129
+
...es técnicamente lo mismo que esto (se movió `var phrase`hacia arriba):
130
130
131
131
```js run
132
132
functionsayHi() {
@@ -141,7 +141,7 @@ function sayHi() {
141
141
sayHi();
142
142
```
143
143
144
-
...Or even as this (remember, code blocks are ignored):
144
+
...O incluso esto (recuerda, los códigos de bloque son ignorados):
145
145
146
146
```js run
147
147
functionsayHi() {
@@ -158,13 +158,13 @@ function sayHi() {
158
158
sayHi();
159
159
```
160
160
161
-
People also call such behavior "hoisting" (raising), because all `var`are "hoisted" (raised) to the top of the function.
161
+
Este comportamiento también se llama "hoisting" (elevamiento), porque todos los `var`son "hoisted" (elevados) hacia el tope de la función.
162
162
163
-
So in the example above, `if (false)`branch never executes, but that doesn't matter. The`var`inside it is processed in the beginning of the function, so at the moment of `(*)`the variable exists.
163
+
Entonces, en el ejemplo anterior, la rama `if (false)`nunca se ejecuta pero eso no tiene importancia. El`var`dentro es procesado al iniciar la función, entonces al momento de `(*)`la variable existe.
164
164
165
-
**Declarations are hoisted, but assignments are not.**
165
+
**Las declaraciones son "hoisted" (elevadas), pero las asignaciones no lo son.**
166
166
167
-
That's best demonstrated with an example:
167
+
Es mejor demostrarlo con un ejemplo:
168
168
169
169
```js run
170
170
functionsayHi() {
@@ -178,40 +178,40 @@ function sayHi() {
178
178
sayHi();
179
179
```
180
180
181
-
The line`var phrase = "Hello"`has two actions in it:
181
+
La línea`var phrase = "Hello"`tiene dentro dos acciones:
182
182
183
-
1.Variable declaration`var`
184
-
2.Variable assignment`=`.
183
+
1.La declaración`var`
184
+
2.La asignación`=`.
185
185
186
-
The declaration is processed at the start of function execution ("hoisted"), but the assignment always works at the place where it appears. So the code works essentially like this:
186
+
La declaración es procesada al inicio de la ejecución de la función ("hoisted"), pero la asignación siempre se hace en el lugar donde aparece. Entonces lo que en esencia hace el código es:
187
187
188
188
```js run
189
189
functionsayHi() {
190
190
*!*
191
-
var phrase; //declaration works at the start...
191
+
var phrase; //la declaración se hace en el inicio...
192
192
*/!*
193
193
194
194
alert(phrase); // undefined
195
195
196
196
*!*
197
-
phrase ="Hello"; // ...assignment - when the execution reaches it.
197
+
phrase ="Hello"; // ...asignación - cuando la ejecución la alcanza.
198
198
*/!*
199
199
}
200
200
201
201
sayHi();
202
202
```
203
203
204
-
Because all `var`declarations are processed at the function start, we can reference them at any place. But variables are undefined until the assignments.
204
+
Como todas las declaraciones `var`son procesadas al inicio de la función, podemos referenciarlas en cualquier lugar. Pero las variables serán indefinidas hasta que alcancen su asignación.
205
205
206
-
In both examples above `alert`runs without an error, because the variable `phrase`exists. But its value is not yet assigned, so it shows`undefined`.
206
+
En ambos ejemplos de arriba `alert`se ejecuta sin un error, porque la variable `phrase`existe. Pero su valor no fue asignado aún, entonces muestra`undefined`.
207
207
208
208
### IIFE
209
209
210
-
As in the past there was only `var`, and it has no block-level visibility, programmers invented a way to emulate it. What they did was called "immediately-invoked function expressions" (abbreviated as IIFE).
210
+
Como en el pasado solo existía `var`, y no había visibilidad a nivel de bloque, los programadores inventaron una manera de emularla. Lo que hicieron fue el llamado "expresiones de función inmediatamente invocadas (abreviado IIFE en inglés).
211
211
212
-
That's not something we should use nowadays, but you can find them in old scripts.
212
+
No es algo que debiéramos usar estos días, pero puedes encontrarlas en código antiguo.
213
213
214
-
An IIFE looks like this:
214
+
Un IIFE se ve así:
215
215
216
216
```js run
217
217
(function() {
@@ -223,13 +223,13 @@ An IIFE looks like this:
223
223
})();
224
224
```
225
225
226
-
Here a Function Expression is created and immediately called. So the code executes right away and has its own private variables.
226
+
Aquí la expresión de función es creada e inmediatamente llamada. Entonces el código se ejecuta enseguida y con sus variables privadas propias.
227
227
228
-
The Function Expression is wrapped with parenthesis `(function {...})`, because when JavaScript meets `"function"`in the main code flow, it understands it as the start of a Function Declaration. But a Function Declaration must have a name, so this kind of code will give an error:
228
+
La expresión de función es encerrada entre paréntesis `(function {...})`, porque cuando JavaScript se encuentra con `"function"`en el flujo de código principal lo entiende como el principio de una declaración de función. Pero una declaración de función debe tener un nombre, entonces ese código daría error:
229
229
230
230
```js run
231
-
//Try to declare and immediately call a function
232
-
function() { // <-- Error: Function statements require a function name
231
+
//Trata de declarar e inmediatamente llamar una función
232
+
function() { // <-- Error: la instrucción de función requiere un nombre de función
233
233
234
234
let message ="Hello";
235
235
@@ -238,48 +238,48 @@ function() { // <-- Error: Function statements require a function name
238
238
}();
239
239
```
240
240
241
-
Even if we say: "okay, let's add a name", that won't work, as JavaScript does not allow Function Declarations to be called immediately:
241
+
Incluso si decimos: "okay, agreguémosle un nombre", no funcionaría, porque JavaScript no permite que las declaraciones de función sean llamadas inmediatamente:
242
242
243
243
```js run
244
-
//syntax error because of parentheses below
244
+
// error de sintaxis por causa de los paréntesis debajo
245
245
functiongo() {
246
246
247
-
}(); // <-- can't call Function Declaration immediately
247
+
}(); // <-- no puede llamarse una declaración de función inmediatamente
248
248
```
249
249
250
-
So, the parentheses around the function is a trick to show JavaScript that the function is created in the context of another expression, and hence it's a Function Expression: it needs no name and can be called immediately.
250
+
Entonces, los paréntesis alrededor de la función es un truco para mostrarle a JavaScript que la función es creada en el contexto de otra expresión, y de allí lo de "expresión de función", que no necesita un nombre y puede ser llamada inmediatamente.
251
251
252
-
There exist other ways besides parentheses to tell JavaScript that we mean a Function Expression:
252
+
Existen otras maneras además de los paréntesis para decirle a JavaScript que queremos una expresión de función:
253
253
254
254
```js run
255
-
//Ways to create IIFE
255
+
//Formas de crear IIFE
256
256
257
257
(function() {
258
-
alert("Parentheses around the function");
258
+
alert("Paréntesis alrededor de la función");
259
259
}*!*)*/!*();
260
260
261
261
(function() {
262
-
alert("Parentheses around the whole thing");
262
+
alert("Paréntesis alrededor de todo");
263
263
}()*!*)*/!*;
264
264
265
265
*!*!*/!*function() {
266
-
alert("Bitwise NOT operator starts the expression");
266
+
alert("Operador 'Bitwise NOT' como comienzo de la expresión");
267
267
}();
268
268
269
269
*!*+*/!*function() {
270
-
alert("Unary plus starts the expression");
270
+
alert("'más unario' como comienzo de la expresión");
271
271
}();
272
272
```
273
273
274
-
In all the above cases we declare a Function Expression and run it immediately. Let's note again: nowadays there's no reason to write such code.
274
+
En todos los casos de arriba declaramos una expresión de función y la ejecutamos inmediatamente. Tomemos nota de nuevo: Ahora no hay motivo para escribir semejante código.
275
275
276
-
## Summary
276
+
## Resumen
277
277
278
-
There are two main differences of `var`compared to`let/const`:
278
+
Hay dos diferencias principales entre `var`y`let/const`:
279
279
280
-
1.`var`variables have no block scope, they are visible minimum at the function level.
281
-
2.`var`declarations are processed at function start (script start for globals).
280
+
1.Las variables `var`no tienen alcance de bloque, su mínimo de alcance es a nivel de función.
281
+
2.Las declaraciones `var`son procesadas al inicio de la función (o del script para las globales) .
282
282
283
-
There's one more very minor difference related to the global object, that we'll cover in the next chapter.
283
+
Hay otra diferencia menor relacionada al objeto global que cubriremos en el siguiente capítulo.
284
284
285
-
These differences make `var`worse than`let` most of the time. Block-level variables is such a great thing. That's why `let`was introduced in the standard long ago, and is now a major way (along with`const`) to declare a variable.
285
+
Estas diferencias casi siempre hacen a `var`peor que`let`. Las variables a nivel de bloque son mejores. Es por ello que `let`fue presentado en el estándar mucho tiempo atrás, y es ahora la forma principal (junto con`const`) de declarar una variable.
0 commit comments