Skip to content

Commit d7bc432

Browse files
authored
Merge pull request #312 from joaquinelio/oldvar
The old "var"
2 parents b613f50 + 0645882 commit d7bc432

File tree

1 file changed

+74
-74
lines changed

1 file changed

+74
-74
lines changed
Lines changed: 74 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -1,117 +1,117 @@
11

2-
# The old "var"
2+
# La vieja "var"
33

4-
```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.
66
7-
That's not how we write a new code.
7+
Así no es como escribimos código moderno.
88
```
99

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

1212
1. `let`
1313
2. `const`
1414
3. `var`
1515

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

1818
```js run
19-
var message = "Hi";
20-
alert(message); // Hi
19+
var message = "Hola";
20+
alert(message); // Hola
2121
```
2222

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

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

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

29-
## "var" has no block scope
29+
## "var" no tiene alcance (visibilidad) de bloque.
3030

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

33-
For instance:
33+
Por ejemplo:
3434

3535
```js run
3636
if (true) {
37-
var test = true; // use "var" instead of "let"
37+
var test = true; // uso de "var" en lugar de "let"
3838
}
3939

4040
*!*
41-
alert(test); // true, the variable lives after if
41+
alert(test); // true, la variable vive después del if
4242
*/!*
4343
```
4444

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

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`:
4848

4949
```js run
5050
if (true) {
51-
let test = true; // use "let"
51+
let test = true; // uso de "let"
5252
}
5353

5454
*!*
55-
alert(test); // Error: test is not defined
55+
alert(test); // Error: test no está definido
5656
*/!*
5757
```
5858

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

6161
```js
6262
for (var i = 0; i < 10; i++) {
6363
// ...
6464
}
6565

6666
*!*
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
6868
*/!*
6969
```
7070

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

7373
```js run
7474
function sayHi() {
7575
if (true) {
7676
var phrase = "Hello";
7777
}
7878

79-
alert(phrase); // works
79+
alert(phrase); // funciona
8080
}
8181

8282
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)
8484
```
8585

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

88-
## "var" tolerates redeclarations
88+
## "var" tolera redeclaraciones
8989

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

9292
```js run
9393
let user;
94-
let user; // SyntaxError: 'user' has already been declared
94+
let user; // SyntaxError: 'user' ya fue declarado
9595
```
9696

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

9999
```js run
100100
var user = "Pete";
101101

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
104104

105105
alert(user); // John
106106
```
107107

108-
## "var" variables can be declared below their use
108+
## Las variables "var" pueden ser declaradas debajo del lugar en donde se usan
109109

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).
111111

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).
113113

114-
So this code:
114+
Entonces el código:
115115

116116
```js run
117117
function sayHi() {
@@ -126,7 +126,7 @@ function sayHi() {
126126
sayHi();
127127
```
128128

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):
130130

131131
```js run
132132
function sayHi() {
@@ -141,7 +141,7 @@ function sayHi() {
141141
sayHi();
142142
```
143143

144-
...Or even as this (remember, code blocks are ignored):
144+
...O incluso esto (recuerda, los códigos de bloque son ignorados):
145145

146146
```js run
147147
function sayHi() {
@@ -158,13 +158,13 @@ function sayHi() {
158158
sayHi();
159159
```
160160

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

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

165-
**Declarations are hoisted, but assignments are not.**
165+
**Las declaraciones son "hoisted" (elevadas), pero las asignaciones no lo son.**
166166

167-
That's best demonstrated with an example:
167+
Es mejor demostrarlo con un ejemplo:
168168

169169
```js run
170170
function sayHi() {
@@ -178,40 +178,40 @@ function sayHi() {
178178
sayHi();
179179
```
180180

181-
The line `var phrase = "Hello"` has two actions in it:
181+
La línea `var phrase = "Hello"` tiene dentro dos acciones:
182182

183-
1. Variable declaration `var`
184-
2. Variable assignment `=`.
183+
1. La declaración `var`
184+
2. La asignación `=`.
185185

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

188188
```js run
189189
function sayHi() {
190190
*!*
191-
var phrase; // declaration works at the start...
191+
var phrase; // la declaración se hace en el inicio...
192192
*/!*
193193

194194
alert(phrase); // undefined
195195

196196
*!*
197-
phrase = "Hello"; // ...assignment - when the execution reaches it.
197+
phrase = "Hello"; // ...asignación - cuando la ejecución la alcanza.
198198
*/!*
199199
}
200200

201201
sayHi();
202202
```
203203

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

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

208208
### IIFE
209209

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).
211211

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

214-
An IIFE looks like this:
214+
Un IIFE se ve así:
215215

216216
```js run
217217
(function() {
@@ -223,13 +223,13 @@ An IIFE looks like this:
223223
})();
224224
```
225225

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

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

230230
```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
233233

234234
let message = "Hello";
235235

@@ -238,48 +238,48 @@ function() { // <-- Error: Function statements require a function name
238238
}();
239239
```
240240

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

243243
```js run
244-
// syntax error because of parentheses below
244+
// error de sintaxis por causa de los paréntesis debajo
245245
function go() {
246246

247-
}(); // <-- can't call Function Declaration immediately
247+
}(); // <-- no puede llamarse una declaración de función inmediatamente
248248
```
249249

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

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

254254
```js run
255-
// Ways to create IIFE
255+
// Formas de crear IIFE
256256

257257
(function() {
258-
alert("Parentheses around the function");
258+
alert("Paréntesis alrededor de la función");
259259
}*!*)*/!*();
260260

261261
(function() {
262-
alert("Parentheses around the whole thing");
262+
alert("Paréntesis alrededor de todo");
263263
}()*!*)*/!*;
264264

265265
*!*!*/!*function() {
266-
alert("Bitwise NOT operator starts the expression");
266+
alert("Operador 'Bitwise NOT' como comienzo de la expresión");
267267
}();
268268

269269
*!*+*/!*function() {
270-
alert("Unary plus starts the expression");
270+
alert("'más unario' como comienzo de la expresión");
271271
}();
272272
```
273273

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

276-
## Summary
276+
## Resumen
277277

278-
There are two main differences of `var` compared to `let/const`:
278+
Hay dos diferencias principales entre `var` y `let/const`:
279279

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) .
282282

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

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

Comments
 (0)