-
Notifications
You must be signed in to change notification settings - Fork 227
Nullish coalescing operator '??' #196
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
EzequielCaste
merged 3 commits into
javascript-tutorial:master
from
ddanielcruzz:master
May 30, 2020
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
117 changes: 117 additions & 0 deletions
117
1-js/02-first-steps/12-nullish-coalescing-operator/article.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,117 @@ | ||
# Nullish coalescing operator '??' | ||
|
||
[recent browser="new"] | ||
|
||
El _nullish coalescing operator_ `??` brinda una sintáxis corta para seleccionar la primera variable "definida" de una lista. | ||
|
||
El resultado de `a ?? b` es: | ||
- `a` si esta no es `null` o `undefined`, | ||
- `b`, en el caso contrario. | ||
|
||
Entonces, `x = a ?? b` es la versión corta de: | ||
|
||
```js | ||
x = (a !== null && a !== undefined) ? a : b; | ||
``` | ||
|
||
Aquí un ejemplo más detallado. | ||
|
||
Pensemos que tenemos un `firstName`, `lastName` o `nickName`, todos ellos opcionales. | ||
|
||
Escojamos el que esté definido y mostrémoslo (o mostremos "Anonymous" si ninguno está definido): | ||
|
||
```js run | ||
let firstName = null; | ||
let lastName = null; | ||
let nickName = "Supercoder"; | ||
|
||
// Muestra la primera variable que no sea null/undefined | ||
alert(firstName ?? lastName ?? nickName ?? "Anonymous"); // Supercoder | ||
``` | ||
|
||
## Comparación con || | ||
|
||
Esto es muy similiar al operador OR `||`. De hecho, podemos reemplazar `??` con `||` en el código anterior y obtener el mismo resultado. | ||
|
||
La gran diferencia es que: | ||
- `||` retorna el primer valor _*truthy*_. | ||
- `??` retorna el primer valor _*defined*_. | ||
|
||
Esto es de suma importancia cuando queremos tratar `null/undefined` diferente de `0`. | ||
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Por ejemplo: | ||
|
||
```js | ||
height = height ?? 100; | ||
``` | ||
|
||
Esto le asigna `100` a `height` si esta no está definida. En cambio si `height` es `0`, esta se mantiene "tal cual". | ||
|
||
Comparémoslo con `||`: | ||
|
||
```js run | ||
let height = 0; | ||
|
||
alert(height || 100); // 100 | ||
alert(height ?? 100); // 0 | ||
``` | ||
|
||
En este caso, `height || 100` maneja `height` con un valor de `0` como no asignada, al igual que con `null`, `undefined` o cualquier otro valor _falsy_, dependiendo de la situación, esto puede ser incorrecto. | ||
|
||
En el caso de `height ?? 100` este retorna `100` solo si `height` es exactamente `null` o `undefined`. | ||
|
||
## Precedencia | ||
|
||
La precedencia del operador `??` es bastante baja: `7` en la [Tabla MDN](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Operadores/Operator_Precedence#Table). | ||
|
||
Es más baja que en la mayoría de los operadores y un poco más alta que `=` y `?`. | ||
|
||
Así que si necesitas usar `??` en una expresión compleja, considera añadir paréntesis: | ||
|
||
```js run | ||
let height = null; | ||
let width = null; | ||
|
||
// Importante: usar paréntesis | ||
let area = (height ?? 100) * (width ?? 50); | ||
|
||
alert(area); // 5000 | ||
``` | ||
|
||
Caso contrario, si omitimos los paréntesis, entonces `*` tiene una mayor precedencia y se ejecutará primero. Eso sería lo mismo que: | ||
|
||
```js | ||
// Incorrecto | ||
let area = height ?? (100 * width) ?? 50; | ||
``` | ||
|
||
Existe también una limitación a nivel del lenguaje. Por razones de seguridad, está prohibido usar `??` junto con los operadores `&&` y `||`. | ||
|
||
El siguiente código desencadena un error de sintáxis: | ||
|
||
```js run | ||
let x = 1 && 2 ?? 3; // Syntax error | ||
``` | ||
|
||
La limitación es sin duda alguna debatible, pero por ciertas razones fue agregada a la especificación del lenguaje. | ||
|
||
Usa paréntesis explícitos para solucionarlo: | ||
|
||
```js run | ||
let x = (1 && 2) ?? 3; // Funciona | ||
alert(x); // 2 | ||
``` | ||
|
||
## Resumen | ||
|
||
- El _nullish coalescing operator_ `??` proveé una manera concisa de seleccionar un valor "definido" de una lista. | ||
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Es usado para asignar valores por defecto a las variables: | ||
|
||
```js | ||
// Asignar height=100, si height es null o undefined | ||
height = height ?? 100; | ||
``` | ||
|
||
- El operador `??` tiene una precedencia muy baja, un poco más alta que `?` y `=`. | ||
- Está prohibido su uso con `||` y `&&` sin paréntesis explícitos. |
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes
File renamed without changes
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.