Skip to content

Commit 682f7d5

Browse files
Merge pull request #178 from vplentinax/variable-scope
Variable scope
2 parents aec3d5c + 84ff7f2 commit 682f7d5

File tree

20 files changed

+264
-250
lines changed

20 files changed

+264
-250
lines changed

1-js/06-advanced-functions/03-closure/1-closure-latest-changes/solution.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
The answer is: **Pete**.
1+
La respuesta es: **Pete**.
22

3-
A function gets outer variables as they are now, it uses the most recent values.
3+
Una función obtiene variables externas con su estado actual, y utiliza los valores más recientes.
4+
5+
Los valores de variables anteriores no se guardan en ningún lado. Cuando una función quiere una variable, toma el valor actual de su propio entorno léxico o el externo.
46

5-
Old variable values are not saved anywhere. When a function wants a variable, it takes the current value from its own Lexical Environment or the outer one.

1-js/06-advanced-functions/03-closure/1-closure-latest-changes/task.md

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ importance: 5
22

33
---
44

5-
# Does a function pickup latest changes?
5+
# ¿Una función recoge los últimos cambios?
66

7-
The function sayHi uses an external variable name. When the function runs, which value is it going to use?
7+
La función sayHi usa un nombre de variable externo. Cuando se ejecuta la función, ¿qué valor va a utilizar?
88

99
```js
1010
let name = "John";
@@ -15,9 +15,10 @@ function sayHi() {
1515

1616
name = "Pete";
1717

18-
sayHi(); // what will it show: "John" or "Pete"?
18+
sayHi(); // ¿qué mostrará: "John" o "Pete"?
19+
1920
```
21+
Tales situaciones son comunes tanto en el desarrollo del navegador como del lado del servidor. Se puede programar que una función se ejecute más tarde de lo que se creó, por ejemplo, después de una acción del usuario o una solicitud de red.
2022

21-
Such situations are common both in browser and server-side development. A function may be scheduled to execute later than it is created, for instance after a user action or a network request.
23+
Entonces, la pregunta es: ¿recoge los últimos cambios?
2224

23-
So, the question is: does it pick up the latest changes?

1-js/06-advanced-functions/03-closure/10-make-army/solution.md

Lines changed: 25 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11

2-
Let's examine what's done inside `makeArmy`, and the solution will become obvious.
2+
Examinemos lo que se hace dentro de `makeArmy`, y la solución será obvia.
33

4-
1. It creates an empty array `shooters`:
4+
1. Crea un array vacío. `shooters`:
55

66
```js
77
let shooters = [];
88
```
9-
2. Fills it in the loop via `shooters.push(function...)`.
109

11-
Every element is a function, so the resulting array looks like this:
10+
2. Lo llena en el bucle a través de `shooters.push(function...)`.
11+
12+
Cada elemento es una función, por lo que el array resultante se ve así:
1213

1314
```js no-beautify
1415
shooters = [
@@ -24,38 +25,38 @@ Let's examine what's done inside `makeArmy`, and the solution will become obviou
2425
function () { alert(i); }
2526
];
2627
```
28+
29+
3. El array se devuelve desde la función.
2730

28-
3. The array is returned from the function.
29-
30-
Then, later, the call to `army[5]()` will get the element `army[5]` from the array (it will be a function) and call it.
31+
Luego, más tarde, la llamada a `army[5] ()` obtendrá el elemento `army[5]` de el array (será una función) y lo llamará.
3132

32-
Now why all such functions show the same?
33+
Ahora, ¿por qué todas esas funciones muestran lo mismo?
3334

34-
That's because there's no local variable `i` inside `shooter` functions. When such a function is called, it takes `i` from its outer lexical environment.
35+
Esto se debe a que no hay una variable local `i` dentro de las funciones `shooter`. Cuando se llama a tal función, toma `i` de su entorno léxico externo.
3536

36-
What will be the value of `i`?
37+
¿Cuál será el valor de 'i'?
3738

38-
If we look at the source:
39+
Si miramos la fuente:
3940

4041
```js
4142
function makeArmy() {
4243
...
4344
let i = 0;
4445
while (i < 10) {
4546
let shooter = function() { // shooter function
46-
alert( i ); // should show its number
47+
alert( i ); // debería mostrar su número
4748
};
4849
...
4950
}
5051
...
5152
}
5253
```
5354

54-
...We can see that it lives in the lexical environment associated with the current `makeArmy()` run. But when `army[5]()` is called, `makeArmy` has already finished its job, and `i` has the last value: `10` (the end of `while`).
55+
... Podemos ver que vive en el entorno léxico asociado con la ejecución actual de `makeArmy()`. Pero cuando se llama a `army[5]()`, `makeArmy` ya ha terminado su trabajo, y `i` tiene el último valor: `10` (el final de `while`).
5556

56-
As a result, all `shooter` functions get from the outer lexical envrironment the same, last value `i=10`.
57+
Como resultado, todas las funciones `shooter` obtienen del mismo entorno léxico externo, el último valor `i = 10`.
5758

58-
We can fix it by moving the variable definition into the loop:
59+
Podemos arreglarlo moviendo la definición de variable al bucle:
5960

6061
```js run demo
6162
function makeArmy() {
@@ -66,7 +67,7 @@ function makeArmy() {
6667
for(let i = 0; i < 10; i++) {
6768
*/!*
6869
let shooter = function() { // shooter function
69-
alert( i ); // should show its number
70+
alert( i ); // debería mostrar su número
7071
};
7172
shooters.push(shooter);
7273
}
@@ -80,15 +81,15 @@ army[0](); // 0
8081
army[5](); // 5
8182
```
8283

83-
Now it works correctly, because every time the code block in `for (let i=0...) {...}` is executed, a new Lexical Environment is created for it, with the corresponding variable `i`.
84+
Ahora funciona correctamente, porque cada vez que se ejecuta el bloque de código en `for (let i = 0 ...) {...}`, se crea un nuevo entorno léxico para él, con la variable correspondiente `i`.
8485

85-
So, the value of `i` now lives a little bit closer. Not in `makeArmy()` Lexical Environment, but in the Lexical Environment that corresponds the current loop iteration. That's why now it works.
86+
Entonces, el valor de `i` ahora vive un poco más cerca. No en el entorno léxico `makeArmy()`, sino en el entorno léxico que corresponde a la iteración del bucle actual. Por eso ahora funciona.
8687

8788
![](lexenv-makearmy.svg)
8889

89-
Here we rewrote `while` into `for`.
90+
Aquí reescribimos `while` en `for`.
9091

91-
Another trick could be possible, let's see it for better understanding of the subject:
92+
Podría usarse otro truco, veámoslo para comprender mejor el tema:
9293

9394
```js run
9495
function makeArmy() {
@@ -100,7 +101,7 @@ function makeArmy() {
100101
let j = i;
101102
*/!*
102103
let shooter = function() { // shooter function
103-
alert( *!*j*/!* ); // should show its number
104+
alert( *!*j*/!* ); // debería verse el núemero
104105
};
105106
shooters.push(shooter);
106107
i++;
@@ -115,6 +116,7 @@ army[0](); // 0
115116
army[5](); // 5
116117
```
117118

118-
The `while` loop, just like `for`, makes a new Lexical Environment for each run. So here we make sure that it gets the right value for a `shooter`.
119+
El bucle `while`, al igual que `for`, crea un nuevo entorno léxico para cada ejecución. Así que aquí nos aseguramos de que obtenga el valor correcto para un `shooter`.
120+
121+
Copiamos `let j = i`. Esto hace que el cuerpo del bucle sea `j` local y copia el valor de `i` en él. Los primitivos se copian "por valor", por lo que en realidad obtenemos una copia independiente completa de `i`, que pertenece a la iteración del bucle actual.
119122

120-
We copy `let j = i`. This makes a loop body local `j` and copies the value of `i` to it. Primitives are copied "by value", so we actually get a complete independent copy of `i`, belonging to the current loop iteration.

1-js/06-advanced-functions/03-closure/10-make-army/task.md

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ importance: 5
22

33
---
44

5-
# Army of functions
5+
# Ejército de funciones
66

7-
The following code creates an array of `shooters`.
7+
El siguiente código crea una serie de `shooters`.
88

9-
Every function is meant to output its number. But something is wrong...
9+
Cada función está destinada a generar su número. Pero algo anda mal ...
1010

1111
```js run
1212
function makeArmy() {
@@ -15,7 +15,7 @@ function makeArmy() {
1515
let i = 0;
1616
while (i < 10) {
1717
let shooter = function() { // shooter function
18-
alert( i ); // should show its number
18+
alert( i ); // debería mostrar su número
1919
};
2020
shooters.push(shooter);
2121
i++;
@@ -26,10 +26,10 @@ function makeArmy() {
2626

2727
let army = makeArmy();
2828

29-
army[0](); // the shooter number 0 shows 10
30-
army[5](); // and number 5 also outputs 10...
31-
// ... all shooters show 10 instead of their 0, 1, 2, 3...
29+
army[0](); // el tirador número 0 muestra 10
30+
army[5](); //y el número 5 también produce 10...
31+
// ... todos los tiradores muestran 10 en lugar de sus 0, 1, 2, 3 ...
3232
```
3333

34-
Why do all of the shooters show the same value? Fix the code so that they work as intended.
34+
¿Por qué todos los tiradores muestran el mismo valor? Arregle el código para que funcionen según lo previsto.
3535

1-js/06-advanced-functions/03-closure/2-closure-variable-access/solution.md

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
The answer is: **Pete**.
21

3-
The `work()` function in the code below gets `name` from the place of its origin through the outer lexical environment reference:
2+
La respuesta es: **Pete**.
3+
4+
La función `work()` en el código a continuación obtiene `name` del lugar de su origen a través de la referencia del entorno léxico externo:
45

56
![](lexenv-nested-work.svg)
67

7-
So, the result is `"Pete"` here.
8+
Entonces, el resultado es "Pete".
9+
10+
Pero si no hubiera `let name` en` makeWorker () `, entonces la búsqueda saldría y tomaría la variable global como podemos ver en la cadena de arriba. En ese caso, el resultado sería `John`.
811

9-
But if there were no `let name` in `makeWorker()`, then the search would go outside and take the global variable as we can see from the chain above. In that case the result would be `"John"`.

1-js/06-advanced-functions/03-closure/2-closure-variable-access/task.md

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ importance: 5
22

33
---
44

5-
# Which variables are available?
5+
# ¿Qué variables están disponibles?
66

7-
The function `makeWorker` below makes another function and returns it. That new function can be called from somewhere else.
7+
La función `makeWorker` a continuación crea otra función y la devuelve. Esa nueva función se puede llamar desde otro lugar.
88

9-
Will it have access to the outer variables from its creation place, or the invocation place, or both?
9+
¿Tendrá acceso a las variables externas desde su lugar de creación, o desde el lugar de invocación, o ambos?
1010

1111
```js
1212
function makeWorker() {
@@ -19,11 +19,11 @@ function makeWorker() {
1919

2020
let name = "John";
2121

22-
// create a function
22+
// crea una función
2323
let work = makeWorker();
2424

25-
// call it
26-
work(); // what will it show?
25+
// la llama
26+
work(); // ¿qué mostrará?
2727
```
2828

29-
Which value it will show? "Pete" or "John"?
29+
¿Qué valor mostrará? "Pete" o "John"?

1-js/06-advanced-functions/03-closure/3-counter-independent/solution.md

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1-
The answer: **0,1.**
21

3-
Functions `counter` and `counter2` are created by different invocations of `makeCounter`.
2+
La respuesta: **0,1.**
3+
4+
Las funciones `counter` y` counter2` son creadas por diferentes invocaciones de `makeCounter`.
5+
6+
Por lo tanto, tienen entornos léxicos externos independientes, cada uno tiene su propio `count`.
47

5-
So they have independent outer Lexical Environments, each one has its own `count`.

1-js/06-advanced-functions/03-closure/3-counter-independent/task.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@ importance: 5
22

33
---
44

5-
# Are counters independent?
5+
# ¿Son independientes los contadores?
66

7-
Here we make two counters: `counter` and `counter2` using the same `makeCounter` function.
7+
Aquí hacemos dos contadores: `counter` y `counter2` usando la misma función `makeCounter`.
8+
9+
¿Son independientes? ¿Qué va a mostrar el segundo contador? `0,1` o `2,3` o algo más?
810

9-
Are they independent? What is the second counter going to show? `0,1` or `2,3` or something else?
1011

1112
```js
1213
function makeCounter() {

1-js/06-advanced-functions/03-closure/4-counter-object-independent/solution.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11

2-
Surely it will work just fine.
2+
Seguramente funcionará bien.
3+
4+
Ambas funciones anidadas se crean dentro del mismo entorno léxico externo, por lo que comparten acceso a la misma variable `count`:
35

4-
Both nested functions are created within the same outer Lexical Environment, so they share access to the same `count` variable:
56

67
```js run
78
function Counter() {
@@ -10,7 +11,6 @@ function Counter() {
1011
this.up = function() {
1112
return ++count;
1213
};
13-
1414
this.down = function() {
1515
return --count;
1616
};

1-js/06-advanced-functions/03-closure/4-counter-object-independent/task.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@ importance: 5
22

33
---
44

5-
# Counter object
5+
# Objeto contador
66

7-
Here a counter object is made with the help of the constructor function.
7+
Aquí se crea un objeto contador con la ayuda de la función constructora.
8+
9+
¿Funcionará? ¿Qué mostrará?
810

9-
Will it work? What will it show?
1011

1112
```js
1213
function Counter() {
@@ -26,4 +27,3 @@ alert( counter.up() ); // ?
2627
alert( counter.up() ); // ?
2728
alert( counter.down() ); // ?
2829
```
29-

0 commit comments

Comments
 (0)