Skip to content

Commit 084f959

Browse files
authored
Merge pull request #195 from ermogenes/master
nullish-coalescing-operator finished
2 parents 433048b + 095b85f commit 084f959

File tree

2 files changed

+68
-68
lines changed

2 files changed

+68
-68
lines changed
Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +0,0 @@
1-
2-
[html src="index.html"]
Lines changed: 68 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -1,94 +1,96 @@
1-
# Nullish coalescing operator '??'
1+
# Operador de coalescência nula '??'
22

33
[recent browser="new"]
44

5-
The nullish coalescing operator is written as two question marks `??`.
5+
O operador de coalescência nula é escrito usando dois sinais de interrogação `??`.
66

7-
As it treats `null` and `undefined` similarly, we'll use a special term here, in this article. We'll say that an expression is "defined" when it's neither `null` nor `undefined`.
7+
Como ele trata `null` e `undefined` da mesma forma, nós iremos usar um termo especial aqui, neste artigo. Diremos que uma expressão está definida quando não é `null` nem `undefined`.
88

9-
The result of `a ?? b` is:
10-
- if `a` is defined, then `a`,
11-
- if `a` isn't defined, then `b`.
9+
O resultado de `a ?? b` é:
1210

13-
In other words, `??` returns the first argument if it's not `null/undefined`. Otherwise, the second one.
11+
- se `a` é definido, então `a`,
12+
- se `a` não é definido, então `b`.
1413

15-
The nullish coalescing operator isn't anything completely new. It's just a nice syntax to get the first "defined" value of the two.
14+
Em outras palavras, `??` retorna o primeiro argumento se ele não for `null/undefined`. Caso contrário, o segundo.
1615

17-
We can rewrite `result = a ?? b` using the operators that we already know, like this:
16+
O operador de coalescência nula não é algo completamente novo. É somente uma sintaxe bacana para obter o primeiro valor "definido" entre os dois.
17+
18+
Podemos reescrever `result = a ?? b` usando os operadores que já conhecemos, assim:
1819

1920
```js
20-
result = (a !== null && a !== undefined) ? a : b;
21+
result = a !== null && a !== undefined ? a : b;
2122
```
2223

23-
Now it should be absolutely clear what `??` does. Let's see where it helps.
24+
Agora, deveria estar completamente claro o que `??` faz. Vamos ver onde ele é útil.
2425

25-
The common use case for `??` is to provide a default value for a potentially undefined variable.
26+
O caso de uso comum para `??` é obter um valor padrão para uma variável potencialmente indefinida.
2627

27-
For example, here we show `user` if defined, otherwise `Anonymous`:
28+
Por exemplo, aqui exibimos `Anônimo` se `user` não for definido:
2829

2930
```js run
3031
let user;
3132

32-
alert(user ?? "Anonymous"); // Anonymous (user not defined)
33+
alert(user ?? "Anônimo"); // Anônimo ("user" não definido)
3334
```
3435
35-
Here's the example with `user` assigned to a name:
36+
Aqui está o exemplo com um nome atribuído a `user`:
3637
3738
```js run
38-
let user = "John";
39+
let user = "João";
3940

40-
alert(user ?? "Anonymous"); // John (user defined)
41+
alert(user ?? "Anônimo"); // João ("user" está definido)
4142
```
4243
43-
We can also use a sequence of `??` to select the first value from a list that isn't `null/undefined`.
44+
Podemos também usar uma sequência de `??` para selecionar o primeiro valor em uma lista que não seja `null/undefined`.
4445
45-
Let's say we have a user's data in variables `firstName`, `lastName` or `nickName`. All of them may be not defined, if the user decided not to enter a value.
46+
Digamos que temos dados de um usuário nas variáveis `nome`, `sobrenome` ou `apelido`. Todos eles podem ser indefinidos, se o usuário optar por não entrar com um valor.
4647
47-
We'd like to display the user name using one of these variables, or show "Anonymous" if all of them aren't defined.
48+
Gostaríamos de exibir o nome do usuário usando uma dessas variáveis, ou exibir "Anônimo" se todas elas forem indefinidas.
4849
49-
Let's use the `??` operator for that:
50+
Para isso usaremos o operador `??`:
5051
5152
```js run
5253
let firstName = null;
5354
let lastName = null;
5455
let nickName = "Supercoder";
5556

56-
// shows the first defined value:
57+
// exibe o primeiro valor definido:
5758
*!*
58-
alert(firstName ?? lastName ?? nickName ?? "Anonymous"); // Supercoder
59+
alert(firstName ?? lastName ?? nickName ?? "Anônimo"); // Supercoder
5960
*/!*
6061
```
6162
62-
## Comparison with ||
63+
## Comparação com ||
6364
64-
The OR `||` operator can be used in the same way as `??`, as it was described in the [previous chapter](info:logical-operators#or-finds-the-first-truthy-value).
65+
O operador OU `||` pode ser utilizado da mesma forma que `??`, como descrito no [capítulo anterior](info:logical-operators#or-finds-the-first-truthy-value).
6566
66-
For example, in the code above we could replace `??` with `||` and still get the same result:
67+
Por exemplo, no código acima podemos substituir `??` por `||` e o resultado se mantém:
6768
6869
```js run
6970
let firstName = null;
7071
let lastName = null;
7172
let nickName = "Supercoder";
7273

73-
// shows the first truthy value:
74+
// exibe o primeiro valor avaliado como verdadeiro:
7475
*!*
75-
alert(firstName || lastName || nickName || "Anonymous"); // Supercoder
76+
alert(firstName || lastName || nickName || "Anônimo"); // Supercoder
7677
*/!*
7778
```
7879
79-
Historically, the OR `||` operator was there first. It exists since the beginning of JavaScript, so developers were using it for such purposes for a long time.
80+
Historicamente, o operador OU `||` foi o primeiro a existir. Ele existe desde a criação do JavaScript, e vem sendo utilizado para este propósito desde então.
81+
82+
Por outro lado, o operador de coalescência nula `??` foi adicionado ao JavaScript recentemente, e a razão para isso foi o descontentamento com `||`.
8083
81-
On the other hand, the nullish coalescing operator `??` was added to JavaScript only recently, and the reason for that was that people weren't quite happy with `||`.
84+
A principal diferença entre eles é:
8285
83-
The important difference between them is that:
84-
- `||` returns the first *truthy* value.
85-
- `??` returns the first *defined* value.
86+
- `||` retorna o primeiro valor avaliado como `true`.
87+
- `??` retorna o primeiro valor _definido_.
8688
87-
In other words, `||` doesn't distinguish between `false`, `0`, an empty string `""` and `null/undefined`. They are all the same -- falsy values. If any of these is the first argument of `||`, then we'll get the second argument as the result.
89+
Em outras palavras, `||` não diferencia entre `false`, `0`, uma string vazia `""` e `null/undefined`. Todos são igualmente valores avaliados como falsos. Se algum desses for o primeiro argumento de `||`, então teremos o segundo argumento como resultado.
8890
89-
In practice though, we may want to use default value only when the variable is `null/undefined`. That is, when the value is really unknown/not set.
91+
Na prática, porém, gostaríamos de usar valores padrão somente se a variável é `null/undefined`. Ou seja, quando o valor seja realmente desconhecido/não definido.
9092
91-
For example, consider this:
93+
Por exemplo, considere isso:
9294
9395
```js run
9496
let height = 0;
@@ -97,73 +99,73 @@ alert(height || 100); // 100
9799
alert(height ?? 100); // 0
98100
```
99101
100-
- The `height || 100` checks `height` for being a falsy value, and it's `0`, falsy indeed.
101-
- so the result of `||` is the second argument, `100`.
102-
- The `height ?? 100` checks `height` for being `null/undefined`, and it's not,
103-
- so the result is `height` "as is", that is `0`.
102+
- `height || 100` verifica se `height` é um valor avaliado como falso, e como é `0`, de fato é.
103+
- então o resultado de `||` é o segundo argumento, `100`.
104+
- `height ?? 100` verifica se `height` é `null/undefined`, e não é,
105+
- então o resultado é o valor atual de `height`, que é `0`.
104106
105-
In practice, the zero height is often a valid value, that shouldn't be replaced with the default. So `??` does just the right thing.
107+
Na prática, a altura igual a zero é um valor válido que não deve ser substituído pelo valor padrão, então usar `??` é o correto.
106108
107-
## Precedence
109+
## Precedência
108110
109-
The precedence of the `??` operator is the same as `||`. They both equal `4` in the [MDN table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table).
111+
A precedência do operador `??` é a mesma que a de `||`. Ambos são iguais a '4' na [tabela MDN](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table).
110112
111-
That means that, just like `||`, the nullish coalescing operator `??` is evaluated before `=` and `?`, but after most other operations, such as `+`, `*`.
113+
Isto significa que, tal como `||`, o operador de coalescência nula `??` é avaliado antes de `=` e `?`, mas após a maioria dos outros operadores, como `+` e `*`.
112114
113-
So if we'd like to choose a value with `??` in an expression with other operators, consider adding parentheses:
115+
Então, se quiser selecionar um valor com `??` em uma expressão com outros operadores, considere o uso de parênteses:
114116
115117
```js run
116118
let height = null;
117119
let width = null;
118120

119-
// important: use parentheses
121+
// importante: use parênteses
120122
let area = (height ?? 100) * (width ?? 50);
121123

122124
alert(area); // 5000
123125
```
124126
125-
Otherwise, if we omit parentheses, then as `*` has the higher precedence than `??`, it would execute first, leading to incorrect results.
127+
Caso contrário, se omitirmos os parênteses, como `*` tem maior precedência que `??`, ele será executado primeiro, levando a resultados incorretos.
126128
127129
```js
128-
// without parentheses
130+
// sem parênteses
129131
let area = height ?? 100 * width ?? 50;
130132

131-
// ...works the same as this (probably not what we want):
132-
let area = height ?? (100 * width) ?? 50;
133+
// ...funciona desta forma (provavelmente não como gostaríamos):
134+
let area = height ?? 100 * width ?? 50;
133135
```
134136
135-
### Using ?? with && or ||
137+
### Usando ?? com && ou ||
136138
137-
Due to safety reasons, JavaScript forbids using `??` together with `&&` and `||` operators, unless the precedence is explicitly specified with parentheses.
139+
Por razões de segurança, o JavaScript proíbe o uso de `??` junto dos operadores `&&` e `||`, a menos que a precedência seja explicitamente especificada usando parênteses.
138140
139-
The code below triggers a syntax error:
141+
O código abaixo dispara um erro de sintaxe:
140142
141143
```js run
142-
let x = 1 && 2 ?? 3; // Syntax error
144+
let x = 1 && 2 ?? 3; // Erro de sintaxe
143145
```
144146
145-
The limitation is surely debatable, it was added to the language specification with the purpose to avoid programming mistakes, when people start to switch from `||` to `??`.
147+
A limitação é certamente discutível, mas foi incluída na especificação da linguagem com o propósito de evitar erros de programação, quando as pessoas começaram a usar `??` em vez de `||`.
146148
147-
Use explicit parentheses to work around it:
149+
Use parênteses explícitos para corrigi-la:
148150
149151
```js run
150152
*!*
151-
let x = (1 && 2) ?? 3; // Works
153+
let x = (1 && 2) ?? 3; // Funciona
152154
*/!*
153155

154156
alert(x); // 2
155157
```
156158
157-
## Summary
159+
## Resumo
158160
159-
- The nullish coalescing operator `??` provides a short way to choose the first "defined" value from a list.
161+
- O operador de coalescência nula `??` disponibiliza uma sintaxe curta para obter um valor "definido" em uma lista.
160162
161-
It's used to assign default values to variables:
163+
É usado para atribuir valores a variáveis:
162164
163-
```js
164-
// set height=100, if height is null or undefined
165-
height = height ?? 100;
166-
```
165+
```js
166+
// grava height=100, se height é null ou undefined
167+
height = height ?? 100;
168+
```
167169
168-
- The operator `??` has a very low precedence, only a bit higher than `?` and `=`, so consider adding parentheses when using it in an expression.
169-
- It's forbidden to use it with `||` or `&&` without explicit parentheses.
170+
- O operador `??` possui uma precedência muito baixa, um pouco maior que `?` e `=`, portanto considere adicionar parênteses quando utilizá-lo em uma expressão.
171+
- É proibido usá-lo com `||` ou `&&` sem parênteses explícitos.

0 commit comments

Comments
 (0)