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
Copy file name to clipboardExpand all lines: 1-js/02-first-steps/12-nullish-coalescing-operator/article.md
+41-41Lines changed: 41 additions & 41 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2,50 +2,50 @@
2
2
3
3
[recent browser="new"]
4
4
5
-
Here, in this article, we'll say that an expression is "defined" when it's neither `null`nor`undefined`.
5
+
Qui, in questo articolo, diremo che un'espressione è "definita" quando non è né `null`né`undefined`.
6
6
7
-
The nullish coalescing operator is written as two question marks`??`.
7
+
Il nullish coalescing operator è scritto come due punti di domanda`??`.
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
+
Il risultato di`a ?? b`è:
10
+
-se`a`è definito, allora`a`,
11
+
-se`a`non è definito, allora`b`.
12
12
13
13
14
-
In other words, `??`returns the first argument if it's not `null/undefined`. Otherwise, the second one.
14
+
In altre parole, `??`ritorna il primo argomento se questo non è `null/undefined`. Altrimenti, ritorna il secondo.
15
15
16
-
The nullish coalescing operator isn't anything completely new. It's just a nice syntax to get the first "defined" value of the two.
16
+
Il nullish coalescing operator non è qualcosa di completamente nuovo. È solo un modo più elegante (una migliore sintassi) per recuperare il primo valore "definito" dei due.
17
17
18
-
We can rewrite `result = a ?? b`using the operators that we already know, like this:
18
+
Possiamo riscrivere `result = a ?? b`usando gli operatori che già conosciamo, nel seguente modo:
19
19
20
20
```js
21
21
result = (a !==null&& a !==undefined) ? a : b;
22
22
```
23
23
24
-
The common use case for `??`is to provide a default value for a potentially undefined variable.
24
+
Un caso d'uso comune per l'operatore `??`è quello di fornire un valore di default per una variabile potenzialmente "non definita".
25
25
26
-
For example, here we show `Anonymous`if`user`isn't defined:
26
+
Per esempio, qui mostriamo `Anonymous`se`user`non è definito:
27
27
28
28
```js run
29
29
let user;
30
30
31
31
alert(user ??"Anonymous"); // Anonymous
32
32
```
33
33
34
-
Of course, if`user`had any value except `null/undefined`, then we would see it instead:
34
+
Ovviamente, se`user`ha un qualsiasi valore eccetto `null/undefined`, allora vedremo quel valore:
35
35
36
36
```js run
37
37
let user ="John";
38
38
39
39
alert(user ??"Anonymous"); // John
40
40
```
41
41
42
-
We can also use a sequence of `??`to select the first value from a list that isn't`null/undefined`.
42
+
Possiamo anche usare una sequenza di `??`per selezionare, da una lista, il primo valore che non sia`null/undefined`.
43
43
44
-
Let's say we have a user's data in variables `firstName`, `lastName`or`nickName`. All of them may be undefined, if the user decided not to enter a value.
44
+
Per esempio, supponiamo di avere dei dati relativi ad un utente nelle variabili `firstName`, `lastName`o`nickName`. Tutte queste potrebbero essere non definite, se l'utente dovesse decidere di non inserirne i valori.
45
45
46
-
We'd like to display the user name using one of these variables, or show "Anonymous" if all of them are undefined.
46
+
Vorremmo visualizzare il nome dell'utente usando una di queste variabili, oppure mostrare "Anonymous" se tutte queste sono indefinite.
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).
63
+
L'operatore OR `||`può essere usato nello stesso modo dell'operatore `??`, come descritto nel [capitolo precedente](info:logical-operators#or-finds-the-first-truthy-value).
64
64
65
-
For example, in the code above we could replace `??`with`||`and still get the same result:
65
+
Per esempio, nel codice precedente potremmo rimpiazzare `??`con`||`e ottenere comunque il medesimo risultato:
The OR `||`operator exists since the beginning of JavaScript, so developers were using it for such purposes for a long time.
78
+
L'operatore OR `||`esiste sin dagli inizi di JavaScript, quindi gli sviluppatori lo hanno usato a tale scopo per molto tempo.
79
79
80
-
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`||`.
80
+
D'altro canto, il nullish coalescing operator `??`fu aggiunto in JavaScript recentemente, poichè le persone non erano del tutto felici dell'operatore`||`.
81
81
82
-
The important difference between them is that:
83
-
- `||`returns the first *truthy* value.
84
-
- `??`returns the first *defined* value.
82
+
L'importante differenza tra essi è la seguente:
83
+
- `||`ritorna il primo valore *truthy*.
84
+
- `??`ritorna il primo valore *definito*.
85
85
86
-
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.
86
+
In altre parole, `||`non distingue tra`false`, `0`, una stringa vuota`""`e`null/undefined`. Sono tutti, allo stesso modo -- valori "falsy". Se uno tra questi è il primo argomento di`||`, allora otterremo il secondo argomento come risultato.
87
87
88
-
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.
88
+
In pratica, però, potremmo voler usare il valore di default solamente quando la variabile è `null/undefined`. È in questo caso che il valore è davvero sconosciuto/non settato.
89
89
90
-
For example, consider this:
90
+
Per esempio, consideriamo questo:
91
91
92
92
```js run
93
93
let height =0;
@@ -96,18 +96,18 @@ alert(height || 100); // 100
96
96
alert(height ??100); // 0
97
97
```
98
98
99
-
- The `height ||100`checks `height`for being a falsy value, and it really is.
100
-
- so the result is the second argument, `100`.
101
-
- The `height ??100`checks `height`for being `null/undefined`, and it's not,
102
-
- so the result is`height` "as is", that is`0`.
99
+
- `height ||100`controlla se `height`possiede un valore "falsy", ed effettivamente così è,
100
+
- quindi il risultato è il secondo argomento, `100`.
101
+
- `height ??100`controlla se `height`è `null/undefined`, ma così non è,
102
+
- quindi il risultato è`height` "così com'è", ovvero`0`.
103
103
104
-
If the zero height is a valid value, that shouldn't be replaced with the default, then`??`does just the right thing.
104
+
Se un'altezza pari a zero è un valore accettabile, allora questo non dovrebbe essere rimpiazzato con il valore di default, quindi`??`fa la cosa giusta.
105
105
106
106
## Precedence
107
107
108
-
The precedence of the `??`operator is rather low: `5`in the [MDN table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table). So`??`is evaluated before `=`and`?`, but after most other operations, such as`+`, `*`.
108
+
La precedenza dell'operatore `??`è piuttosto bassa: `5`nella [MDN table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table). Quindi`??`è valutato prima di `=`e`?`, ma dopo la maggior parte degli altri operatori, come`+`, `*`.
109
109
110
-
So if we'd like to choose a value with `??` in an expression with other operators, consider adding parentheses:
110
+
Quindi, se volessimo scegliere un valore tramite l'operatore `??` in un'espressione contenente altri operatori, dovremmo considerare l'utilizzo delle parentesi:
111
111
112
112
```js run
113
113
let height =null;
@@ -119,7 +119,7 @@ let area = (height ?? 100) * (width ?? 50);
119
119
alert(area); // 5000
120
120
```
121
121
122
-
Otherwise, if we omit parentheses, then as `*`has the higher precedence than `??`, it would execute first, leading to incorrect results.
122
+
Altrimenti, se omettessimo le parentesi, siccome `*`ha una precedenza maggiore rispetto a `??`, sarebbe eseguito prima, portando a risultati scorretti.
123
123
124
124
```js
125
125
// without parentheses
@@ -131,17 +131,17 @@ let area = height ?? (100 * width) ?? 50;
131
131
132
132
### Using ?? with && or ||
133
133
134
-
Due to safety reasons, JavaScript forbids using `??`together with `&&`and`||` operators, unless the precedence is explicitly specified with parentheses.
134
+
Per motivi di sicurezza, JavaScript proibisce l'utilizzo di `??`insieme agli operatori `&&`e`||`, a meno che la precedenza non sia esplicitamente specificata tramite l'utilizzo delle parentesi.
135
135
136
-
The code below triggers a syntax error:
136
+
Il codice sottostante causa un errore di sintassi:
137
137
138
138
```js run
139
139
let x =1&&2??3; // Syntax error
140
140
```
141
141
142
-
The limitation is surely debatable, but it was added to the language specification with the purpose to avoid programming mistakes, when people start to switch to `??`from`||`.
142
+
La limitazione è sicuramente discutibile, ma fu aggiunta alle specifiche del linguaggio con lo scopo di evitare errori di programmazione nel momento in cui le persone hanno iniziato ad utilizzare `??`al posto di`||`.
143
143
144
-
Use explicit parentheses to work around it:
144
+
Per aggirare il problema si possono utilizzare delle parentesi esplicite:
145
145
146
146
```js run
147
147
*!*
@@ -153,14 +153,14 @@ alert(x); // 2
153
153
154
154
## Summary
155
155
156
-
- The nullish coalescing operator `??`provides a short way to choose the first "defined" value from a list.
156
+
- Il nullish coalescing operator `??`fornisce una breve strada per la scelta del primo valore "definito" da una lista di valori.
157
157
158
-
It's used to assign default values to variables:
158
+
È usato per assegnare valori di default alle variabili:
159
159
160
160
```js
161
161
// set height=100, if height is null or undefined
162
162
height = height ??100;
163
163
```
164
164
165
-
- The operator `??`has a very low precedence, only a bit higher than `?`and`=`, so consider adding parentheses when using it in an expression.
166
-
- It's forbidden to use it with `||`or`&&`without explicit parentheses.
165
+
- L'operatore `??`ha una precedenza molto bassa, solo un po' più alta di `?`e`=`, quindi considerare l'aggiunta di parentesi quando lo si utilizza all'interno di un'espressione.
166
+
- È proibito usarlo con `||`o`&&`senza l'utilizzo di parentesi esplicite.
0 commit comments