diff --git a/1-js/01-getting-started/index.md b/1-js/01-getting-started/index.md index a052c4ca7..169f6884e 100644 --- a/1-js/01-getting-started/index.md +++ b/1-js/01-getting-started/index.md @@ -1,3 +1,3 @@ # Введення -Про мову JavaScript і робоче середовище, для розробки. +Про мову JavaScript і робоче середовище для розробки. diff --git a/1-js/02-first-steps/04-variables/1-hello-variables/solution.md b/1-js/02-first-steps/04-variables/1-hello-variables/solution.md index 9249e1c84..363f7d5d5 100644 --- a/1-js/02-first-steps/04-variables/1-hello-variables/solution.md +++ b/1-js/02-first-steps/04-variables/1-hello-variables/solution.md @@ -1,12 +1,12 @@ -In the code below, each line corresponds to the item in the task list. +В коді нижче, кожен рядок рішення відповідає одному елементу в списку задачі. ```js run -let admin, name; // can declare two variables at once +let admin, name; // можна оголошувати дві змінні через кому -name = "John"; +name = "Іван"; admin = name; -alert( admin ); // "John" +alert( admin ); // "Іван" ``` diff --git a/1-js/02-first-steps/04-variables/1-hello-variables/task.md b/1-js/02-first-steps/04-variables/1-hello-variables/task.md index 84f009e8c..30489e65d 100644 --- a/1-js/02-first-steps/04-variables/1-hello-variables/task.md +++ b/1-js/02-first-steps/04-variables/1-hello-variables/task.md @@ -2,9 +2,9 @@ importance: 2 --- -# Working with variables +# Робота зі змінними -1. Declare two variables: `admin` and `name`. -2. Assign the value `"John"` to `name`. -3. Copy the value from `name` to `admin`. -4. Show the value of `admin` using `alert` (must output "John"). +1. Оголосіть дві змінні: `admin` та `name`. +2. Присвойте значення `"Іван"` змінній `name`. +3. Скопіюйте значення зі змінної `name` в `admin`. +4. Виведіть значення змінної `admin`, використовуючи функцію `alert` (яка повинна показати "Іван"). diff --git a/1-js/02-first-steps/04-variables/2-declare-variables/solution.md b/1-js/02-first-steps/04-variables/2-declare-variables/solution.md index 9ffc3efca..95f3d09b0 100644 --- a/1-js/02-first-steps/04-variables/2-declare-variables/solution.md +++ b/1-js/02-first-steps/04-variables/2-declare-variables/solution.md @@ -1,21 +1,21 @@ -First, the variable for the name of our planet. +1. Змінна для назви нашої планети. -That's simple: +Ось приклад: ```js -let ourPlanetName = "Earth"; +let ourPlanetName = "Земля"; ``` -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. +Зверніть увагу, ми могли використати коротше ім'я `planet`, але тоді буде не зрозуміло, яку планету ми маємо на увазі. Краще описати вміст змінної детальніше. Принаймні до тих пір, поки ім'я змінної неСтанеЗанадтоДовгим. -Second, the name of the current visitor: +2. Ім'я поточного відвідувача: ```js -let currentUserName = "John"; +let currentUserName = "Іван"; ``` -Again, we could shorten that to `userName` if we know for sure that the user is current. +Знову ж таки, ми можемо скоротити ім'я до `userName`, якщо ми точно знатимемо що це поточний відвідувач. -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. +Сучасні редактори і автодоповнювачі дозволяють легко писати довгі імена змінних. Не економте букв. Імена з трьох слів цілком нормальні. -And if your editor does not have proper autocompletion, get [a new one](/code-editors). +Якщо в вашому редакторі немає автодоповнювача, скористайтеся [іншим](/code-editors). diff --git a/1-js/02-first-steps/04-variables/2-declare-variables/task.md b/1-js/02-first-steps/04-variables/2-declare-variables/task.md index f364badf4..a08fad6ab 100644 --- a/1-js/02-first-steps/04-variables/2-declare-variables/task.md +++ b/1-js/02-first-steps/04-variables/2-declare-variables/task.md @@ -2,7 +2,7 @@ importance: 3 --- -# Giving the right name +# Придумайте правильні імена -1. Create a variable with the name of our planet. How would you name such a variable? -2. Create a variable to store the name of a current visitor to a website. How would you name that variable? +1. Створіть змінну із назвою нашої планети. Як би ви назвали таку змінну? +2. Створіть змінну для зберігання імені поточного відвідувача сайту. Як би ви назвали таку змінну? diff --git a/1-js/02-first-steps/04-variables/3-uppercast-constant/solution.md b/1-js/02-first-steps/04-variables/3-uppercast-constant/solution.md index f3a96c692..fe980555c 100644 --- a/1-js/02-first-steps/04-variables/3-uppercast-constant/solution.md +++ b/1-js/02-first-steps/04-variables/3-uppercast-constant/solution.md @@ -1,5 +1,5 @@ -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. +Зазвичай, ми використовуємо великі букви для констант, які "жорстко закодовані" (hardcoded). Іншими словами, коли значення константи відоме до початку виконання скрипта і записується безпосередньо в код. -In this code, `birthday` is exactly like that. So we could use the upper case for it. +В нашому випадку, `birthday` саме така змінна. Тому для неї ми можемо використати великі букви. -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. \ No newline at end of file +На відмінну від попередньої, константа `age` обчислюється під час виконання скрипта. Сьогодні в нас один вік, а через рік вже зовсім інший. Вона є константою, тому що не змінюється під час виконання коду. Але вона "трохи менша" константа, ніж `birthday`, вона обчислюється, тому ми повинні зберегти її в нижньому регістрі. \ No newline at end of file diff --git a/1-js/02-first-steps/04-variables/3-uppercast-constant/task.md b/1-js/02-first-steps/04-variables/3-uppercast-constant/task.md index 5fd18f90a..3e654a638 100644 --- a/1-js/02-first-steps/04-variables/3-uppercast-constant/task.md +++ b/1-js/02-first-steps/04-variables/3-uppercast-constant/task.md @@ -2,9 +2,9 @@ importance: 4 --- -# Uppercase const? +# Використовувати великі чи маленькі букви для імен констант? -Examine the following code: +Переглянемо наступний код: ```js const birthday = '18.04.1982'; @@ -12,13 +12,13 @@ const birthday = '18.04.1982'; const age = someCode(birthday); ``` -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). +В нас є константа `birthday`, а також `age`, яка вираховується за допомогою функції, використовуючи значення із `birthday` (в даному випадку деталі не мають значення, тому код функції не розглядається). -Would it be right to use upper case for `birthday`? For `age`? Or even for both? +Чи можна використовувати великі букви для імені `birthday`? А для `age`? Чи для обох змінних? ```js -const BIRTHDAY = '18.04.1982'; // make uppercase? +const BIRTHDAY = '18.04.1982'; // використовувати великі букви? -const AGE = someCode(BIRTHDAY); // make uppercase? +const AGE = someCode(BIRTHDAY); // а тут? ``` diff --git a/1-js/02-first-steps/04-variables/article.md b/1-js/02-first-steps/04-variables/article.md index 8fe13a970..edba6d86e 100644 --- a/1-js/02-first-steps/04-variables/article.md +++ b/1-js/02-first-steps/04-variables/article.md @@ -1,260 +1,260 @@ -# Variables +# Змінні -Most of the time, a JavaScript application needs to work with information. Here are two examples: -1. An online shop -- the information might include goods being sold and a shopping cart. -2. A chat application -- the information might include users, messages, and much more. +Найчастіше, застосункам на JavaScript потрібно працювати з інформацією. Ось два приклади: +1. Онлайн магазин -- інформацією можуть бути товари, які продаються і вміст кошика. +2. Застосунок для чату -- інформація може включати користувачів, повідомлення та багато іншого. -Variables are used to store this information. +Змінні використовуються для зберігання цієї інформації. -## A variable +## Змінна -A [variable](https://en.wikipedia.org/wiki/Variable_(computer_science)) is a "named storage" for data. We can use variables to store goodies, visitors, and other data. +[Змінна](https://uk.wikipedia.org/wiki/Змінна_(програмування)) це "іменована частинка сховища", в якій зберігаються дані. Ми можемо використовувати змінні, щоб зберігати товари, відвідувачів та інші дані. -To create a variable in JavaScript, use the `let` keyword. +Щоб створити змінну, використовуйте ключове слово `let`. -The statement below creates (in other words: *declares* or *defines*) a variable with the name "message": +Цей рядок нижче створить (іншими словами *оголосить* чи *визначить*) змінну з ім'ям "message": ```js let message; ``` -Now, we can put some data into it by using the assignment operator `=`: +Тепер, ми можемо покласти деякі дані в цю змінну, використовуючи оператор присвоєння `=`: ```js let message; *!* -message = 'Hello'; // store the string +message = 'Привіт'; // збереження рядка */!* ``` -The string is now saved into the memory area associated with the variable. We can access it using the variable name: +Тепер рядок збережено в частину пам'яті, яка зв'язана з цією змінною. Ми можемо отримати доступ до даних, використовуючи ім'я змінної: ```js run let message; -message = 'Hello!'; +message = 'Привіт!'; *!* -alert(message); // shows the variable content +alert(message); // показує вміст змінної */!* ``` -To be concise, we can combine the variable declaration and assignment into a single line: +Щоб писати менше коду, ми можемо суміщати оголошення змінної та її присвоєння в одному рядку: ```js run -let message = 'Hello!'; // define the variable and assign the value +let message = 'Привіт!'; // оголошення і присвоєння значення -alert(message); // Hello! +alert(message); // Привіт! ``` -We can also declare multiple variables in one line: +Ми також можемо оголосити декілька змінних в одному рядку: ```js no-beautify -let user = 'John', age = 25, message = 'Hello'; +let user = 'Іван', age = 25, message = 'Привіт'; ``` -That might seem shorter, but we don't recommend it. For the sake of better readability, please use a single line per variable. +Таке оголошення може виглядати коротшим, проте ми не рекомендуємо так писати. Заради кращої читабельності, будь ласка, оголошуйте змінні з нового рядка. -The multiline variant is a bit longer, but easier to read: +Багаторядковий спосіб трохи довший, проте його легше читати: ```js -let user = 'John'; +let user = 'Іван'; let age = 25; -let message = 'Hello'; +let message = 'Привіт'; ``` -Some people also define multiple variables in this multiline style: +Деякі люди також оголошують змінні в такому багаторядковому стилі: ```js no-beautify -let user = 'John', +let user = 'Іван', age = 25, - message = 'Hello'; + message = 'Привіт'; ``` -...Or even in the "comma-first" style: +...або навіть в стилі "кома спочатку": ```js no-beautify -let user = 'John' +let user = 'Іван' , age = 25 - , message = 'Hello'; + , message = 'Привіт'; ``` -Technically, all these variants do the same thing. So, it's a matter of personal taste and aesthetics. +Технічно, всі ці способи роблять одне і теж. Тому, це питання особистого смаку та естетики. -````smart header="`var` instead of `let`" -In older scripts, you may also find another keyword: `var` instead of `let`: +````smart header="`var` замість `let`" +В старих скриптах, ви можете знайти інше ключове слово: `var` замість `let`: ```js -*!*var*/!* message = 'Hello'; +*!*var*/!* message = 'Привіт'; ``` -The `var` keyword is *almost* the same as `let`. It also declares a variable, but in a slightly different, "old-school" way. +Ключове слово `var` *майже* таке як `let`. Воно теж оголошує змінну, але дещо іншим, "застарілим" способом. -There are subtle differences between `let` and `var`, but they do not matter for us yet. We'll cover them in detail in the chapter . +Існують деякі відмінності між `let` і `var`, але вони поки що не мають для нас значення. Ми дізнаємося більше про їхню різницю в розділі . ```` -## A real-life analogy +## Аналогія з життя -We can easily grasp the concept of a "variable" if we imagine it as a "box" for data, with a uniquely-named sticker on it. +Ми легко зрозуміємо концепцію "змінної", якщо уявимо її у вигляді "коробки" для даних з унікальною наклейкою з назвою на ній. -For instance, the variable `message` can be imagined as a box labeled `"message"` with the value `"Hello!"` in it: +Наприклад, змінну `message` можна уявити як коробку з підписом `"Повідомлення"` із значенням `"Привіт!"` всередині: ![](variable.png) -We can put any value in the box. +Ми можемо покласти будь-яке значення в цю коробку. -We can also change it as many times as we want: +Ми також можемо змінювати її скільки разів, скільки захочемо: ```js run let message; -message = 'Hello!'; +message = 'Привіт!'; -message = 'World!'; // value changed +message = 'Світ!'; // значення змінено alert(message); ``` -When the value is changed, the old data is removed from the variable: +Коли значення змінюється, старі дані видаляються зі змінної: ![](variable-change.png) -We can also declare two variables and copy data from one into the other. +ми також можемо оголосити дві змінні і скопіювати дані з однієї в іншу. ```js run -let hello = 'Hello world!'; +let hello = 'Привіт світ!'; let message; *!* -// copy 'Hello world' from hello into message +// копіюємо 'Привіт світ' з hello в message message = hello; */!* -// now two variables hold the same data -alert(hello); // Hello world! -alert(message); // Hello world! +// тепер дві змінні мають одинакові дані +alert(hello); // Привіт світ! +alert(message); // Привіт світ! ``` -```smart header="Functional languages" -It's interesting to note that [functional](https://en.wikipedia.org/wiki/Functional_programming) programming languages, like [Scala](http://www.scala-lang.org/) or [Erlang](http://www.erlang.org/), forbid changing variable values. +```smart header="Функціональне програмування" +Цікаво відзначити, що [функціональні](https://uk.wikipedia.org/wiki/Функційне_програмування) мови програмування, такі як [Scala](http://www.scala-lang.org/) або [Erlang](http://www.erlang.org/), забороняють змінювати значення змінних. -In such languages, once the value is stored "in the box", it's there forever. If we need to store something else, the language forces us to create a new box (declare a new variable). We can't reuse the old one. +В таких мовах, збережені в "коробку" значення залишаються там назавджи. Якщо нам потрібно зберегти щось інше, мова змусить нас створити нову коробку (оголосити нову змінну). Ми не можемо використати стару змінну. -Though it may seem a little odd at first sight, these languages are quite capable of serious development. More than that, there are areas like parallel computations where this limitation confers certain benefits. Studying such a language (even if you're not planning to use it soon) is recommended to broaden the mind. +Хоча на перший погляд це може здатися дивним, проте ці мови цілком підходять для серйозної розробки. Більше того, є така область, як паралельні обчислення, де це обмеження дає певні переваги. Вивчення такої мови (навіть якщо ви не плануєте користуватися нею найближчим часом) рекомендується для розширення кругозору. ``` -## Variable naming [#variable-naming] +## Іменування змінних [#variable-naming] -There are two limitations on variable names in JavaScript: +В JavaScript є два обмеження, які стосуються імен змінних: -1. The name must contain only letters, digits, or the symbols `$` and `_`. -2. The first character must not be a digit. +1. Ім'я повинне містити лише букви, цифри або символи `$` і `_`. +2. Перша буква не повинна бути числом. -Examples of valid names: +Ось приклади допустимих імен: ```js let userName; let test123; ``` -When the name contains multiple words, [camelCase](https://en.wikipedia.org/wiki/CamelCase) is commonly used. That is: words go one after another, each word except first starting with a capital letter: `myVeryLongName`. +Для написання ім'я, яке містить декілька слів, зазвичай використовують "[верблюжий регістр](https://uk.wikipedia.org/wiki/Верблюжий_регістр)" (camelCase). Тобто, слова йдуть одне за одним, де кожне слово пишуть з великої букви і без пробілів: `myVeryLongName`. Зауважте, що перше слово пишеться з маленької букви. -What's interesting -- the dollar sign `'$'` and the underscore `'_'` can also be used in names. They are regular symbols, just like letters, without any special meaning. +Що цікаво -- знак долара `'$'` і знак підкреслення `'_'`, також можна використовувати в іменах. Це звичайні символи, такі ж як і букви, без будь-якого особливого значення. -These names are valid: +Ці імена також допустимі: ```js run untrusted -let $ = 1; // declared a variable with the name "$" -let _ = 2; // and now a variable with the name "_" +let $ = 1; // оголошено змінну з ім'ям "$" +let _ = 2; // а тепер змінна з ім'ям "_" alert($ + _); // 3 ``` -Examples of incorrect variable names: +Приклади недопустимих імен змінних: ```js no-beautify -let 1a; // cannot start with a digit +let 1a; // не може починатися з цифри -let my-name; // hyphens '-' aren't allowed in the name +let my-name; // дефіс '-' недопустимий в імені ``` -```smart header="Case matters" -Variables named `apple` and `AppLE` are two different variables. +```smart header="Регістр має значення" +Змінні з іменами `apple` і `AppLE` -- це дві різні змінні. ``` -````smart header="Non-English letters are allowed, but not recommended" -It is possible to use any language, including cyrillic letters or even hieroglyphs, like this: +````smart header="Не-латинські букви дозволені, але не рекомендуються" +Можна використовувати будь-яку мову, включно з кирилицею або навіть ієрогліфи, наприклад: ```js -let имя = '...'; +let імя = '...'; let 我 = '...'; ``` -Technically, there is no error here, such names are allowed, but there is an international tradition 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 some time. +Технічно тут немає помилки, такі імена дозволені, проте існує міжнародна традиція використовувати англійську мову в іменах змінних. Слова теж бажано писати англійські (`yaLyublyuUkrainu` => `iLoveUkraine`). Навіть якщо ми пишемо маленький скрипт, в нього може бути тривале життя попереду. Людям з інших країн, можливо, доведеться прочитати його не один раз. ```` -````warn header="Reserved names" -There is a [list of reserved words](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords), which cannot be used as variable names because they are used by the language itself. +````warn header="Зарезервовані слова" +Існує [список зарезервованих слів](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords), які не можна використовувати в якості імен змінних, тому що ці слова використовує сама мова. -For example: `let`, `class`, `return`, and `function` are reserved. +Наприклад: `let`, `class`, `return`, і `function` зарезервовані. -The code below gives a syntax error: +Такий код видатиме синтаксичну помилку: ```js run no-beautify -let let = 5; // can't name a variable "let", error! -let return = 5; // also can't name it "return", error! +let let = 5; // неможна назвати змінну "let", помилка! +let return = 5; // також неможна називати змінну "return", помилка! ``` ```` -````warn header="An assignment without `use strict`" +````warn header="Створення змінної без використання `use strict`" -Normally, we need to define a variable before using it. But in the old times, it was technically possible to create a variable by a mere assignment of the value without using `let`. This still works now if we don't put `use strict` in our scripts to maintain compatibility with old scripts. +Зазвичай нам потрібно оголосити змінну перед її використанням. Але в старі часи можна було технічно створити змінну простим присвоєнням значення, без використання `let`. Це все ще працює, якщо не вмикати `строгий режим` в наших скриптах для підтримки сумісності зі старими сценаріями. ```js run no-strict -// note: no "use strict" in this example +// "use strict" в цьому прикладі не використовується -num = 5; // the variable "num" is created if it didn't exist +num = 5; // якщо змінна "num" не існувала, її буде створено alert(num); // 5 ``` -This is a bad practice and would cause an error in strict mode: +Це погана практика, яка призведе до помилки в строгому режимі: ```js "use strict"; *!* -num = 5; // error: num is not defined +num = 5; // помилка: num не оголошено */!* ``` ```` -## Constants +## Константи -To declare a constant (unchanging) variable, use `const` instead of `let`: +Щоб оголосити константу (незмінювану) змінну, використовуйте ключове слово `const` замість `let`: ```js const myBirthday = '18.04.1982'; ``` -Variables declared using `const` are called "constants". They cannot be changed. An attempt to do so would cause an error: +Змінні, оголошені за допомогою `const`, називаються "константами". Їх неможна змінити. Спроба це зробити призведе до помилки: ```js run const myBirthday = '18.04.1982'; -myBirthday = '01.01.2001'; // error, can't reassign the constant! +myBirthday = '01.01.2001'; // помилка, не можна перевизначати константу! ``` -When a programmer is sure that a variable will never change, they can declare it with `const` to guarantee and clearly communicate that fact to everyone. +Коли програміст впевнений, що змінна ніколи не буде змінюватися, він може оголосити її через `const`, що буде гарантовано зрозуміло для кожного. -### Uppercase constants +### Константи в верхньому регістрі -There is a widespread practice to use constants as aliases for difficult-to-remember values that are known prior to execution. +Широко поширена практика використання констант в якості псевдонімів для значень, які важко запам'ятати і які відомі до початку виконання скрипта. -Such constants are named using capital letters and underscores. +Такі константи пишуться в верхньому регістрі з використанням підкреслень. -Like this: +Ось так: ```js run const COLOR_RED = "#F00"; @@ -262,69 +262,69 @@ const COLOR_GREEN = "#0F0"; const COLOR_BLUE = "#00F"; const COLOR_ORANGE = "#FF7F00"; -// ...when we need to pick a color +// ...коли потрібно вибрати колір let color = COLOR_ORANGE; alert(color); // #FF7F00 ``` -Benefits: +Переваги: -- `COLOR_ORANGE` is much easier to remember than `"#FF7F00"`. -- It is much easier to mistype `"#FF7F00"` than `COLOR_ORANGE`. -- When reading the code, `COLOR_ORANGE` is much more meaningful than `#FF7F00`. +- `COLOR_ORANGE` набагато легше запам'ятати, ніж `"#FF7F00"`. +- Набагато легше допустити помилку в `"#FF7F00"`, ніж при введені `COLOR_ORANGE`. +- Під час читання коду, `COLOR_ORANGE` набагато зрозуміліше, ніж `#FF7F00`. -When should we use capitals for a constant and when should we name it normally? Let's make that clear. +Коли ми повинні використовувати для констант великі букви, а коли звичайні? Давайте це вияснимо. -Being a "constant" just means that a variable's value never changes. But there are constants that are known prior to execution (like a hexadecimal value for red) and there are constants that are *calculated* in run-time, during the execution, but do not change after their initial assignment. +Назва "константа" лише означає, що змінна ніколи не зміниться. Але є константи, які відомі нам до виконання скрипта (наприклад, шістнадцяткове значення для червоного кольору), а є константи, які *вираховуються* в процесі виконання скрипта, але не змінюються після їхнього початкового присвоєння. -For instance: +Наприклад: ```js -const pageLoadTime = /* time taken by a webpage to load */; +const pageLoadTime = /* час, потрачений на завантаження веб-сторінки */; ``` -The value of `pageLoadTime` is not known prior to the page load, so it's named normally. But it's still a constant because it doesn't change after assignment. +Значення `pageLoadTime` невідоме до завантаження сторінки, тому її ім'я записано звичайними, а не великими буквами. Але це все ще константа, тому що вона не змінює значення після призначення. -In other words, capital-named constants are only used as aliases for "hard-coded" values. +Іншими словами, константи з великими буквами, використовуються як псевдоніми для "жорстко закодованих" значень. -## Name things right +## Придумуйте правильні імена -Talking about variables, there's one more extremely important thing. +В розмові про змінні необхідно згадати, що є ще одна дуже важлива річ -- правильні імена змінних. -Please name your variables sensibly. Take time to think about this. +Такі імена повинні мати ясний і зрозумілий сенс, говорити про те, які дані в них зберігаються. -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. +Іменування змінних -- одна з найважливіших і найскладніших навичок в програмуванні. Швидкий перегляд змінних може показати, чи код був написаний новачком чи досвідченим розробником. -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. +В реальному проекті, більшість часу тратиться на змінення і розширення існуючої кодової бази, а не на написання чогось цілком нового. Коли ми повертаємося до якогось коду, після виконання чогось іншого впродовж тривалого часу, набагато легше знайти інформацію, яку добре позначено. Або, іншими словами, коли змінні мають хороші імена. -Please spend time thinking about the right name for a variable before declaring it. Doing so will repay you handsomely. +Будь ласка, приділіть час на обдумування правильного імені для змінної перед її оголошенням. Робіть так, і будете винагороджені. -Some good-to-follow rules are: +Декілька хороших правил: -- Use human-readable names like `userName` or `shoppingCart`. -- Stay away from abbreviations or short names like `a`, `b`, `c`, unless you really 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 own mind. If a site visitor is called a "user" then we should name related variables `currentUser` or `newUser` instead of `currentVisitor` or `newManInTown`. +- Використовуйте імена, які легко прочитати, наприклад, `userName` або `shoppingCart`. +- Уникайте використання абревіатур або коротких імен, таких як `a`, `b`, `c`, за винятками тих випадків, коли ви точно знаєте, що так потрібно. +- Робіть імена максимально описовими і лаконічними. Наприклад, такі імена погані: `data` і `value`. Такі імена нічого не говорять. Їх можна використовувати лише тоді, коли з контексту очевидно, на які дані або значення посилається змінна. +- Узгодьте з вашою командою, які терміни будуть використовуватися. Якщо відвідувач сайту називається "user", тоді ми повинні давати відповідні імена іншим пов'язаним змінним: `currentUser` або `newUser`, замість `currentVisitor` або `newManInTown`. -Sounds simple? Indeed it is, but creating descriptive and concise variable names in practice is not. Go for it. +Звучить легко? Це дійсно так, проте на практиці створення зрозумілих і коротких імен -- рідкість. Дійте. -```smart header="Reuse or create?" -And the last note. There are some lazy programmers who, instead of declaring new variables, tend to reuse existing ones. +```smart header="Перевикористовувати чи створювати?" +І остання примітка. Є ліниві програмісти, які замість оголошення нових змінних, повторно використовують існуючі. -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. +В результаті їхні змінні схожі на коробки, в які люди кидають різні речі, не змінюючи на них наклейки. Що зараз знаходиться всередині коробки? Хто знає? Нам необхідно підійти поближче і перевірити. -Such programmers save a little bit on variable declaration but lose ten times more on debugging. +Такі програмісти економлять трішки часу на оголошенні змінних, але втрачають вдесятеро більше при відлагодженні. -An extra variable is good, not evil. +Додаткова змінна -- це добро, а не зло. -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. +Сучасні JavaScript мініфікатори і браузери оптимізують код досить добре, тому додаткові змінні не погіршують продуктивність. Використання різних змінних для різних значень може навіть допомогти рушію оптимізувати ваш код. ``` -## Summary +## Підсумки -We can declare variables to store data by using the `var`, `let`, or `const` keywords. +Ми можемо оголосити змінні для збереження даних за допомогою ключових слів `var`, `let`, чи `const`. -- `let` -- is a modern variable declaration. The code must be in strict mode to use `let` in Chrome (V8). -- `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 , just in case you need them. -- `const` -- is like `let`, but the value of the variable can't be changed. +- `let` -- це сучасний спосіб оголошення. При використанні `let` в Chrome (V8) повинен бути включений строгий режим. +- `var` -- це застарілий спосіб оголошення змінної. Зазвичай ми не використовуємо його взагалі, але ми розглянемо тонкі відмінності від `let` в розділі , на випадок, якщо це все-таки знадобиться. +- `const` -- це як `let`, але значення змінної не може змінюватися. -Variables should be named in a way that allows us to easily understand what's inside them. +Змінні повинні називатися таким чином, щоб ми могли легко зрозуміти, що в середині них. diff --git a/1-js/02-first-steps/04-variables/variable-change.png b/1-js/02-first-steps/04-variables/variable-change.png index 9135e930a..e8b977a32 100644 Binary files a/1-js/02-first-steps/04-variables/variable-change.png and b/1-js/02-first-steps/04-variables/variable-change.png differ diff --git a/1-js/02-first-steps/04-variables/variable-change@2x.png b/1-js/02-first-steps/04-variables/variable-change@2x.png index c9569e638..54329475f 100644 Binary files a/1-js/02-first-steps/04-variables/variable-change@2x.png and b/1-js/02-first-steps/04-variables/variable-change@2x.png differ diff --git a/1-js/02-first-steps/04-variables/variable.png b/1-js/02-first-steps/04-variables/variable.png index 6d2482556..584b7eb1e 100644 Binary files a/1-js/02-first-steps/04-variables/variable.png and b/1-js/02-first-steps/04-variables/variable.png differ diff --git a/1-js/02-first-steps/04-variables/variable@2x.png b/1-js/02-first-steps/04-variables/variable@2x.png index 845f34408..b4ed57723 100644 Binary files a/1-js/02-first-steps/04-variables/variable@2x.png and b/1-js/02-first-steps/04-variables/variable@2x.png differ diff --git a/README.md b/README.md index 767c9aacf..373eef31f 100755 --- a/README.md +++ b/README.md @@ -114,6 +114,8 @@ document.querySelector('.привіт').innerHTML = text; [JavaScript](https://uk.wikipedia.org/wiki/JavaScript) це прототипна мова програмування. ``` +Якщо посилання на українську версію містить кодовані букви (`https://uk.wikipedia.org/wiki/V8_(%D1%80%D1%83%D1%88%D1%96%D0%B9_JavaScript`), їх слід замінити на українські букви (`https://uk.wikipedia.org/wiki/V8_(рушій_JavaScript)`). + Для статтей на MDN, які частково перекладені на українську мову, також можна вказати посилання на українську версію. Якщо така стаття немає перекладеної версії, залишайте посилання "як є".