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
+
Оператор об’єднання з null записується як два знаки питання`??`.
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
+
В цій статті ми будемо писати, що значення виразу "визначене", якщо воно відрізняється від `null`чи`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
+
Результатом `a ?? b`буде:
10
+
-`a`, якщо`a` визначене,
11
+
-`b`, якщо `a` не визначене.
12
12
13
-
In other words, `??`returns the first argument if it's not `null/undefined`. Otherwise, the second one.
13
+
Інакше кажучи, `??`повертає перший аргумент, якщо він не `null/undefined`. Інакше, другий.
14
14
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.
15
+
Оператор об’єднання з null не є абсолютно новим. Це просто хороший синтаксис, щоб отримати перше "визначене" значення з двох.
16
16
17
-
We can rewrite `result = a ?? b` using the operators that we already know, like this:
17
+
Ми можемо переписати вираз `result = a ?? b`, використовуючи оператори, які ми вже знаємо:
18
18
19
19
```js
20
20
result = (a !==null&& a !==undefined) ? a : b;
21
21
```
22
22
23
-
Now it should be absolutely clear what`??` does. Let's see where it helps.
23
+
Тепер повинно бути абсолютно зрозуміло, що робить`??`. Подивімось, де це допомагає.
24
24
25
-
The common use case for `??`is to provide a default value for a potentially undefined variable.
25
+
В загальному, оператор `??`використовують, щоб забезпечити типове значення для потенційно невизначеної змінної.
26
26
27
-
For example, here we show`user` if defined, otherwise `Anonymous`:
27
+
Наприклад, тут ми показуємо`user`, якщо він визначений, інакше `Анонімний`:
28
28
29
29
```js run
30
30
let user;
31
31
32
-
alert(user ??"Anonymous"); //Anonymous (user not defined)
32
+
alert(user ??"Анонімний"); //Анонімний (user не визначений)
33
33
```
34
34
35
-
Here's the example with `user` assigned to a name:
We can also use a sequence of `??` to select the first value from a list that isn't`null/undefined`.
43
+
Ми також можемо використовувати послідовність з `??`, щоб вибрати перше значення зі списку, яке не є`null/undefined`.
44
44
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.
45
+
Скажімо, у нас є дані користувача в змінних `firstName`, `lastName`або`nickName`. Всі вони можуть бути не визначені, якщо користувач вирішив не вводити значення.
46
46
47
-
We'd like to display the user name using one of these variables, or show "Anonymous" if all of them aren't defined.
47
+
Ми хотіли б показати ім’я користувача, використовуючи одну з цих змінних, або показати "Анонімний", якщо всі вони не визначені.
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).
64
+
Оператор АБО`||`може бути використаний таким же чином, як `??`, як це було описано в [попередній главі](info:logical-operators#or-finds-the-first-truthy-value).
65
65
66
-
For example, in the code above we could replace`??`with`||`and still get the same result:
66
+
Наприклад, у коді вище, ми могли б замінити`??`на`||`і все ще отримали б той самий результат:
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.
79
+
Історично, оператор АБО`||`був першим. Він існує з початку JavaScript, тому розробники використовували його для цих цілей протягом тривалого часу.
80
80
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`||`.
81
+
З іншого боку, оператор об’єднання з null`??`було нещодавно додано в JavaScript, і причиною того було те, що люди були не дуже задоволені`||`.
82
82
83
-
The important difference between them is that:
84
-
- `||`returns the first *truthy* value.
85
-
- `??`returns the first *defined* value.
83
+
Важлива різниця між ними полягає в тому, що:
84
+
- `||`повертає перше *істинне* значення.
85
+
- `??`повертає перше *визначене* значення.
86
86
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.
87
+
Інакше кажучи, оператор `||`не розрізняє, чи значення `false`, `0`, порожній рядок `""`чи`null/undefined`. Всі вони однакові -- хибні значення. Якщо будь-яке з них є першим аргументом `||`, тоді ми отримаємо другий аргумент як результат.
88
88
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.
89
+
Однак на практиці, ми хочемо використовувати типове значення лише тоді, коли змінна `null/undefined`. Тобто, коли значення дійсно невідоме/не встановлене.
90
90
91
-
For example, consider this:
91
+
Наприклад, розгляньте це:
92
92
93
93
```js run
94
94
let height =0;
@@ -97,73 +97,73 @@ alert(height || 100); // 100
97
97
alert(height ??100); // 0
98
98
```
99
99
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`.
100
+
- `height ||100`перевіряє чи має змінна `height`має хибне значення, і `0` -- це дійсно хибне значення.
101
+
- отже, результатом `||`є другий аргумент, `100`.
102
+
- `height ??100`перевіряє змінну `height`, чи вона`null/undefined`, і це не так,
103
+
- отже, результат -- `height` "як є", тобто`0`.
104
104
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.
105
+
На практиці нульова висота часто є дійсним значенням, яке не слід замінювати на типове значення. Отже,`??`робить саме те, що треба.
106
106
107
-
## Precedence
107
+
## Пріоритет
108
108
109
-
The precedence of the `??`operator is about the same as `||`, just a bit lower. It equals`5`in the [MDN table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table), while `||`is`6`.
109
+
Пріоритет оператора `??`приблизно такий самий, як `||`, тільки трохи нижчий. Він дорівнює`5`у [таблиці MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table), а пріоритет `||`--`6`.
110
110
111
-
That means that, just like`||`, the nullish coalescing operator`??`is evaluated before `=`and`?`, but after most other operations, such as`+`, `*`.
111
+
Це означає, що, як і`||`, оператор об’єднання з null`??`оцінюється до `=`та`?`, але після більшості інших операцій, таких як`+`, `*`.
112
112
113
-
So if we'd like to choose a value with`??`in an expression with other operators, consider adding parentheses:
113
+
Отже, якщо ми хотіли б вибрати значення за допомогою`??`у виразі з іншими операторами, розгляньте додавання дужок:
114
114
115
115
```js run
116
116
let height =null;
117
117
let width =null;
118
118
119
-
//important: use parentheses
119
+
//важливо: використовуйте дужки
120
120
let area = (height ??100) * (width ??50);
121
121
122
122
alert(area); // 5000
123
123
```
124
124
125
-
Otherwise, if we omit parentheses, then as`*`has the higher precedence than `??`, it would execute first, leading to incorrect results.
125
+
В іншому випадку, якщо ми опускаємо дужки, то, оскільки`*`має вищий пріоритет, ніж `??`, то він буде виконуватися першим, що призводить до неправильних результатів.
126
126
127
127
```js
128
-
//without parentheses
128
+
//без дужок
129
129
let area = height ??100* width ??50;
130
130
131
-
// ...works the same as this (probably not what we want):
131
+
// ...працює так само, як попередній вираз (мабуть, це не те, що ми хочемо):
132
132
let area = height ?? (100* width) ??50;
133
133
```
134
134
135
-
### Using ?? with && or ||
135
+
### Використання ?? разом з && або ||
136
136
137
-
Due to safety reasons, JavaScript forbids using`??`together with `&&`and`||` operators, unless the precedence is explicitly specified with parentheses.
137
+
З міркувань безпеки, JavaScript забороняє використання`??`разом з операторами `&&`та`||`, якщо пріоритет явно не вказаний дужками.
138
138
139
-
The code below triggers a syntax error:
139
+
Код нижче викликає синтаксичну помилку:
140
140
141
141
```js run
142
-
let x =1&&2??3; //Syntax error
142
+
let x =1&&2??3; //Синтаксична помилка
143
143
```
144
144
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`??`.
145
+
Обмеження є досить спірним, воно було додано до специфікації мови з метою уникнення помилок програмування, коли люди почнуть переходити з `||`до`??`.
146
146
147
-
Use explicit parentheses to work around it:
147
+
Використовуйте явні дужки, щоб працювати з цим оператором:
148
148
149
149
```js run
150
150
*!*
151
-
let x = (1&&2) ??3; //Works
151
+
let x = (1&&2) ??3; //Працює
152
152
*/!*
153
153
154
154
alert(x); // 2
155
155
```
156
156
157
-
## Summary
157
+
## Підсумки
158
158
159
-
- The nullish coalescing operator`??`provides a short way to choose the first "defined" value from a list.
159
+
- Оператор об’єднання з null`??`надає короткий спосіб вибору першого "визначеного" значення зі списку.
160
160
161
-
It's used to assign default values to variables:
161
+
Він використовується для присвоєння типових значень до змінних:
162
162
163
163
```js
164
-
//set height=100, if height is null or undefined
164
+
//встановлює height=100, якщо height null чи undefined
165
165
height = height ??100;
166
166
```
167
167
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.
168
+
- Оператор `??`має дуже низький пріоритет -- трохи вищий, ніж `?`та`=`, тому розглядайте додавання дужок при використанні його у виразах.
169
+
- Цей оператор заборонено використовувати з `||`або`&&`без явних дужок.
0 commit comments