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
The optional chaining`?.`is an error-proof way to access nested object properties, even if an intermediate property doesn't exist.
6
+
El encadenamiento opcional`?.`es una forma a prueba de errores para acceder a las propiedades de los objetos anidados, incluso si no existe una propiedad intermedia.
7
7
8
-
## The problem
8
+
## El problema
9
9
10
-
If you've just started to read the tutorial and learn JavaScript, maybe the problem hasn't touched you yet, but it's quite common.
10
+
Si acaba de comenzar a leer el tutorial y aprender JavaScript, quizás el problema aún no lo haya tocado, pero es bastante común.
11
11
12
-
For example, some of our users have addresses, but few did not provide them. Then we can't safely read`user.address.street`:
12
+
Por ejemplo, algunos de nuestros usuarios tienen direcciones, pero pocos no las proporcionaron. Entonces no podemos leer con seguridad`user.address.street`:
13
13
14
14
```js run
15
-
let user = {}; //the user happens to be without address
15
+
let user = {}; //usuario sin dirección
16
16
17
17
alert(user.address.street); // Error!
18
18
```
19
19
20
-
Or, in the web development, we'd like to get an information about an element on the page, but it may not exist:
20
+
O, en el desarrollo web, nos gustaría obtener información sobre un elemento en la página, pero puede no existir:
21
21
22
22
```js run
23
-
// Error if the result of querySelector(...) is null
23
+
// Error si el resultado de querySelector(...) es nulo
24
24
let html =document.querySelector('.my-element').innerHTML;
25
25
```
26
26
27
-
Before `?.`appeared in the language, the `&&`operator was used to work around that.
27
+
Antes de que apareciera `?.`en el lenguaje, el operador `&&`se usaba para solucionarlo.
28
28
29
-
For example:
29
+
Por ejemplo:
30
30
31
31
```js run
32
-
let user = {}; //user has no address
32
+
let user = {}; //El usuario no tiene dirección
33
33
34
34
alert( user &&user.address&&user.address.street ); // undefined (no error)
35
35
```
36
36
37
-
AND'ing the whole path to the property ensures that all components exist, but is cumbersome to write.
37
+
Y el camino completo a la propiedad asegura que todos los componentes existen, pero es engorroso de escribir.
38
38
39
-
## Optional chaining
39
+
## Encadenamiento opcional
40
40
41
-
The optional chaining`?.`stops the evaluation and returns `undefined`if the part before `?.`is `undefined`or`null`.
41
+
El encadenamiento opcional`?.`detiene la evaluación y devuelve`undefined`si la parte anterior a `?.`es`undefined`o`null`.
42
42
43
-
Further in this article, for brevity, we'll be saying that something "exists" if it's not`null`and not`undefined`.
43
+
Más adelante en este artículo, por brevedad, diremos que algo "existe" si no es`null`ni`undefined`.
44
44
45
45
46
-
Here's the safe way to access`user.address.street`:
46
+
Aquí está la forma segura de acceder a`user.address.street`:
47
47
48
48
```js run
49
-
let user = {}; //user has no address
49
+
let user = {}; //El usuario no tiene dirección
50
50
51
51
alert( user?.address?.street ); // undefined (no error)
52
52
```
53
53
54
-
Reading the address with`user?.address` works even if `user`object doesn't exist:
54
+
Leer la dirección con`user? .Address` funciona incluso si el objeto `user`no existe:
Please note: the `?.`syntax works exactly where it's placed, not any further.
65
+
Tenga en cuenta: la sintaxis `?.`funciona exactamente donde está colocada, nada más.
66
66
67
-
In the last two lines the evaluation stops immediately after `user?.`, never accessing further properties. But if the `user`actually exists, then the further intermediate properties, such as `user.address` must exist.
67
+
En las últimas dos líneas, la evaluación se detiene inmediatamente después de `user?.`, sin acceder nunca a otras propiedades. Pero si `user`realmente existe, entonces las propiedades intermedias adicionales, como `user.address`deben existir.
68
68
69
-
```warn header="Don't overuse the optional chaining"
70
-
We should use `?.`only where it's ok that something doesn't exist.
69
+
```warn header="No abuses del encadenamiento opcional"
70
+
Deberíamos usar `?.`solo donde está bien que algo no exista.
71
71
72
-
For example, if according to our coding logic `user`object must be there, but`address`is optional, then`user.address?.street` would be better.
72
+
Por ejemplo, si de acuerdo con nuestra lógica de codificación, el objeto `user`debe estar allí, pero`address`es opcional, entonces`user.address?.Street` sería mejor.
73
73
74
-
So, if`user`happens to be undefined due to a mistake, we'll know about it and fix it. Otherwise, coding errors can be silenced where not appropriate, and become more difficult to debug.
74
+
Entonces, si`user`no está definido debido a un error, lo sabremos y lo arreglaremos. De lo contrario, los errores de codificación pueden silenciarse donde no sea apropiado y volverse más difíciles de depurar.
75
75
```
76
76
77
-
````warn header="The variable before `?.` must exist"
78
-
If there's no variable `user`, then`user?.anything` triggers an error:
77
+
````warn header="La variable antes de ?. debe existir"
78
+
Si no hay una variable `user`, entonces`user? .Anything` provocará un error:
79
79
80
80
```js run
81
-
// ReferenceError: user is not defined
81
+
// ReferenceError: El usuario no está definido
82
82
user?.address;
83
83
```
84
-
The optional chaining only tests for`null/undefined`, doesn't interfere with any other language mechanics.
84
+
El encadenamiento opcional solo prueba para`null/undefined`, no interfiere con ninguna otra mecánica del lenguaje.
85
85
````
86
86
87
-
## Short-circuiting
87
+
## Short-circuiting (Cortocircuitos)
88
88
89
-
As it was said before, the `?.` immediately stops ("short-circuits") the evaluation if the left part doesn't exist.
89
+
Como se dijo antes, el`?.`detiene inmediatamente ("cotocircuito") la evaluación si la parte izquierda no existe.
90
90
91
-
So, if there are any further function calls or side effects, they don't occur:
91
+
Entonces, si hay más llamadas a funciones o efectos secundarios, estos no suceden:
92
92
93
93
```js run
94
94
let user =null;
95
95
let x =0;
96
96
97
-
user?.sayHi(x++); //nothing happens
97
+
user?.sayHi(x++); //no pasa nada
98
98
99
-
alert(x); // 0, value not incremented
99
+
alert(x); // 0, el valor no se incrementa
100
100
```
101
101
102
-
## Other cases: ?.(), ?.[]
102
+
## Otros casos: ?.(), ?.[]
103
103
104
-
The optional chaining `?.` is not an operator, but a special syntax construct, that also works with functions and square brackets.
104
+
El encadenamiento opcional`?.`no es un operador, sino una construcción de sintaxis especial, que también funciona con funciones y corchetes.
105
105
106
-
For example, `?.()` is used to call a function that may not exist.
106
+
Por ejemplo, `?.()`Se usa para llamar a una función que puede no existir.
107
107
108
-
In the code below, some of our users have `admin` method, and some don't:
108
+
En el siguiente código, algunos de nuestros usuarios tienen el método `admin`, y otros no:
109
109
110
110
```js run
111
111
let user1 = {
@@ -122,18 +122,18 @@ user2.admin?.();
122
122
*/!*
123
123
```
124
124
125
-
Here, in both lines we first use the dot `.`to get `admin` property, because the user object must exist, so it's safe read from it.
125
+
Aquí, en ambas líneas, primero usamos el punto `.`para obtener la propiedad `admin`, porque el objeto usuario debe existir, por lo que es seguro leerlo.
126
126
127
-
Then`?.()`checks the left part: if the user exists, then it runs (for`user1`). Otherwise (for`user2`) the evaluation stops without errors.
127
+
Entonces`?.()`Comprueba la parte izquierda: si el usuario existe, entonces se ejecuta (para`user1`). De lo contrario (para`user2`) la evaluación se detiene sin errores.
128
128
129
-
The `?.[]`syntax also works, if we'd like to use brackets `[]`to access properties instead of dot `.`. Similar to previous cases, it allows to safely read a property from an object that may not exist.
129
+
La sintaxis `?.[]`también funciona si quisiéramos usar corchetes `[]`para acceder a las propiedades en lugar de punto `.`. Al igual que en casos anteriores, permite leer de forma segura una propiedad de un objeto que puede no existir.
130
130
131
131
```js run
132
132
let user1 = {
133
133
firstName:"John"
134
134
};
135
135
136
-
let user2 =null; // Imagine, we couldn't authorize the user
136
+
let user2 =null; // Imagine, no podríamos autorizar al usuario
1.`obj?.prop`--devuelve`obj.prop`si`obj`existe, si no,`undefined`.
167
+
2.`obj?.[prop]`--devuelve`obj[prop]`si`obj`existe, si no,`undefined`.
168
+
3.`obj?.method()`--llama a `obj.method()`si`obj`existe, si no devuelve`undefined`.
169
169
170
-
As we can see, all of them are straightforward and simple to use. The`?.`checks the left part for`null/undefined`and allows the evaluation to proceed if it's not so.
170
+
Como podemos ver, todos ellos son sencillos y fáciles de usar. El`?.`comprueba la parte izquierda para`null/undefined`y permite que la evaluación continúe si no es así.
171
171
172
-
A chain of `?.` allows to safely access nested properties.
172
+
Una cadena de`?.`permite acceder de forma segura a las propiedades anidadas.
173
173
174
-
Still, we should apply `?.` carefully, only where it's ok that the left part doesn't to exist.
174
+
Aún así, debemos aplicar `?.`con cuidado, solo donde está bien que la parte izquierda no exista.
175
175
176
-
So that it won't hide programming errors from us, if they occur.
176
+
Para que no nos oculte errores de programación, si ocurren.
0 commit comments