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
Note, we could use a shorter name `planet`, but it might be not obvious what planet it refers to. It's nice to be more verbose. At least until the variable isNotTooLong.
9
+
Зверніть увагу, ми могли використати коротше ім'я `planet`, але тоді буде не зрозуміло, яку планету ми маємо на увазі. Краще описати вміст змінної детальніше. Принаймні до тих пір, поки ім'я змінної неСтанеЗанадтоДовгим.
10
10
11
-
Second, the name of the current visitor:
11
+
2. Ім'я поточного відвідувача:
12
12
13
13
```js
14
-
let currentUserName ="John";
14
+
let currentUserName ="Іван";
15
15
```
16
16
17
-
Again, we could shorten that to`userName` if we know for sure that the user is current.
17
+
Знову ж таки, ми можемо скоротити ім'я до`userName`, якщо ми точно знатимемо що це поточний відвідувач.
18
18
19
-
Modern editors and autocomplete make long variable names easy to write. Don't save on them. A name with 3 words in it is fine.
19
+
Сучасні редактори і автодоповнювачі дозволяють легко писати довгі імена змінних. Не економте букв. Імена з трьох слів цілком нормальні.
20
20
21
-
And if your editor does not have proper autocompletion, get [a new one](/code-editors).
21
+
Якщо в вашому редакторі немає автодоповнювача, скористайтеся [іншим](/code-editors).
We generally use upper case for constants that are "hard-coded". Or, in other words, when the value is known prior to execution and directly written into the code.
1
+
Зазвичай, ми використовуємо великі букви для констант, які "жорстко закодовані" (hardcoded). Іншими словами, коли значення константи відоме до початку виконання скрипта і записується безпосередньо в код.
2
2
3
-
In this code, `birthday`is exactly like that. So we could use the upper case for it.
3
+
В нашому випадку, `birthday`саме така змінна. Тому для неї ми можемо використати великі букви.
4
4
5
-
In contrast, `age`is evaluated in run-time. Today we have one age, a year after we'll have another one. It is constant in a sense that it does not change through the code execution. But it is a bit "less of a constant" than `birthday`, it is calculated, so we should keep the lower case for it.
5
+
На відмінну від попередньої, константа `age`обчислюється під час виконання скрипта. Сьогодні в нас один вік, а через рік вже зовсім інший. Вона є константою, тому що не змінюється під час виконання коду. Але вона "трохи менша" константа, ніж `birthday`, вона обчислюється, тому ми повинні зберегти її в нижньому регістрі.
Copy file name to clipboardExpand all lines: 1-js/02-first-steps/04-variables/3-uppercast-constant/task.md
+6-6Lines changed: 6 additions & 6 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2,23 +2,23 @@ importance: 4
2
2
3
3
---
4
4
5
-
# Uppercase const?
5
+
# Використовувати великі чи маленькі букви для імен констант?
6
6
7
-
Examine the following code:
7
+
Переглянемо наступний код:
8
8
9
9
```js
10
10
constbirthday='18.04.1982';
11
11
12
12
constage=someCode(birthday);
13
13
```
14
14
15
-
Here we have a constant `birthday` date and the `age` is calculated from `birthday` with the help of some code (it is not provided for shortness, and because details don't matter here).
15
+
В нас є константа `birthday`, а також `age`, яка вираховується за допомогою функції, використовуючи значення із `birthday` (в даному випадку деталі не мають значення, тому код функції не розглядається).
16
16
17
-
Would it be right to use upper case for `birthday`? For `age`? Or even for both?
17
+
Чи можна використовувати великі букви для імені `birthday`? А для `age`? Чи для обох змінних?
18
18
19
19
```js
20
-
constBIRTHDAY='18.04.1982'; //make uppercase?
20
+
constBIRTHDAY='18.04.1982'; //використовувати великі букви?
Copy file name to clipboardExpand all lines: 1-js/02-first-steps/04-variables/article.md
+24-25Lines changed: 24 additions & 25 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -286,46 +286,45 @@ const pageLoadTime = /* час, потрачений на завантаженн
286
286
287
287
Іншими словами, константи з великими буквами, використовуються як псевдоніми для "жорстко закодованих" значень.
288
288
289
-
## Name things right
289
+
## Придумуйте правильні імена
290
290
291
-
Talking about variables, there's one more extremely important thing.
291
+
В розмові про змінні необхідно згадати, що є ще одна дуже важлива річ -- правильні імена змінних.
292
292
293
-
Please name your variables sensibly. Take time to think about this.
293
+
Такі імена повинні мати ясний і зрозумілий сенс, говорити про те, які дані в них зберігаються.
294
294
295
-
Variable naming is one of the most important and complex skills in programming. A quick glance at variable names can reveal which code was written by a beginner versus an experienced developer.
295
+
Іменування змінних -- одна з найважливіших і найскладніших навичок в програмуванні. Швидкий перегляд змінних може показати, чи код був написаний новачком чи досвідченим розробником.
296
296
297
-
In a real project, most of the time is spent modifying and extending an existing code base rather than writing something completely separate from scratch. When we return to some code after doing something else for a while, it's much easier to find information that is well-labeled. Or, in other words, when the variables have good names.
297
+
В реальному проекті, більшість часу тратиться на змінення і розширення існуючої кодової бази, а не на написання чогось цілком нового. Коли ми повертаємося до якогось коду, після виконання чогось іншого впродовж тривалого часу, набагато легше знайти інформацію, яку добре позначено. Або, іншими словами, коли змінні мають хороші імена.
298
298
299
-
Please spend time thinking about the right name for a variable before declaring it. Doing so will repay you handsomely.
299
+
Будь ласка, приділіть час на обдумування правильного імені для змінної перед її оголошенням. Робіть так, і будете винагороджені.
300
300
301
-
Some good-to-follow rules are:
301
+
Декілька хороших правил:
302
302
303
-
- Use human-readable names like `userName` or `shoppingCart`.
304
-
- Stay away from abbreviations or short names like `a`, `b`, `c`, unless you really know what you're doing.
305
-
- Make names maximally descriptive and concise. Examples of bad names are `data` and `value`. Such names say nothing. It's only okay to use them if the context of the code makes it exceptionally obvious which data or value the variable is referencing.
306
-
- Agree on terms within your team and in your own mind. If a site visitor is called a "user" then we should name related variables `currentUser` or `newUser` instead of `currentVisitor` or `newManInTown`.
307
-
- Використовуйте імені лише англійською мовою. Оголошення `let message` і `let повідомлення` будуть працювати, проте перший варіант є хорошим тоном для написання коду.
303
+
- Використовуйте імена, які легко прочитати, наприклад, `userName` або `shoppingCart`.
304
+
- Уникайте використання абревіатур або коротких імен, таких як `a`, `b`, `c`, за винятками тих випадків, коли ви точно знаєте, що так потрібно.
305
+
- Робіть імена максимально описовими і лаконічними. Наприклад, такі імена погані: `data` і `value`. Такі імена нічого не говорять. Їх можна використовувати лише тоді, коли з контексту очевидно, на які дані або значення посилається змінна.
306
+
- Узгодьте з вашою командою, які терміни будуть використовуватися. Якщо відвідувач сайту називається "user", тоді ми повинні давати відповідні імена іншим пов'язаним змінним: `currentUser` або `newUser`, замість `currentVisitor` або `newManInTown`.
308
307
309
-
Sounds simple? Indeed it is, but creating descriptive and concise variable names in practice is not. Go for it.
308
+
Звучить легко? Це дійсно так, проте на практиці створення зрозумілих і коротких імен -- рідкість. Дійте.
310
309
311
-
```smart header="Reuse or create?"
312
-
And the last note. There are some lazy programmers who, instead of declaring new variables, tend to reuse existing ones.
310
+
```smart header="Перевикористовувати чи створювати?"
311
+
І остання примітка. Є ліниві програмісти, які замість оголошення нових змінних, повторно використовують існуючі.
313
312
314
-
As a result, their variables are like boxes into which people throw different things without changing their stickers. What's inside the box now? Who knows? We need to come closer and check.
313
+
В результаті їхні змінні схожі на коробки, в які люди кидають різні речі, не змінюючи на них наклейки. Що зараз знаходиться всередині коробки? Хто знає? Нам необхідно підійти поближче і перевірити.
315
314
316
-
Such programmers save a little bit on variable declaration but lose ten times more on debugging.
315
+
Такі програмісти економлять трішки часу на оголошенні змінних, але втрачають вдесятеро більше при відлагодженні.
317
316
318
-
An extra variable is good, not evil.
317
+
Додаткова змінна -- це добро, а не зло.
319
318
320
-
Modern JavaScript minifiers and browsers optimize code well enough, so it won't create performance issues. Using different variables for different values can even help the engine optimize your code.
319
+
Сучасні JavaScript мініфікатори і браузери оптимізують код досить добре, тому додаткові змінні не погіршують продуктивність. Використання різних змінних для різних значень може навіть допомогти рушію оптимізувати ваш код.
321
320
```
322
321
323
-
## Summary
322
+
## Підсумки
324
323
325
-
We can declare variables to store data by using the `var`, `let`, or `const` keywords.
324
+
Ми можемо оголосити змінні для збереження даних за допомогою ключових слів `var`, `let`, чи `const`.
326
325
327
-
- `let` -- is a modern variable declaration. The code must be in strict mode to use `let` in Chrome (V8).
328
-
- `var` -- is an old-school variable declaration. Normally we don't use it at all, but we'll cover subtle differences from `let` in the chapter <info:var>, just in case you need them.
329
-
- `const` -- is like `let`, but the value of the variable can't be changed.
326
+
- `let` -- це сучасний спосіб оголошення. При використанні `let` в Chrome (V8) повинен бути включений строгий режим.
327
+
- `var` -- це застарілий спосіб оголошення змінної. Зазвичай ми не використовуємо його взагалі, але ми розглянемо тонкі відмінності від `let` в розділі <info:var>, на випадок, якщо це все-таки знадобиться.
328
+
- `const` -- це як `let`, але значення змінної не може змінюватися.
330
329
331
-
Variables should be named in a way that allows us to easily understand what's inside them.
330
+
Змінні повинні називатися таким чином, щоб ми могли легко зрозуміти, що в середині них.
0 commit comments