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
One of the fundamental differences of objects vs primitives is that they are stored and copied "by reference".
3
+
Una de las diferencias fundamentales de los objetos respecto a los primitivos es que son almacenados y copiados "por referencia".
4
4
5
-
Primitive values: strings, numbers, booleans -- are assigned/copied "as a whole value".
5
+
Los valores primitivos: strings, numbers, booleans -- son asignados y copiados "como un valor completo".
6
6
7
-
For instance:
7
+
Por ejemplo:
8
8
9
9
```js
10
10
let message ="Hello!";
11
11
let phrase = message;
12
12
```
13
13
14
-
As a result we have two independent variables, each one is storing the string`"Hello!"`.
14
+
Como resultado tenemos dos variables independientes, cada una almacenando la cadena`"Hello!"`.
15
15
16
16

17
17
18
-
Objects are not like that.
18
+
Los objetos no son así.
19
19
20
-
**A variable stores not the object itself, but its "address in memory", in other words "a reference" to it.**
20
+
**Una variable no almacena el objeto mismo sino su "dirección en memoria", en otras palabras "una referencia" a él.**
21
21
22
-
Here's the picture for the object:
22
+
Aquí tenemos una imagen del objeto:
23
23
24
24
```js
25
25
let user = {
@@ -29,76 +29,76 @@ let user = {
29
29
30
30

31
31
32
-
Here, the object is stored somewhere in memory. And the variable `user`has a "reference" to it.
32
+
Aquí, el objeto es almacenado en algún lugar de la memoria. Y la variable `user`tiene una "referencia" a él.
33
33
34
-
**When an object variable is copied -- the reference is copied, the object is not duplicated.**
34
+
**Cuando una variable de objeto es copiada -- la referencia es copiada, el objeto no es duplicado.**
35
35
36
-
For instance:
36
+
Por ejemplo:
37
37
38
38
```js no-beautify
39
39
let user = { name:"John" };
40
40
41
-
let admin = user; //copy the reference
41
+
let admin = user; //copia la referencia
42
42
```
43
43
44
-
Now we have two variables, each one with the reference to the same object:
44
+
Ahora tenemos dos variables, cada una con una referencia al mismo objeto:
45
45
46
46

47
47
48
-
We can use any variable to access the object and modify its contents:
48
+
Podemos usar cualquiera de las variables para acceder al objeto y modificar su contenido:
49
49
50
50
```js run
51
51
let user = { name:'John' };
52
52
53
53
let admin = user;
54
54
55
55
*!*
56
-
admin.name='Pete'; //changed by the "admin" reference
56
+
admin.name='Pete'; //cambiado por la referencia "admin"
57
57
*/!*
58
58
59
-
alert(*!*user.name*/!*); //'Pete', changes are seen from the "user" reference
59
+
alert(*!*user.name*/!*); //'Pete', los cambios se ven desde la referencia "user"
60
60
```
61
61
62
-
The example above demonstrates that there is only one object. As if we had a cabinet with two keys and used one of them (`admin`) to get into it. Then, if we later use another key (`user`) we can see changes.
62
+
El ejemplo anterior demuestra que solamente hay un único objeto. Como si tuviéramos un gabinete con dos llaves y usáramos una de ellas (`admin`) para accederlo. Si más tarde usamos la llave (`user`), podemos ver los cambios.
63
63
64
-
## Comparison by reference
64
+
## Comparación por referencia
65
65
66
-
The equality `==`and strict equality`===`operators for objects work exactly the same.
66
+
En los objetos, los operadores de igualdad `==`e igualdad estricta`===`funcionan exactamente igual.
67
67
68
-
**Two objects are equal only if they are the same object.**
68
+
**Dos objetos son iguales solamente si ellos son el mismo objeto.**
69
69
70
-
Here two variables reference the same object, thus they are equal:
70
+
Aquí dos variables referencian el mismo objeto, así que ellos son iguales:
71
71
72
72
```js run
73
73
let a = {};
74
-
let b = a; //copy the reference
74
+
let b = a; //copia la referencia
75
75
76
-
alert( a == b ); // true, both variables reference the same object
76
+
alert( a == b ); // true, verdadero. Ambas variables hacen referencia al mismo objeto
77
77
alert( a === b ); // true
78
78
```
79
79
80
-
And here two independent objects are not equal, even though both are empty:
80
+
Y aquí dos objetos independientes no son iguales, incluso estando ambos vacíos:
81
81
82
82
```js run
83
83
let a = {};
84
-
let b = {}; //two independent objects
84
+
let b = {}; //dos objetos independientes
85
85
86
86
alert( a == b ); // false
87
87
```
88
88
89
-
For comparisons like`obj1 > obj2` or for a comparison against a primitive `obj ==5`, objects are converted to primitives. We'll study how object conversions work very soon, but to tell the truth, such comparisons occur very rarely, usually as a result of a coding mistake.
89
+
Para comparaciones como`obj1 > obj2`, o comparaciones contra un primitivo `obj ==5`, los objetos son convertidos a primitivos. Estudiaremos cómo funciona la conversión de objetos pronto, pero a decir verdad tales comparaciones ocurren raramente y suelen ser errores de código.
90
90
91
-
## Cloning and merging, Object.assign
91
+
## Clonación y mezcla, Object.assign
92
92
93
-
So, copying an object variable creates one more reference to the same object.
93
+
Entonces copiar una variable de objeto crea una referencia adicional al mismo objeto.
94
94
95
-
But what if we need to duplicate an object? Create an independent copy, a clone?
95
+
Pero ¿si necesitamos duplicar un objeto? ¿Crear una copia independiente, un clon?
96
96
97
-
That's also doable, but a little bit more difficult, because there's no built-in method for that in JavaScript. Actually, that's rarely needed. Copying by reference is good most of the time.
97
+
Eso también es factible, pero un poco más difícil porque no hay un método incorporado para eso en JavaScript. En realidad, eso es raramente necesario. Copiar por referencia está bien la mayoría de las veces.
98
98
99
-
But if we really want that, then we need to create a new object and replicate the structure of the existing one by iterating over its properties and copying them on the primitive level.
99
+
Pero si realmente queremos eso, necesitamos crear un nuevo objeto y replicar la estructura del existente iterando a través de sus propiedades y copiándolas en el nivel primitivo.
100
100
101
-
Like this:
101
+
Como esto:
102
102
103
103
```js run
104
104
let user = {
@@ -107,59 +107,59 @@ let user = {
107
107
};
108
108
109
109
*!*
110
-
let clone = {}; //the new empty object
110
+
let clone = {}; //el nuevo objeto vacío
111
111
112
-
//let's copy all user properties into it
112
+
//copiemos todas las propiedades de user en él
113
113
for (let key in user) {
114
114
clone[key] = user[key];
115
115
}
116
116
*/!*
117
117
118
-
//now clone is a fully independent object with the same content
119
-
clone.name="Pete"; //changed the data in it
118
+
//ahora clone es un objeto totalmente independiente con el mismo contenido
119
+
clone.name="Pete"; //cambiamos datos en él
120
120
121
-
alert( user.name ); //still John in the original object
121
+
alert( user.name ); // John aún está en el objeto original
122
122
```
123
123
124
-
Also we can use the method [Object.assign](mdn:js/Object/assign) for that.
124
+
También podemos usar el método [Object.assign](mdn:js/Object/assign) para ello.
125
125
126
-
The syntax is:
126
+
La sintaxis es:
127
127
128
128
```js
129
129
Object.assign(dest, [src1, src2, src3...])
130
130
```
131
131
132
-
- The first argument`dest`is a target object.
133
-
- Further arguments `src1, ..., srcN` (can be as many as needed) are source objects.
134
-
- It copies the properties of all source objects `src1, ..., srcN`into the target`dest`. In other words, properties of all arguments starting from the second are copied into the first object.
135
-
- The call returns`dest`.
132
+
- El primer argumento`dest`es el objeto destinatario.
133
+
- Los siguientes argumentos `src1, ..., srcN` (tantos como sea necesario) son objetos fuentes.
134
+
- Esto copia todas las propiedades de todos los objetos fuentes `src1, ..., srcN`dentro del destino`dest`. En otras palabras, las propiedades de todos los argumentos, comenzando desde el segundo, son copiadas en el primer objeto.
135
+
- El llamado devuelve`dest`.
136
136
137
-
For instance, we can use it to merge several objects into one:
137
+
Por ejemplo, podemos usarlo para combinar distintos objetos en uno:
138
138
```js
139
139
let user = { name:"John" };
140
140
141
141
let permissions1 = { canView:true };
142
142
let permissions2 = { canEdit:true };
143
143
144
144
*!*
145
-
//copies all properties from permissions1 and permissions2 into user
145
+
//copia todas las propiedades desde permissions1 y permissions2 en user
If the copied property name already exists, it gets overwritten:
152
+
Si la propiedad por copiar ya existe, se sobrescribe:
153
153
154
154
```js run
155
155
let user = { name:"John" };
156
156
157
157
Object.assign(user, { name:"Pete" });
158
158
159
-
alert(user.name); //now user = { name: "Pete" }
159
+
alert(user.name); //ahora user = { name: "Pete" }
160
160
```
161
161
162
-
We also can use `Object.assign`to replace `for..in`loop for simple cloning:
162
+
También podemos usar `Object.assign`reemplazando el bucle `for..in`para hacer una clonación simple:
163
163
164
164
```js
165
165
let user = {
@@ -172,13 +172,13 @@ let clone = Object.assign({}, user);
172
172
*/!*
173
173
```
174
174
175
-
It copies all properties of`user`into the empty object and returns it.
175
+
Copia todas las propiedades de`user`en un objeto vacío y lo devuelve.
176
176
177
-
## Nested cloning
177
+
## Clonación anidada
178
178
179
-
Until now we assumed that all properties of`user`are primitive. But properties can be references to other objects. What to do with them?
179
+
Hasta ahora asumimos que todas las propiedades de`user`son primitivas. Pero las propiedades pueden ser referencias a otros objetos. ¿Qué hacer con ellas?
180
180
181
-
Like this:
181
+
Como esto:
182
182
```js run
183
183
let user = {
184
184
name:"John",
@@ -191,9 +191,9 @@ let user = {
191
191
alert( user.sizes.height ); // 182
192
192
```
193
193
194
-
Now it's not enough to copy `clone.sizes=user.sizes`, because the `user.sizes`is an object, it will be copied by reference. So`clone`and`user`will share the same sizes:
194
+
Ahora no es suficiente copiar `clone.sizes=user.sizes`, porque `user.sizes`es un objeto y será copiado por referencia. Entonces`clone`y`user`compartirán las mismas tallas (.sizes):
195
195
196
-
Like this:
196
+
Como esto:
197
197
198
198
```js run
199
199
let user = {
@@ -206,23 +206,23 @@ let user = {
206
206
207
207
let clone =Object.assign({}, user);
208
208
209
-
alert( user.sizes===clone.sizes ); // true, same object
209
+
alert( user.sizes===clone.sizes ); // true, el mimo objeto
210
210
211
-
// user and clone share sizes
212
-
user.sizes.width++; //change a property from one place
213
-
alert(clone.sizes.width); // 51, see the result from the other one
211
+
// user y clone comparten sizes
212
+
user.sizes.width++; //cambia la propiedad en un lugar
213
+
alert(clone.sizes.width); // 51, ve el resultado desde el otro
214
214
```
215
215
216
-
To fix that, we should use the cloning loop that examines each value of`user[key]`and, if it's an object, then replicate its structure as well. That is called a "deep cloning".
216
+
Para corregir esto, debemos usar un bucle de clonación que examine cada valor de`user[key]`y, si es un objeto, replicar su estructura también. Esto es llamado "clonación profunda".
217
217
218
-
There's a standard algorithm for deep cloning that handles the case above and more complex cases, called the [Structured cloning algorithm](https://html.spec.whatwg.org/multipage/structured-data.html#safe-passing-of-structured-data).
218
+
Hay un algoritmo estándar para clonación profunda que maneja este caso y otros más complicados llamado [Structured cloning algorithm](https://html.spec.whatwg.org/multipage/structured-data.html#safe-passing-of-structured-data).
219
219
220
-
We can use recursion to implement it. Or, not to reinvent the wheel, take an existing implementation, for instance [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep) from the JavaScript library [lodash](https://lodash.com).
220
+
Podemos usar recursividad para implementarlo. O, para no inventar la rueda, tomar una implementación existente, por ejemplo [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep) de la librería JavaScript [lodash](https://lodash.com).
221
221
222
-
## Summary
222
+
## Resumen
223
223
224
-
Objects are assigned and copied by reference. In other words, a variable stores not the "object value", but a "reference" (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object.
224
+
Los objetos son asignados y copiados por referencia. En otras palabras, una variable almacena no el valor del objeto sino una referencia (dirección de memoria) del valor. Entoncess copiar tal variable o pasarla como argumento de función copia la referencia, no el objeto.
225
225
226
-
All operations via copied references (like adding/removing properties) are performed on the same single object.
226
+
Todas la operaciones a través de referencias copiadas (como agregar y borrar propiedades) son efectuadas en el mismo y único objeto .
227
227
228
-
To make a "real copy" (a clone) we can use `Object.assign` for the so-called "shallow copy" (nested objects are copied by reference) or a "deep cloning" function, such as [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep).
228
+
Si queremos conseguir una "copia real" (un clon), podemos usar: Una "clonación superficial" por medio de la función `Object.assign` (con los objetos anidados copiados por referencia), o una "clonación profunda" con una función como [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep).
Copy file name to clipboardExpand all lines: 1-js/06-advanced-functions/04-var/article.md
+28-17Lines changed: 28 additions & 17 deletions
Original file line number
Diff line number
Diff line change
@@ -13,27 +13,18 @@ In the very first chapter about [variables](info:variables), we mentioned three
13
13
2.`const`
14
14
3.`var`
15
15
16
-
`let` and `const` behave exactly the same way in terms of Lexical Environments.
17
-
18
-
But `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.
19
-
20
-
If you don't plan on meeting such scripts you may even skip this chapter or postpone it, but then there's a chance that it bites you later.
21
-
22
-
From the first sight, `var` behaves similar to `let`. That is, declares a variable:
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:
23
17
24
18
```js run
25
-
functionsayHi() {
26
-
var phrase ="Hello"; // local variable, "var" instead of "let"
27
-
28
-
alert(phrase); // Hello
29
-
}
19
+
var message ="Hi";
20
+
alert(message); // Hi
21
+
```
30
22
31
-
sayHi();
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.
32
24
33
-
alert(phrase); // Error, phrase is not defined
34
-
```
25
+
If you don't plan on meeting such scripts you may even skip this chapter or postpone it.
35
26
36
-
...But here are the differences.
27
+
On the other hand, it's important to understand differences when migrating old scripts from `var` to `let`, to avoid odd errors.
37
28
38
29
## "var" has no block scope
39
30
@@ -94,7 +85,27 @@ alert(phrase); // Error: phrase is not defined (Check the Developer Console)
94
85
95
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.
96
87
97
-
## "var" declarations are processed at the function start
88
+
## "var" tolerates redeclarations
89
+
90
+
If we declare the same variable with `let` twice in the same scope, that's an error:
91
+
92
+
```js run
93
+
let user;
94
+
let user; // SyntaxError: 'user' has already been declared
95
+
```
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:
98
+
99
+
```js run
100
+
var user ="Pete";
101
+
102
+
var user ="John"; // this "var" does nothing (already declared)
103
+
// ...it doesn't trigger an error
104
+
105
+
alert(user); // John
106
+
```
107
+
108
+
## "var" variables can be declared below their use
98
109
99
110
`var` declarations are processed when the function starts (or script starts for globals).
0 commit comments