This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Ключове слово `var` *майже* таке, як `let`. Воно теж оголошує змінну, але дещо іншим, "застарілим" способом.
Є деякі відмінності між `let` і `var`, але вони поки що не мають для нас значення. Ми дізнаємося більше про ці відмінності в розділі <info:var>.
=======
The `var` keyword is *almost* the same as `let`. It also declares a variable but in a slightly different, "old-school" way.
There are subtle differences between `let` and `var`, but they do not matter to us yet. We'll cover them in detail in the chapter <info:var>.
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
````
## Аналогія з життя
Ми легко зрозуміємо концепцію "змінної", якщо уявимо її у вигляді "коробки" для даних з унікальною назвою на наклейці.
<<<<<<< HEAD
Наприклад, змінну `message` можна уявити як коробку з написом `"Повідомлення"` зі значенням `"Привіт!"` всередині:
=======
For instance, the variable `message` can be imagined as a box labelled `"message"` with the value `"Hello!"` in it:
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3

Expand Down
Expand Up
@@ -197,15 +207,24 @@ let my-name; // дефіс '-' недопустимий в імені
Змінні з іменами `apple` і `APPLE` -- це дві різні змінні.
```
<<<<<<< HEAD
````smart header="Нелатинські букви дозволені, але не рекомендуються"
Можна використовувати будь-яку мову, включно з кирилицею або навіть ієрогліфами, наприклад:
=======
````smart header="Non-Latin letters are allowed, but not recommended"
It is possible to use any language, including Cyrillic letters, Chinese logograms and so on, like this:
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
```js
let назва = '...';
let 我 = '...';
```
<<<<<<< HEAD
Технічно тут немає помилки. Такі імена дозволені, проте є міжнародна традиція використовувати англійську мову в іменах змінних (наприклад, `yaLyublyuUkrainu` => `iLoveUkraine`). Навіть якщо ми пишемо маленький скрипт, у нього може бути тривале життя попереду. Можливо, людям з інших країн колись доведеться прочитати його.
=======
Technically, there is no error here. Such names are allowed, but there is an international convention to use English in variable names. Even if we're writing a small script, it may have a long life ahead. People from other countries may need to read it sometime.
myBirthday = '01.01.2001'; // помилка, не можна перевизначати константу!
```
<<<<<<< HEAD
Коли програміст впевнений, що змінна ніколи не буде змінюватися, він може оголосити її через `const`, що гарантує постійність і буде зрозумілим для кожного.
=======
When a programmer is sure that a variable will never change, they can declare it with `const` to guarantee and communicate that fact to everyone.
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
### Константи в верхньому регістрі
<<<<<<< HEAD
Широко поширена практика використання констант як псевдонімів для значень, які важко запам’ятати і які відомі до початку виконання скрипту.
=======
There is a widespread practice to use constants as aliases for difficult-to-remember values that are known before execution.
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
Такі константи пишуться в верхньому регістрі з використанням підкреслень.
Expand All
@@ -289,15 +316,23 @@ alert(color); // #FF7F00
Коли ми маємо використовувати для констант великі букви, а коли звичайні? Давайте це з’ясуємо.
<<<<<<< HEAD
Назва "константа" лише означає, що змінна ніколи не зміниться. Але є константи, які відомі нам до виконання скрипту (наприклад, шістнадцяткове значення для червоного кольору), а є константи, які *вираховуються* в процесі виконання скрипту, але не змінюються після їхнього початкового присвоєння.
=======
Being a "constant" just means that a variable's value never changes. But some constants are known before execution (like a hexadecimal value for red) and some constants are *calculated* in run-time, during the execution, but do not change after their initial assignment.
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
Наприклад:
```js
const pageLoadTime = /* час, потрачений на завантаження вебсторінки */;
```
<<<<<<< HEAD
Значення `pageLoadTime` невідоме до завантаження сторінки, тому її ім’я записано звичайними, а не великими буквами. Але це все ще константа, тому що вона не змінює значення після присвоєння.
=======
The value of `pageLoadTime` is not known before the page load, so it's named normally. But it's still a constant because it doesn't change after the assignment.
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
Інакше кажучи, константи з великими буквами використовуються як псевдоніми для "жорстко закодованих" значень.
Expand All
@@ -307,18 +342,31 @@ const pageLoadTime = /* час, потрачений на завантаженн
Такі імена повинні мати чіткий і зрозумілий сенс, який описує дані, що в них зберігаються.
<<<<<<< HEAD
Іменування змінних -- одна з найважливіших і найскладніших навичок у програмуванні. Швидкий погляд на імена змінних може показати, який код був написаний початківцем, а який досвідченим розробником.
У реальному проєкті більшість часу тратиться на змінення і розширення наявної кодової бази, а не на написання чогось цілком нового. Коли ми повертаємося до якогось коду після виконання чогось іншого впродовж тривалого часу, набагато легше знайти інформацію, яку добре позначено. Або, інакше кажучи, коли змінні мають хороші імена.
=======
Variable naming is one of the most important and complex skills in programming. A glance at variable names can reveal which code was written by a beginner versus an experienced developer.
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-labelled. Or, in other words, when the variables have good names.
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
Будь ласка, приділяйте час на обдумування правильного імені для змінної перед її оголошенням. Робіть так, і будете винагороджені.
Декілька хороших правил:
<<<<<<< HEAD
- Використовуйте імена, які легко прочитати, як-от `userName` або `shoppingCart`.
- Уникайте використання абревіатур або коротких імен, таких як `a`, `b` та `c`, окрім тих випадків, коли ви точно знаєте, що так потрібно.
- Робіть імена максимально описовими і лаконічними. Наприклад, такі імена погані: `data` і `value`. Такі імена нічого не говорять. Їх можна використовувати лише тоді, коли з контексту очевидно, на які дані або значення посилається змінна.
- Погоджуйте з вашою командою (та з самим собою), які терміни будуть використовуватися у проєкті. Якщо відвідувач сайту називається "user", тоді ми маємо давати відповідні імена іншим пов’язаним змінним: `currentUser` або `newUser`, замість `currentVisitor` або `newManInTown`.
=======
- Use human-readable names like `userName` or `shoppingCart`.
- Stay away from abbreviations or short names like `a`, `b`, and `c`, unless you know what you're doing.
- 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.
- Agree on terms within your team and in your mind. If a site visitor is called a "user" then we should name related variables `currentUser` or `newUser` instead of `currentVisitor` or `newManInTown`.
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
Звучить легко? Це дійсно так, проте на практиці створення зрозумілих і коротких імен -- рідкість. Дійте.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Через те, що тип `BigInt` рідко використовується, ми не розглядатимемо його в цьому розділі, проте ми винесли його в окремий розділ <info:bigint>. Прочитайте його, якщо вам потрібні такі великі числа.
<<<<<<< HEAD
```smart header="Проблеми із сумісністю"
Цієї миті, підтримка типу `BigInt` є в останніх версіях Firefox/Chrome/Edge/Safari, але не в IE.
На сайті *MDN* є [таблиця сумісності](https://developer.mozilla.org/uk/docs/Web/JavaScript/Reference/Global_Objects/BigInt#Сумісність_з_веб-переглядачами), де показано, які версії браузерів підтримують тип `BigInt`.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- Оператори порівняння повертають значення логічного типу.
- Рядки порівнюються посимвольно в лексикографічному порядку.
- Значення різних типів під час порівняння конвертуються в числа. Винятками є порівняння за допомогою операторів строгої рівності/нерівності.
- Значення `null` і `undefined` рівні `==` один одному і не рівні будь-якому іншому значенню.
- Будьте обережні, використовуючи оператори порівняння на зразок `>` чи `<` зі змінними, які можуть приймати значення `null/undefined`. Хорошою ідеєю буде зробити окрему перевірку на `null/undefined` для таких значень.
=======
- Comparison operators return a boolean value.
- Strings are compared letter-by-letter in the "dictionary" order.
- When values of different types are compared, they get converted to numbers (with the exclusion of a strict equality check).
- The values `null` and `undefined` are equal `==` to themselves and each other, but do not equal any other value.
- Be careful when using comparisons like `>` or `<` with variables that can occasionally be `null/undefined`. Checking for `null/undefined` separately is a good idea.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Тому це цілком звичайна ситуація, коли лише частина стандарту реалізована у самому рушії.
<<<<<<< HEAD
Хороша сторінка, щоб побачити поточний стан підтримки функцій мови, є тут <https://compat-table.github.io/compat-table/es6/> (вона велика, нам доведеться ще багато вивчати).
=======
A good page to see the current state of support for language features is <https://compat-table.github.io/compat-table/es6/> (it's big, we have a lot to study yet).
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
Як програмісти, ми б хотіли використовувати найновіші можливості. Чим більше хороших речей — тим краще!
Expand Down
Expand Up
@@ -71,9 +75,13 @@ if (!Math.trunc) { // якщо немає такої функції
JavaScript дуже динамічна мова -- скрипти можуть додавати чи оновлювати функції, навіть якщо вони вбудовані.
<<<<<<< HEAD
Є два цікавих поліфіла:
- [core js](https://github.com/zloirock/core-js), що підтримує багато функціонала, дозволяє включати лише необхідні функції.
=======
One interesting polyfill library is [core-js](https://github.com/zloirock/core-js), which supports a wide range of features and allows you to include only the ones you need.
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
## Підсумки
Expand All
@@ -83,8 +91,16 @@ JavaScript дуже динамічна мова -- скрипти можуть
Наприклад, пізніше (коли достатньо вивчите JavaScript), ви зможете налаштувати систему збору проєкту на основі [webpack](https://webpack.js.org/) із плагіном [babel-loader](https://github.com/babel/babel-loader).
<<<<<<< HEAD
Ось хороші ресурси, де можна дізнатися поточний стан підтримки різного функціоналу:
- <https://compat-table.github.io/compat-table/es6/> - для чистого JavaScript.
- <https://caniuse.com/> - для браузерних функцій.
=======
Good resources that show the current state of support for various features:
- <https://compat-table.github.io/compat-table/es6/> - for pure JavaScript.
- <https://caniuse.com/> - for browser-related functions.
P.S. Google Chrome is usually the most up-to-date with language features, try it if a tutorial demo fails. Most tutorial demos work with any modern browser though.
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
P.S. Зазвичай браузер Google Chrome підтримує більшість найновіших функцій мови, спробуйте його, якщо демонстрація не працює. Більшість демонстрацій працюють із сучасними браузерами.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Sync with upstream @ d78b01e9 #781
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Uh oh!
There was an error while loading. Please reload this page.
Sync with upstream @ d78b01e9 #781
Filter by extension
Viewed files
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
There are no files selected for viewing
Uh oh!
There was an error while loading. Please reload this page.