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
Це називається "[Політикою того ж походження (Same Origin Policy)](https://uk.wikipedia.org/wiki/Політика_того_ж_походження)". Щоб обійти це обмеження, *обидві сторінки* мають погодитися на обмін даними та містити спеціальний JavaScript-код, який здійснюватиме це. Ми розглянемо цю тему в посібнику.
<<<<<<< HEAD
Знову-таки, це обмеження існує задля безпеки користувача. Сторінка за адресою `http://anysite.com`, яку відкрив користувач, не повинна мати доступ до іншої вкладки браузера з URL-адресою `http://gmail.com` і викрадати звідти інформацію.
- JavaScript може легко спілкуватися мережею з сервером, від якого отримана поточна сторінка. Але здатність скрипту отримувати дані з інших сайтів/доменів обмежена. Такі запити можливі, але потребують спеціальної згоди (вираженої в HTTP-заголовках) від віддаленого сервера. Це також зроблено задля безпеки.
=======
This limitation is, again, for the user's safety. A page from `http://anysite.com` which a user has opened must not be able to access another browser tab with the URL `http://gmail.com`, for example, and steal information from there.
- JavaScript can easily communicate over the net to the server where the current page came from. But its ability to receive data from other sites/domains is severely limited. Though possible, it requires explicit agreement (expressed in HTTP headers) from the remote side. Once again, that's a safety limitation.
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>.
>>>>>>> 20208769e528337949e946f526534d61d38bac47
````
## Аналогія з життя
Ми легко зрозуміємо концепцію "змінної", якщо уявимо її у вигляді "коробки" для даних з унікальною назвою на наклейці.
<<<<<<< HEAD
Наприклад, змінну `message` можна уявити як коробку з написом `"Повідомлення"` зі значенням `"Привіт!"` всередині:
=======
For instance, the variable `message` can be imagined as a box labelled `"message"` with the value `"Hello!"` in it:
>>>>>>> 20208769e528337949e946f526534d61d38bac47

Expand Down
Expand Up
@@ -172,7 +182,11 @@ let userName;
let test123;
```
<<<<<<< HEAD
Для написання імені, яке містить декілька слів, зазвичай використовують "[верблюжий регістр](https://uk.wikipedia.org/wiki/Верблюжий_регістр)" (camelCase). Тобто слова йдуть одне за одним, і кожне слово пишуть із великої букви й без пробілів: `myVeryLongName`. Зауважте, що перше слово пишеться з маленької букви.
=======
When the name contains multiple words, [camelCase](https://en.wikipedia.org/wiki/CamelCase) is commonly used. That is: words go one after another, with each word except the first starting with a capital letter: `myVeryLongName`.
>>>>>>> 20208769e528337949e946f526534d61d38bac47
Що цікаво -- знак долара `'$'` і знак підкреслення `'_'` також можна використовувати в іменах. Це звичайні символи, такі ж, як і букви, без будь-якого особливого значення.
Expand All
@@ -197,15 +211,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:
>>>>>>> 20208769e528337949e946f526534d61d38bac47
```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.
>>>>>>> 20208769e528337949e946f526534d61d38bac47
### Константи в верхньому регістрі
<<<<<<< HEAD
Широко поширена практика використання констант як псевдонімів для значень, які важко запам’ятати і які відомі до початку виконання скрипту.
=======
There is a widespread practice to use constants as aliases for difficult-to-remember values that are known before execution.
>>>>>>> 20208769e528337949e946f526534d61d38bac47
Такі константи пишуться в верхньому регістрі з використанням підкреслень.
Expand All
@@ -289,15 +320,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.
>>>>>>> 20208769e528337949e946f526534d61d38bac47
Наприклад:
```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.
>>>>>>> 20208769e528337949e946f526534d61d38bac47
Інакше кажучи, константи з великими буквами використовуються як псевдоніми для "жорстко закодованих" значень.
Expand All
@@ -307,18 +346,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.
>>>>>>> 20208769e528337949e946f526534d61d38bac47
Будь ласка, приділяйте час на обдумування правильного імені для змінної перед її оголошенням. Робіть так, і будете винагороджені.
Декілька хороших правил:
<<<<<<< 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`.
>>>>>>> 20208769e528337949e946f526534d61d38bac47
Звучить легко? Це дійсно так, проте на практиці створення зрозумілих і коротких імен -- рідкість. Дійте.
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
Ланцюгове присвоєння виконується справа наліво. Спочатку обчислюється найправіший вираз `2 + 2`, а потім результат присвоюється змінним ліворуч: `c`, `b` та `a`. Зрештою всі змінні мають спільне значення.
<<<<<<< HEAD
Знову таки, щоби покращити читабельність коду, краще розділяти подібні конструкції на декілька рядків:
=======
Once again, for the purposes of readability it's better to split such code into a few lines:
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
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 @ 20208769 #809
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
Are you sure you want to change the base?
Uh oh!
There was an error while loading. Please reload this page.
Sync with upstream @ 20208769 #809
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.