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 nullish coalescing operator is written as two question marks`??`.
5
+
O operador de coalescência nula é escrito usando dois sinais de interrogação`??`.
6
6
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`.
8
8
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` é:
12
10
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`.
14
13
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.
16
15
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:
18
19
19
20
```js
20
-
result =(a !==null&& a !==undefined)? a : b;
21
+
result = a !==null&& a !==undefined? a : b;
21
22
```
22
23
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.
24
25
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.
26
27
27
-
For example, here we show `user`if defined, otherwise `Anonymous`:
28
+
Por exemplo, aqui exibimos `Anônimo` se `user`não for definido:
28
29
29
30
```js run
30
31
let user;
31
32
32
-
alert(user ??"Anonymous"); //Anonymous (user not defined)
33
+
alert(user ??"Anônimo"); //Anônimo ("user" não definido)
33
34
```
34
35
35
-
Here's the example with `user` assigned to a name:
36
+
Aqui está o exemplo com um nome atribuído a `user`:
36
37
37
38
```js run
38
-
let user ="John";
39
+
let user ="João";
39
40
40
-
alert(user ??"Anonymous"); //John (user defined)
41
+
alert(user ??"Anônimo"); //João ("user" está definido)
41
42
```
42
43
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`.
44
45
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.
46
47
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.
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).
65
66
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:
67
68
68
69
```js run
69
70
let firstName =null;
70
71
let lastName =null;
71
72
let nickName ="Supercoder";
72
73
73
-
//shows the first truthy value:
74
+
//exibe o primeiro valor avaliado como verdadeiro:
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 `||`.
80
83
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 é:
82
85
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_.
86
88
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.
88
90
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.
90
92
91
-
For example, consider this:
93
+
Por exemplo, considere isso:
92
94
93
95
```js run
94
96
let height =0;
@@ -97,73 +99,73 @@ alert(height || 100); // 100
97
99
alert(height ??100); // 0
98
100
```
99
101
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`.
104
106
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.
106
108
107
-
## Precedence
109
+
## Precedência
108
110
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).
110
112
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`*`.
112
114
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:
114
116
115
117
```js run
116
118
let height =null;
117
119
let width =null;
118
120
119
-
//important: use parentheses
121
+
//importante: use parênteses
120
122
let area = (height ??100) * (width ??50);
121
123
122
124
alert(area); // 5000
123
125
```
124
126
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.
126
128
127
129
```js
128
-
//without parentheses
130
+
//sem parênteses
129
131
let area = height ??100* width ??50;
130
132
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;
133
135
```
134
136
135
-
### Using ?? with && or ||
137
+
### Usando ?? com && ou ||
136
138
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.
138
140
139
-
The code below triggers a syntax error:
141
+
O código abaixo dispara um erro de sintaxe:
140
142
141
143
```js run
142
-
let x =1&&2??3; //Syntax error
144
+
let x =1&&2??3; //Erro de sintaxe
143
145
```
144
146
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 `||`.
146
148
147
-
Use explicit parentheses to work around it:
149
+
Use parênteses explícitos para corrigi-la:
148
150
149
151
```js run
150
152
*!*
151
-
let x = (1&&2) ??3; //Works
153
+
let x = (1&&2) ??3; //Funciona
152
154
*/!*
153
155
154
156
alert(x); // 2
155
157
```
156
158
157
-
## Summary
159
+
## Resumo
158
160
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.
160
162
161
-
It's used to assign default values to variables:
163
+
É usado para atribuir valores a variáveis:
162
164
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
+
```
167
169
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