Skip to content

Commit ab53d84

Browse files
Merge pull request #190 from vplentinax/chaining
Optional chaining '?.'
2 parents cdb44f1 + f1cb7da commit ab53d84

File tree

1 file changed

+57
-57
lines changed
  • 1-js/04-object-basics/07-optional-chaining

1 file changed

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

2-
# Optional chaining '?.'
2+
# Encadenamiento opcional '?.'
33

44
[recent browser="new"]
55

6-
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.
77

8-
## The problem
8+
## El problema
99

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

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

1414
```js run
15-
let user = {}; // the user happens to be without address
15+
let user = {}; // usuario sin dirección
1616

1717
alert(user.address.street); // Error!
1818
```
1919

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

2222
```js run
23-
// Error if the result of querySelector(...) is null
23+
// Error si el resultado de querySelector (...) es nulo
2424
let html = document.querySelector('.my-element').innerHTML;
2525
```
2626

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

29-
For example:
29+
Por ejemplo:
3030

3131
```js run
32-
let user = {}; // user has no address
32+
let user = {}; // El usuario no tiene dirección
3333

3434
alert( user && user.address && user.address.street ); // undefined (no error)
3535
```
3636

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

39-
## Optional chaining
39+
## Encadenamiento opcional
4040

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

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

4545

46-
Here's the safe way to access `user.address.street`:
46+
Aquí está la forma segura de acceder a `user.address.street`:
4747

4848
```js run
49-
let user = {}; // user has no address
49+
let user = {}; // El usuario no tiene dirección
5050

5151
alert( user?.address?.street ); // undefined (no error)
5252
```
5353
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:
5555
5656
```js run
5757
let user = null;
@@ -62,50 +62,50 @@ alert( user?.address.street ); // undefined
6262
alert( user?.address.street.anything ); // undefined
6363
```
6464
65-
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.
6666
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.
6868
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.
7171

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

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.
7575
```
7676
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:
7979
8080
```js run
81-
// ReferenceError: user is not defined
81+
// ReferenceError: El usuario no está definido
8282
user?.address;
8383
```
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.
8585
````
8686
87-
## Short-circuiting
87+
## Short-circuiting (Cortocircuitos)
8888
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.
9090
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:
9292
9393
```js run
9494
let user = null;
9595
let x = 0;
9696

97-
user?.sayHi(x++); // nothing happens
97+
user?.sayHi(x++); // no pasa nada
9898

99-
alert(x); // 0, value not incremented
99+
alert(x); // 0, el valor no se incrementa
100100
```
101101
102-
## Other cases: ?.(), ?.[]
102+
## Otros casos: ?.(), ?.[]
103103
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.
105105
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.
107107
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:
109109
110110
```js run
111111
let user1 = {
@@ -122,18 +122,18 @@ user2.admin?.();
122122
*/!*
123123
```
124124
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.
126126
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.
128128
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.
130130
131131
```js run
132132
let user1 = {
133133
firstName: "John"
134134
};
135135

136-
let user2 = null; // Imagine, we couldn't authorize the user
136+
let user2 = null; // Imagine, no podríamos autorizar al usuario
137137

138138
let key = "firstName";
139139

@@ -143,34 +143,34 @@ alert( user2?.[key] ); // undefined
143143
alert( user1?.[key]?.something?.not?.existing); // undefined
144144
```
145145
146-
Also we can use `?.` with `delete`:
146+
También podemos usar `?.` con `delete`:
147147
148148
```js run
149-
delete user?.name; // delete user.name if user exists
149+
delete user?.name; // Eliminar user.name si el usuario existe
150150
```
151151
152-
```warn header="We can use `?.` for safe reading and deleting, but not writing"
153-
The optional chaining `?.` has no use at the left side of an assignment:
152+
```warn header="Podemos usar `?.` para una lectura y eliminación segura, pero no para escribir"
153+
El encadenamiento opcional `?.` no tiene uso en el lado izquierdo de una tarea:
154154

155155
```js run
156-
// the idea of the code below is to write user.name, if user exists
156+
// la idea del siguiente código es escribir user.name, si el usuario existe
157157
158-
user?.name = "John"; // Error, doesn't work
159-
// because it evaluates to undefined = "John"
158+
user?.name = "John"; // Error, no funciona
159+
// porque se evalúa como undefined = "John"
160160
```
161161

162-
## Summary
162+
## Resumen
163163

164-
The `?.` syntax has three forms:
164+
La sintaxis `?.` tiene tres formas:
165165

166-
1. `obj?.prop` -- returns `obj.prop` if `obj` exists, otherwise `undefined`.
167-
2. `obj?.[prop]` -- returns `obj[prop]` if `obj` exists, otherwise `undefined`.
168-
3. `obj?.method()` -- calls `obj.method()` if `obj` exists, otherwise returns `undefined`.
166+
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`.
169169

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í.
171171

172-
A chain of `?.` allows to safely access nested properties.
172+
Una cadena de `?.` permite acceder de forma segura a las propiedades anidadas.
173173

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

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

Comments
 (0)