diff --git a/1-js/02-first-steps/12-while-for/1-loop-last-value/solution.md b/1-js/02-first-steps/12-while-for/1-loop-last-value/solution.md index 43ee4aad3d..bbfc6d9ec6 100644 --- a/1-js/02-first-steps/12-while-for/1-loop-last-value/solution.md +++ b/1-js/02-first-steps/12-while-for/1-loop-last-value/solution.md @@ -1,4 +1,4 @@ -The answer: `1`. +Ответ: `1`. ```js run let i = 3; @@ -8,18 +8,18 @@ while (i) { } ``` -Every loop iteration decreases `i` by `1`. The check `while(i)` stops the loop when `i = 0`. +Каждое выполнение цикла уменьшает `i`. Проверка `while(i)` даст сигнал «стоп» при `i = 0`. -Hence, the steps of the loop form the following sequence ("loop unrolled"): +Соответственно, шаги цикла со следующей последовательностью ("развёрнутый цикл"): ```js let i = 3; -alert(i--); // shows 3, decreases i to 2 +alert(i--); // выведет 3, затем уменьшит i до 2 -alert(i--) // shows 2, decreases i to 1 +alert(i--) // выведет 2, затем уменьшит i до 1 -alert(i--) // shows 1, decreases i to 0 +alert(i--) // выведет 1, затем уменьшит i до 0 -// done, while(i) check stops the loop +// все, проверка while(i) не даст выполняться циклу дальше ``` diff --git a/1-js/02-first-steps/12-while-for/1-loop-last-value/task.md b/1-js/02-first-steps/12-while-for/1-loop-last-value/task.md index 3b847dfa2d..2333335eb4 100644 --- a/1-js/02-first-steps/12-while-for/1-loop-last-value/task.md +++ b/1-js/02-first-steps/12-while-for/1-loop-last-value/task.md @@ -1,10 +1,10 @@ -importance: 3 +важность: 3 --- -# Last loop value +# Последнее значение цикла -What is the last value alerted by this code? Why? +Какое последнее значение выведет этот код? Почему? ```js let i = 3; diff --git a/1-js/02-first-steps/12-while-for/2-which-value-while/solution.md b/1-js/02-first-steps/12-while-for/2-which-value-while/solution.md index 4953598769..95f2944956 100644 --- a/1-js/02-first-steps/12-while-for/2-which-value-while/solution.md +++ b/1-js/02-first-steps/12-while-for/2-which-value-while/solution.md @@ -1,30 +1,31 @@ -The task demonstrates how postfix/prefix forms can lead to different results when used in comparisons. +Задача демонстрирует, как постфиксные/префиксные варианты могут повлиять на результат, когда используются в сравнениях. -1. **From 1 to 4** +1. **От 1 до 4** ```js run let i = 0; while (++i < 5) alert( i ); ``` - The first value is `i = 1`, because `++i` first increments `i` and then returns the new value. So the first comparison is `1 < 5` and the `alert` shows `1`. + Первое значение: `i = 1`, так как операция `++i` сначала увеличит `i`, а потом уже произойдёт сравнение и выполнение `alert`. - Then follow `2, 3, 4…` -- the values show up one after another. The comparison always uses the incremented value, because `++` is before the variable. + Далее `2, 3, 4..` Значения выводятся одно за другим. Для каждого значения сначала происходит увеличение, а потом – сравнение, так как `++` стоит перед переменной. - Finally, `i = 4` is incremented to `5`, the comparison `while(5 < 5)` fails, and the loop stops. So `5` is not shown. -2. **From 1 to 5** + При `i = 4` произойдет увеличение `i` до `5`, а потом сравнение `while (5 < 5)` – это неверно. Поэтому на этом цикл остановится, и значение `5` выведено не будет. + +2. **От 1 до 5** ```js run let i = 0; while (i++ < 5) alert( i ); ``` - The first value is again `i = 1`. The postfix form of `i++` increments `i` and then returns the *old* value, so the comparison `i++ < 5` will use `i = 0` (contrary to `++i < 5`). + Первое значение: `i = 1`. Остановимся на нём подробнее. Оператор `i++` увеличивает `i`, возвращая старое значение, так что в сравнении `i++ < 5` будет участвовать старое `i = 0`. - But the `alert` call is separate. It's another statement which executes after the increment and the comparison. So it gets the current `i = 1`. + Но последующий вызов alert уже не относится к этому выражению, так что получит новый `i = 1`. - Then follow `2, 3, 4…` + Далее `2, 3, 4..` Для каждого значения сначала происходит сравнение, а потом – увеличение, и затем срабатывание `alert`. - Let's stop on `i = 4`. The prefix form `++i` would increment it and use `5` in the comparison. But here we have the postfix form `i++`. So it increments `i` to `5`, but returns the old value. Hence the comparison is actually `while(4 < 5)` -- true, and the control goes on to `alert`. + Окончание цикла: при `i = 4` произойдет сравнение `while (4 < 5)` – верно, после этого сработает `i++`, увеличив `i` до `5`, так что значение `5` будет выведено. Оно станет последним. - The value `i = 5` is the last one, because on the next step `while(5 < 5)` is false. + Значение `i = 5` последнее, потому что на следующем шаге `while (5 < 5)` ложно. diff --git a/1-js/02-first-steps/12-while-for/2-which-value-while/task.md b/1-js/02-first-steps/12-while-for/2-which-value-while/task.md index 298213237b..2da07466ba 100644 --- a/1-js/02-first-steps/12-while-for/2-which-value-while/task.md +++ b/1-js/02-first-steps/12-while-for/2-which-value-while/task.md @@ -1,20 +1,20 @@ -importance: 4 +важность: 4 --- -# Which values does the while loop show? +# Какие значения i выведет цикл while? -For every loop iteration, write down which value it outputs and then compare it with the solution. +Для каждого цикла запишите, какие значения он выведет. Потом сравните с ответом. -Both loops `alert` the same values, or not? +Оба цикла выводят `alert` с одинаковыми значениями или нет? -1. The prefix form `++i`: +1. Префиксный вариант `++i`: ```js let i = 0; while (++i < 5) alert( i ); ``` -2. The postfix form `i++` +2. Постфиксный вариант `i++` ```js let i = 0; diff --git a/1-js/02-first-steps/12-while-for/3-which-value-for/solution.md b/1-js/02-first-steps/12-while-for/3-which-value-for/solution.md index e2e28e75b4..a5a77699f2 100644 --- a/1-js/02-first-steps/12-while-for/3-which-value-for/solution.md +++ b/1-js/02-first-steps/12-while-for/3-which-value-for/solution.md @@ -1,4 +1,4 @@ -**The answer: from `0` to `4` in both cases.** +**Ответ: от `0` до `4` в обоих случаях.** ```js run for (let i = 0; i < 5; ++i) alert( i ); @@ -6,12 +6,10 @@ for (let i = 0; i < 5; ++i) alert( i ); for (let i = 0; i < 5; i++) alert( i ); ``` -That can be easily deducted from the algorithm of `for`: +Такой результат обусловлен алгоритмом работы `for`: -1. Execute once `i = 0` before everything (begin). -2. Check the condition `i < 5` -3. If `true` -- execute the loop body `alert(i)`, and then `i++` +1. Выполнить единожды присваивание `i = 0` перед чем-либо (начало). +2. Проверить условие `i < 5` +3. Если `true` -- выполнить тело цикла `alert(i)`, и затем `i++` -The increment `i++` is separated from the condition check (2). That's just another statement. - -The value returned by the increment is not used here, so there's no difference between `i++` and `++i`. +Увеличение `i++` выполняется отдельно от проверки условия `(2)`, значение `i` при этом не используется, поэтому нет никакой разницы между `i++` и `++i`. diff --git a/1-js/02-first-steps/12-while-for/3-which-value-for/task.md b/1-js/02-first-steps/12-while-for/3-which-value-for/task.md index bfefa63f53..ebf9a102fc 100644 --- a/1-js/02-first-steps/12-while-for/3-which-value-for/task.md +++ b/1-js/02-first-steps/12-while-for/3-which-value-for/task.md @@ -1,19 +1,19 @@ -importance: 4 +важность: 4 --- -# Which values get shown by the "for" loop? +# Какие значения i выведет цикл for? -For each loop write down which values it is going to show. Then compare with the answer. +Для каждого цикла запишите, какие значения он выведет. Потом сравните с ответом. -Both loops `alert` same values or not? +Оба цикла выведут `alert` с одинаковыми значениями или нет? -1. The postfix form: +1. Постфиксная форма: ```js for (let i = 0; i < 5; i++) alert( i ); ``` -2. The prefix form: +2. Префиксная форма: ```js for (let i = 0; i < 5; ++i) alert( i ); diff --git a/1-js/02-first-steps/12-while-for/4-for-even/solution.md b/1-js/02-first-steps/12-while-for/4-for-even/solution.md index e8e66bb47c..337da58e02 100644 --- a/1-js/02-first-steps/12-while-for/4-for-even/solution.md +++ b/1-js/02-first-steps/12-while-for/4-for-even/solution.md @@ -8,4 +8,4 @@ for (let i = 2; i <= 10; i++) { } ``` -We use the "modulo" operator `%` to get the remainder and check for the evenness here. +Чётность проверяется по остатку при делении на `2`, используя оператор «деление с остатком» `%`: `i % 2`. diff --git a/1-js/02-first-steps/12-while-for/4-for-even/task.md b/1-js/02-first-steps/12-while-for/4-for-even/task.md index ff34e7e40f..fc19beaf39 100644 --- a/1-js/02-first-steps/12-while-for/4-for-even/task.md +++ b/1-js/02-first-steps/12-while-for/4-for-even/task.md @@ -1,9 +1,9 @@ -importance: 5 +важность: 5 --- -# Output even numbers in the loop +# Выведите чётные числа -Use the `for` loop to output even numbers from `2` to `10`. +При помощи цикла `for` выведите чётные числа от `2` до `10`. [demo] diff --git a/1-js/02-first-steps/12-while-for/5-replace-for-while/task.md b/1-js/02-first-steps/12-while-for/5-replace-for-while/task.md index 0c69d9c2d5..232fd1637d 100644 --- a/1-js/02-first-steps/12-while-for/5-replace-for-while/task.md +++ b/1-js/02-first-steps/12-while-for/5-replace-for-while/task.md @@ -1,14 +1,13 @@ -importance: 5 +важность: 5 --- -# Replace "for" with "while" +# Замените for на while -Rewrite the code changing the `for` loop to `while` without altering its behavior (the output should stay same). +Перепишите код, заменив цикл `for` на `while`, без изменения поведения цикла. ```js run for (let i = 0; i < 3; i++) { alert( `number ${i}!` ); } ``` - diff --git a/1-js/02-first-steps/12-while-for/6-repeat-until-correct/solution.md b/1-js/02-first-steps/12-while-for/6-repeat-until-correct/solution.md index 2e04a78c43..65e8f35318 100644 --- a/1-js/02-first-steps/12-while-for/6-repeat-until-correct/solution.md +++ b/1-js/02-first-steps/12-while-for/6-repeat-until-correct/solution.md @@ -7,9 +7,9 @@ do { } while (num <= 100 && num); ``` -The loop `do..while` repeats while both checks are truthy: +Цикл `do..while` повторяется, пока верны две проверки: -1. The check for `num <= 100` -- that is, the entered value is still not greater than `100`. -2. The check `&& num` is false when `num` is `null` or a empty string. Then the `while` loop stops too. +1. Проверка `num <= 100` -- то есть, введённое число всё еще меньше `100`. +2. Проверка `&& num` вычисляется в `false`, когда `num` имеет значение `null` или пустая строка `''`. В этом случае цикл `while` тоже нужно прекратить. -P.S. If `num` is `null` then `num <= 100` is `true`, so without the 2nd check the loop wouldn't stop if the user clicks CANCEL. Both checks are required. +Кстати, сравнение `num <= 100` при вводе `null` даст `true`, так что вторая проверка необходима. diff --git a/1-js/02-first-steps/12-while-for/6-repeat-until-correct/task.md b/1-js/02-first-steps/12-while-for/6-repeat-until-correct/task.md index 0788ee76e4..85171a1a26 100644 --- a/1-js/02-first-steps/12-while-for/6-repeat-until-correct/task.md +++ b/1-js/02-first-steps/12-while-for/6-repeat-until-correct/task.md @@ -1,13 +1,13 @@ -importance: 5 +важность: 5 --- -# Repeat until the input is correct +# Повторять цикл, пока ввод неверен -Write a loop which prompts for a number greater than `100`. If the visitor enters another number -- ask them to input again. +Напишите цикл, который предлагает `prompt` ввести число, большее `100`. Если посетитель ввёл другое число – попросить ввести ещё раз, и так далее. -The loop must ask for a number until either the visitor enters a number greater than `100` or cancels the input/enters an empty line. +Цикл должен спрашивать число пока либо посетитель не введёт число, большее `100`, либо не нажмёт кнопку Cancel (ESC). -Here we can assume that the visitor only inputs numbers. There's no need to implement a special handling for a non-numeric input in this task. +Предполагается, что посетитель вводит только числа. Предусматривать обработку нечисловых строк в этой задаче необязательно. [demo] diff --git a/1-js/02-first-steps/12-while-for/7-list-primes/solution.md b/1-js/02-first-steps/12-while-for/7-list-primes/solution.md index 9ff0663d71..6a04e61202 100644 --- a/1-js/02-first-steps/12-while-for/7-list-primes/solution.md +++ b/1-js/02-first-steps/12-while-for/7-list-primes/solution.md @@ -1,29 +1,29 @@ -There are many algorithms for this task. +Существует множество алгоритмов решения этой задачи. -Let's use a nested loop: +Давайте воспользуемся вложенными циклами: ```js -For each i in the interval { - check if i has a divisor from 1..i - if yes => the value is not a prime - if no => the value is a prime, show it +Для всех i от 1 до 10 { + проверить, делится ли число i на какое - либо из чисел до него + если делится, то это i не подходит, берем следующее + если не делится, то i - простое число } ``` -The code using a label: +Решение с использованием метки: ```js run let n = 10; nextPrime: -for (let i = 2; i <= n; i++) { // for each i... +for (let i = 2; i <= n; i++) { // Для всех i... - for (let j = 2; j < i; j++) { // look for a divisor.. - if (i % j == 0) continue nextPrime; // not a prime, go next i + for (let j = 2; j < i; j++) { // проверить, делится ли число.. + if (i % j == 0) continue nextPrime; // не подходит, берем следующее } - alert( i ); // a prime + alert( i ); // простое число } ``` -There's a lot of space to opimize it. For instance, we could look for the divisors from `2` to square root of `i`. But anyway, if we want to be really efficient for large intervals, we need to change the approach and rely on advanced maths and complex algorithms like [Quadratic sieve](https://en.wikipedia.org/wiki/Quadratic_sieve), [General number field sieve](https://en.wikipedia.org/wiki/General_number_field_sieve) etc. +Конечно же, его можно оптимизировать с точки зрения производительности. Например, проверять все `j` не от `2` до `i`, а от `2` до квадратного корня из `i`. А для очень больших чисел – существуют более эффективные специализированные алгоритмы проверки простоты числа, например [квадратичное решето](https://ru.wikipedia.org/wiki/%D0%9C%D0%B5%D1%82%D0%BE%D0%B4_%D0%BA%D0%B2%D0%B0%D0%B4%D1%80%D0%B0%D1%82%D0%B8%D1%87%D0%BD%D0%BE%D0%B3%D0%BE_%D1%80%D0%B5%D1%88%D0%B5%D1%82%D0%B0) и [решето числового поля](https://ru.wikipedia.org/wiki/%D0%9E%D0%B1%D1%89%D0%B8%D0%B9_%D0%BC%D0%B5%D1%82%D0%BE%D0%B4_%D1%80%D0%B5%D1%88%D0%B5%D1%82%D0%B0_%D1%87%D0%B8%D1%81%D0%BB%D0%BE%D0%B2%D0%BE%D0%B3%D0%BE_%D0%BF%D0%BE%D0%BB%D1%8F). diff --git a/1-js/02-first-steps/12-while-for/7-list-primes/task.md b/1-js/02-first-steps/12-while-for/7-list-primes/task.md index 6344b9f6f8..d4d0a5c18d 100644 --- a/1-js/02-first-steps/12-while-for/7-list-primes/task.md +++ b/1-js/02-first-steps/12-while-for/7-list-primes/task.md @@ -1,17 +1,17 @@ -importance: 3 +важность: 3 --- -# Output prime numbers +# Вывести простые числа -An integer number greater than `1` is called a [prime](https://en.wikipedia.org/wiki/Prime_number) if it cannot be divided without a remainder by anything except `1` and itself. +Натуральное число, большее `1`, называется [простым](https://ru.wikipedia.org/wiki/%D0%9F%D1%80%D0%BE%D1%81%D1%82%D0%BE%D0%B5_%D1%87%D0%B8%D1%81%D0%BB%D0%BE), если оно ни на что не делится, кроме себя и `1`. -In other words, `n > 1` is a prime if it can't be evenly divided by anything except `1` and `n`. +Другими словами, `n > 1` – простое, если при делении на любое число от `2` до `n - 1` есть остаток. -For example, `5` is a prime, because it cannot be divided without a remainder by `2`, `3` and `4`. +Например, `5` это простое числое, оно не может быть разделено без остатка на `2`, `3` и `4`. -**Write the code which outputs prime numbers in the interval from `2` to `n`.** +**Создайте код, который выводит все простые числа из интервала от `2` до `n`.** -For `n = 10` the result will be `2,3,5,7`. +Для `n = 10` результат должен быть `2,3,5,7`. -P.S. The code should work for any `n`, not be hard-tuned for any fixed value. +P.S. Код также должен легко модифицироваться для любых других интервалов. diff --git a/1-js/02-first-steps/12-while-for/article.md b/1-js/02-first-steps/12-while-for/article.md index 992c21af64..e91f6f4a5b 100644 --- a/1-js/02-first-steps/12-while-for/article.md +++ b/1-js/02-first-steps/12-while-for/article.md @@ -1,54 +1,54 @@ -# Loops: while and for +# Циклы while, for -We often need to repeat actions. +При написании скриптов зачастую встаёт задача сделать однотипное действие много раз. -For example, outputting goods from a list one after another or just running the same code for each number from 1 to 10. +Например, вывести товары из списка один за другим. Или просто перебрать все числа от `1` до `10` и для каждого выполнить одинаковый код. -*Loops* are a way to repeat the same code multiple times. +Для многократного повторения одного участка кода – предусмотрены *циклы*. -## The "while" loop +## Цикл "while" -The `while` loop has the following syntax: +Цикл `while` имеет следующий синтаксис: ```js while (condition) { - // code - // so-called "loop body" + // код + // также называемый "телом цикла" } ``` -While the `condition` is `true`, the `code` from the loop body is executed. +Пока `condition` вычисляется в `true`, выполняется код из тела цикла. -For instance, the loop below outputs `i` while `i < 3`: +Например, цикл ниже выводит `i` пока `i < 3`: ```js run let i = 0; -while (i < 3) { // shows 0, then 1, then 2 +while (i < 3) { // выводит 0, затем 1, затем 2 alert( i ); i++; } ``` -A single execution of the loop body is called *an iteration*. The loop in the example above makes three iterations. +Повторение цикла по-научному называется *итерация*. Цикл в примере выше совершает три итерации. -If `i++` was missing from the example above, the loop would repeat (in theory) forever. In practice, the browser provides ways to stop such loops, and in server-side JavaScript, we can kill the process. +Если бы `i++` отсутствовало в примере выше, то цикл бы повторялся (в теории) вечно. На практике же, браузер предоставляет способы останавливать такие циклы, а в JavaScript на стороне сервера, мы можем просто "убить" этот процесс. -Any expression or variable can be a loop condition, not just comparisons: the condition is evaluated and converted to a boolean by `while`. +Любое выражение или переменная может быть условием цикла, а не только сравнения: условие `while` вычисляется и преобразуется в boolean. -For instance, a shorter way to write `while (i != 0)` is `while (i)`: +Например, `while (i)` -- более краткий вариант `while (i != 0)`: ```js run let i = 3; *!* -while (i) { // when i becomes 0, the condition becomes falsy, and the loop stops +while (i) { // когда i будет равно 0, условие станет ложным и цикл остановится */!* alert( i ); i--; } ``` -````smart header="Brackets are not required for a single-line body" -If the loop body has a single statement, we can omit the brackets `{…}`: +````smart header="Фигурные скобки не требуются для тела цикла из одной строки" +Если тело цикла состоит лишь из одной конструкции, мы можем опустить фигурные скобки `{…}`: ```js run let i = 3; @@ -58,19 +58,19 @@ while (i) alert(i--); ``` ```` -## The "do..while" loop +## Цикл "do…while" -The condition check can be moved *below* the loop body using the `do..while` syntax: +Проверку условия можно разместить под телом цикла, используя специальный синтаксис `do..while`: ```js do { - // loop body + // тело цикла } while (condition); ``` -The loop will first execute the body, then check the condition, and, while it's truthy, execute it again and again. +Цикл сначала выполнит тело, а затем проверит условие, и пока оно вычисляется в `true`, он будет выполняться снова и снова. -For example: +Например: ```js run let i = 0; @@ -80,107 +80,109 @@ do { } while (i < 3); ``` -This form of syntax should only be used when you want the body of the loop to execute **at least once** regardless of the condition being truthy. Usually, the other form is preferred: `while(…) {…}`. +Такая форма синтаксиса оправдана, если вы хотите, чтобы тело цикла выполнилось **хотя бы один раз** даже если условие окажется ложным. Чаще используется обычная форма: `while(…) {…}`. -## The "for" loop +## Цикл "for" -The `for` loop is the most commonly used loop. +В большинстве случаев применяется цикл `for`. -It looks like this: +Выглядит он так: ```js for (begin; condition; step) { - // ... loop body ... + // ... тело цикла ... } ``` -Let's learn the meaning of these parts by example. The loop below runs `alert(i)` for `i` from `0` up to (but not including) `3`: +Давайте разберёмся, что означает каждая часть следующего примера. Цикл ниже выполняет `alert(i)` для `i` от `0` до (но не включая) `3`: ```js run -for (let i = 0; i < 3; i++) { // shows 0, then 1, then 2 +for (let i = 0; i < 3; i++) { // выведет 0, затем 1, затем 2 alert(i); } ``` -Let's examine the `for` statement part-by-part: +Рассмотрим конструкцию `for` подробней: -| part | | | +| часть | | | |-------|----------|----------------------------------------------------------------------------| -| begin | `i = 0` | Executes once upon entering the loop. | -| condition | `i < 3`| Checked before every loop iteration. If false, the loop stops. | -| step| `i++` | Executes after the body on each iteration but before the condition check. | -| body | `alert(i)`| Runs again and again while the condition is truthy. | +| *начало* | `i = 0` | Выполняется один раз при входе в цикл | +| *условие* | `i < 3`| Проверяется *перед* каждой итерацией цикла. Если оно вычислится в `false`, цикл остановится. | +| *шаг* | `i++` | Выполняется *после* тела цикла на каждой итерации *перед* проверкой условия. | +| *тело* | `alert(i)`| Выполняется снова и снова, пока условие вычисляется в `true`. | -The general loop algorithm works like this: +В целом, алгоритм работы цикла выглядит следующим образом: ``` -Run begin -→ (if condition → run body and run step) -→ (if condition → run body and run step) -→ (if condition → run body and run step) +Выполнить *начало* +→ (Если *условие* == true → Выполнить *тело*, Выполнить *шаг*) +→ (Если *условие* == true → Выполнить *тело*, Выполнить *шаг*) +→ (Если *условие* == true → Выполнить *тело*, Выполнить *шаг*) → ... ``` -If you are new to loops, it could help to go back to the example and reproduce how it runs step-by-step on a piece of paper. +Если тема циклов для вас нова, может быть полезным вернуться к примеру выше и воспроизвести его работу на листе бумаги, шаг за шагом. -Here's exactly what happens in our case: +Вот что на самом деле происходит в нашем случае: ```js // for (let i = 0; i < 3; i++) alert(i) -// run begin +// Выполнить начало let i = 0 -// if condition → run body and run step +// Если условие == true → Выполнить тело, Выполнить шаг if (i < 3) { alert(i); i++ } -// if condition → run body and run step +// Если условие == true → Выполнить тело, Выполнить шаг if (i < 3) { alert(i); i++ } -// if condition → run body and run step +// Если условие == true → Выполнить тело, Выполнить шаг if (i < 3) { alert(i); i++ } -// ...finish, because now i == 3 +// ...конец, потому что теперь i == 3 ``` -````smart header="Inline variable declaration" -Here, the "counter" variable `i` is declared right in the loop. This is called an "inline" variable declaration. Such variables are visible only inside the loop. +````smart header="Встроенное объявление переменной" +В примере переменная "счётчика" `i` была объявлена прямо в цикле. Это так называемое "встроенное" объявление переменной. Такие переменные видны только внутри цикла. ```js run for (*!*let*/!* i = 0; i < 3; i++) { alert(i); // 0, 1, 2 } -alert(i); // error, no such variable +alert(i); // ошибка, нет такой переменной ``` -Instead of defining a variable, we could use an existing one: +Вместо объявления новой переменной мы можем использовать уже существующую. + +Например: ```js run let i = 0; -for (i = 0; i < 3; i++) { // use an existing variable +for (i = 0; i < 3; i++) { // используем существующую переменную alert(i); // 0, 1, 2 } -alert(i); // 3, visible, because declared outside of the loop +alert(i); // 3, переменная доступна, т.к. была объявлена снаружи цикла ``` ```` -### Skipping parts +### Пропуск частей "for" -Any part of `for` can be skipped. +Любая часть `for` может быть пропущена. -For example, we can omit `begin` if we don't need to do anything at the loop start. +Для примера, мы можем пропустить `начало` если нам ничего не нужно делать перед стартом цикла. -Like here: +Вот так: ```js run -let i = 0; // we have i already declared and assigned +let i = 0; // мы уже имеем объявленную i с присвоенным значением -for (; i < 3; i++) { // no need for "begin" +for (; i < 3; i++) { // нет необходимости в "начале" alert( i ); // 0, 1, 2 } ``` -We can also remove the `step` part: +Можно убрать и `шаг`: ```js run let i = 0; @@ -190,25 +192,25 @@ for (; i < 3;) { } ``` -This makes the loop identical to `while (i < 3)`. +Это сделает цикл аналогичным `while (i < 3)`. -We can actually remove everything, creating an infinite loop: +А можно и вообще убрать всё, получив бесконечный цикл: ```js for (;;) { - // repeats without limits + // будет выполняться вечно } ``` -Please note that the two `for` semicolons `;` must be present. Otherwise, there would be a syntax error. +При этом сами точки с запятой `;` обязательно должны присутствовать, иначе будет ошибка синтаксиса. -## Breaking the loop +## Прерывание цикла: "break" -Normally, a loop exits when its condition becomes falsy. +Обычно цикл завершается при вычислении *условия* в `false`. -But we can force the exit at any time using the special `break` directive. +Но мы можем выйти из цикла в любой момент с помощью специальной директивы `break`. -For example, the loop below asks the user for a series of numbers, "breaking" when no number is entered: +Например, следующий код подсчитывает сумму вводимых чисел до тех пор, пока посетитель их вводит, а затем – выдаёт: ```js let sum = 0; @@ -227,32 +229,32 @@ while (true) { alert( 'Sum: ' + sum ); ``` -The `break` directive is activated at the line `(*)` if the user enters an empty line or cancels the input. It stops the loop immediately, passing control to the first line after the loop. Namely, `alert`. +Директива `break` в строке `(*)`, если посетитель ничего не ввёл, полностью прекращает выполнение цикла и передаёт управление на строку за его телом, то есть на `alert`. -The combination "infinite loop + `break` as needed" is great for situations when a loop's condition must be checked not in the beginning or end of the loop, but in the middle or even in several places of its body. +Вообще, сочетание «бесконечный цикл + `break`» – отличная штука для тех ситуаций, когда условие, по которому нужно прерваться, находится не в начале-конце цикла, а посередине. -## Continue to the next iteration [#continue] +## Переход к следующей итерации: continue [#continue] -The `continue` directive is a "lighter version" of `break`. It doesn't stop the whole loop. Instead, it stops the current iteration and forces the loop to start a new one (if the condition allows). +Директива `continue` -- "облегчённая версия" `break`. Она прерывает не весь цикл, а лишь останавливает текущую итерацию и вынуждает цикл перейти к следующей (если позволяет условие). -We can use it if we're done with the current iteration and would like to move on to the next one. +Её используют, если понятно, что на текущем повторе цикла делать больше нечего. -The loop below uses `continue` to output only odd values: +Например, цикл ниже использует `continue`, чтобы выводить только нечётные значения: ```js run no-beautify for (let i = 0; i < 10; i++) { - // if true, skip the remaining part of the body + // если true, пропустить оставшуюся часть тела цикла *!*if (i % 2 == 0) continue;*/!* - alert(i); // 1, then 3, 5, 7, 9 + alert(i); // 1, затем 3, 5, 7, 9 } ``` -For even values of `i`, the `continue` directive stops executing the body and passes control to the next iteration of `for` (with the next number). So the `alert` is only called for odd values. +Для чётных значений `i`, директива `continue` прекращает выполнение тела цикла и передаёт управление на следующую итерацию `for` (со следующим числом). Таким образом `alert` вызывается только для нечётных значений. -````smart header="The `continue` directive helps decrease nesting" -A loop that shows odd values could look like this: +````smart header="Директива `continue` позволяет избегать вложенности" +Цикл, который обрабатывает только нечётные значения, мог бы выглядеть так: ```js for (let i = 0; i < 10; i++) { @@ -264,15 +266,15 @@ for (let i = 0; i < 10; i++) { } ``` -From a technical point of view, this is identical to the example above. Surely, we can just wrap the code in an `if` block instead of using `continue`. +С технической точки зрения он полностью идентичен. Действительно, вместо `continue` можно просто завернуть действия в блок `if`. -But as a side-effect, this created one more level of nesting (the `alert` call inside the curly braces). If the code inside of`if` is longer than a few lines, that may decrease the overall readability. +Однако, мы получили дополнительный уровень вложенности фигурных скобок. Если код внутри `if` более длинный, то это ухудшает читаемость, в отличие от варианта с `continue`. ```` -````warn header="No `break/continue` to the right side of '?'" -Please note that syntax constructs that are not expressions cannot be used with the ternary operator `?`. In particular, directives such as `break/continue` aren't allowed there. +````warn header="Нельзя использовать `break/continue` справа от оператора '?'" +Обратите внимание, что эти синтаксические конструкции не являются выражениями, и не могут быть использованы с тернарным оператором `?`. В частности, использование таких директив, как `break/continue` вызовет ошибку. -For example, if we take this code: +Например, если мы возьмём этот код: ```js if (i > 5) { @@ -282,24 +284,24 @@ if (i > 5) { } ``` -...and rewrite it using a question mark: +...и перепишем его используя вопросительный знак: ```js no-beautify -(i > 5) ? alert(i) : *!*continue*/!*; // continue isn't allowed here +(i > 5) ? alert(i) : *!*continue*/!*; // continue здесь приведёт к ошибке ``` -...it stops working. Code like this will give a syntax error: +...выполнение остановится. Такой код приведёт к синтаксической ошибке: -This is just another reason not to use the question mark operator `?` instead of `if`. +Это лишь ещё один повод не использовать оператор вопросительного знака `?` вместо `if`. ```` -## Labels for break/continue +## Метки для break/continue -Sometimes we need to break out from multiple nested loops at once. +Бывает нужно выйти одновременно из нескольких уровней цикла сразу. -For example, in the code below we loop over `i` and `j`, prompting for the coordinates `(i, j)` from `(0,0)` to `(3,3)`: +Например, в коде ниже мы проходимся циклами по `i` и `j`, запрашивая с помощью `prompt` координаты `(i, j)` с `(0,0)` до `(3,3)`: ```js run no-beautify for (let i = 0; i < 3; i++) { @@ -308,7 +310,7 @@ for (let i = 0; i < 3; i++) { let input = prompt(`Value at coords (${i},${j})`, ''); - // what if I want to exit from here to Done (below)? + // Что если мы захотим перейти к Done (ниже) прямо отсюда? } } @@ -316,18 +318,18 @@ for (let i = 0; i < 3; i++) { alert('Done!'); ``` -We need a way to stop the process if the user cancels the input. +Нам нужен способ остановить выполнение если пользователь отменит ввод. -The ordinary `break` after `input` would only break the inner loop. That's not sufficient--labels, come to the rescue! +Обычный `break` после `input` лишь прервёт внутренний цикл. Этого не достаточно -- метки, приходят на помощь! -A *label* is an identifier with a colon before a loop: +*Метка* имеет вид идентификатора с двоеточием перед циклом: ```js labelName: for (...) { ... } ``` -The `break ` statement in the loop below breaks out to the label: +Вызов `break ` в цикле ниже ищет ближайший внешний цикл с такой меткой и переходит в его конец. ```js run no-beautify *!*outer:*/!* for (let i = 0; i < 3; i++) { @@ -336,51 +338,51 @@ The `break ` statement in the loop below breaks out to the label: let input = prompt(`Value at coords (${i},${j})`, ''); - // if an empty string or canceled, then break out of both loops + // если пустая строка или ОТМЕНА, то выйти из обоих циклов if (!input) *!*break outer*/!*; // (*) - // do something with the value... + // сделать что-нибудь со значениями... } } alert('Done!'); ``` -In the code above, `break outer` looks upwards for the label named `outer` and breaks out of that loop. - -So the control goes straight from `(*)` to `alert('Done!')`. +В примере выше это означает, что вызовом `break outer` будет разорван самый внешний цикл до метки с именем `outer` и управление перейдёт со строки помеченной `(*)` к `alert('Done!')`. -We can also move the label onto a separate line: +Можно размещать метку на отдельной строке: ```js no-beautify outer: for (let i = 0; i < 3; i++) { ... } ``` -The `continue` directive can also be used with a label. In this case, code execution jumps to the next iteration of the labeled loop. +Директива `continue`, также может быть использована с меткой. В этом случае управление перейдёт на следующую итерацию цикла с меткой. -````warn header="Labels are not a \"goto\"" -Labels do not allow us to jump into an arbitrary place in the code. +````warn header="Метки не то же самое, что \"goto\"" +Метки не дают возможности передавать управление в произвольное место кода. -For example, it is impossible to do this: +Например, нет возможности сделать следующее: ```js -break label; // jumps to label? No. +break label; // прыгнуть к метке? Нет. label: for (...) ``` -A call to `break/continue` is only possible from inside a loop and the label must be somewhere above the directive. +Вызов `break/continue` возможен только внутри цикла и метка должна находиться где-то выше этой директивы. ```` -## Summary +## Итого + +Мы рассмотрели 3 вида циклов: -We covered 3 types of loops: +- `while` -- Проверяет условие перед каждой итерацией. +- `do..while` -- Проверяет условие после каждой итерации. +- `for (;;)` -- Проверяет условие перед каждой итерацией, есть возможность задать дополнительные настройки. -- `while` -- The condition is checked before each iteration. -- `do..while` -- The condition is checked after each iteration. -- `for (;;)` -- The condition is checked before each iteration, additional settings available. +Чтобы организовать бесконечный цикл, используют конструкцию `while (true)`. При этом он, как и любой другой цикл, может быть прерван директивой `break`. -To make an "infinite" loop, usually the `while(true)` construct is used. Such a loop, just like any other, can be stopped with the `break` directive. +Если на данной итерации цикла делать больше ничего не надо, но полностью прекращать цикл не следует – используют директиву `continue`. -If we don't want to do anything in the current iteration and would like to forward to the next one, we can use the `continue` directive. +Обе этих директивы поддерживают *метки*, которые ставятся перед циклом. Метки – единственный способ для `break/continue` повлиять на выполнение внешнего цикла. -`break/continue` support labels before the loop. A label is the only way for `break/continue` to escape a nested loop to go to an outer one. +Заметим, что метки не позволяют прыгнуть в произвольное место кода, в JavaScript нет такой возможности. diff --git a/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/solution.md b/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/solution.md index d3e397434b..9af87fd7c9 100644 --- a/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/solution.md +++ b/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/solution.md @@ -1,6 +1,6 @@ -To precisely match the functionality of `switch`, the `if` must use a strict comparison `'==='`. +Если совсем точно следовать работе `switch`, то `if` должен выполнять строгое сравнение `'==='`. -For given strings though, a simple `'=='` works too. +В реальном случае, скорее всего, подойдёт обычное сравнение `'=='`. ```js no-beautify if(browser == 'Edge') { @@ -15,6 +15,6 @@ if(browser == 'Edge') { } ``` -Please note: the construct `browser == 'Chrome' || browser == 'Firefox' …` is split into multiple lines for better readability. +Обратите внимание: конструкция `browser == 'Chrome' || browser == 'Firefox' ...` разбита на несколько строк для лучшей читаемости. -But the `switch` construct is still cleaner and more descriptive. +Но всё равно запись через `switch` нагляднее. diff --git a/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/task.md b/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/task.md index f4dc0e5f19..6f2c5e7e19 100644 --- a/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/task.md +++ b/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/task.md @@ -1,10 +1,10 @@ -importance: 5 +важность: 5 --- -# Rewrite the "switch" into an "if" +# Напишите "if", аналогичный "switch" -Write the code using `if..else` which would correspond to the following `switch`: +Напишите `if..else`, соответствующий следующему `switch`: ```js switch (browser) { @@ -23,4 +23,3 @@ switch (browser) { alert( 'We hope that this page looks ok!' ); } ``` - diff --git a/1-js/02-first-steps/13-switch/2-rewrite-if-switch/solution.md b/1-js/02-first-steps/13-switch/2-rewrite-if-switch/solution.md index ed87dd94b6..7095b8406d 100644 --- a/1-js/02-first-steps/13-switch/2-rewrite-if-switch/solution.md +++ b/1-js/02-first-steps/13-switch/2-rewrite-if-switch/solution.md @@ -1,4 +1,4 @@ -The first two checks turn into two `case`. The third check is split into two cases: +Первые две проверки – обычный `case`, третья разделена на два `case`: ```js run let a = +prompt('a?', ''); @@ -21,6 +21,6 @@ switch (a) { } ``` -Please note: the `break` at the bottom is not required. But we put it to make the code future-proof. +Обратите внимание: `break` внизу не обязателен, но ставится по «правилам хорошего тона». -In the future, there is a chance that we'd want to add one more `case`, for example `case 4`. And if we forget to add a break before it, at the end of `case 3`, there will be an error. So that's a kind of self-insurance. +Допустим, он не стоит. Есть шанс, что в будущем нам понадобится добавить в конец ещё один `case`, например `case 4`, и мы, вполне вероятно, забудем этот `break` поставить. В результате выполнение `case 2/case 3` продолжится на `case 4` и будет ошибка. diff --git a/1-js/02-first-steps/13-switch/2-rewrite-if-switch/task.md b/1-js/02-first-steps/13-switch/2-rewrite-if-switch/task.md index ec99d098db..0a7b1be637 100644 --- a/1-js/02-first-steps/13-switch/2-rewrite-if-switch/task.md +++ b/1-js/02-first-steps/13-switch/2-rewrite-if-switch/task.md @@ -1,10 +1,10 @@ -importance: 4 +важность: 4 --- -# Rewrite "if" into "switch" +# Переписать "if'ы" в "switch" -Rewrite the code below using a single `switch` statement: +Перепишите код с использованием одной конструкции `switch`: ```js run let a = +prompt('a?', ''); @@ -20,4 +20,3 @@ if (a == 2 || a == 3) { alert( '2,3' ); } ``` - diff --git a/1-js/02-first-steps/13-switch/article.md b/1-js/02-first-steps/13-switch/article.md index 258f240687..adf9423dd4 100644 --- a/1-js/02-first-steps/13-switch/article.md +++ b/1-js/02-first-steps/13-switch/article.md @@ -1,14 +1,14 @@ -# The "switch" statement +# Конструкция "switch" -A `switch` statement can replace multiple `if` checks. +Конструкция `switch` заменяет собой сразу несколько `if`. -It gives a more descriptive way to compare a value with multiple variants. +Она представляет собой более наглядный способ сравнить выражение сразу с несколькими вариантами. -## The syntax +## Синтаксис -The `switch` has one or more `case` blocks and an optional default. +Конструкция `switch` имеет один или более блок `case` и необязательный блок `default`. -It looks like this: +Выглядит она так: ```js no-beautify switch(x) { @@ -26,13 +26,13 @@ switch(x) { } ``` -- The value of `x` is checked for a strict equality to the value from the first `case` (that is, `value1`) then to the second (`value2`) and so on. -- If the equality is found, `switch` starts to execute the code starting from the corresponding `case`, until the nearest `break` (or until the end of `switch`). -- If no case is matched then the `default` code is executed (if it exists). +- Переменная `x` проверяется на строгое равенство первому значению `value1`, затем второму `value2` и так далее. +- Если соответствие установлено – `switch` начинает выполняться от соответствующей директивы `case` и далее, до ближайшего `break` (или до конца `switch`). +- Если ни один `case` не совпал – выполняется (если есть) вариант `default`. -## An example +## Пример работы -An example of `switch` (the executed code is highlighted): +Пример использования `switch` (сработавший код выделен): ```js run let a = 2 + 2; @@ -54,13 +54,13 @@ switch (a) { } ``` -Here the `switch` starts to compare `a` from the first `case` variant that is `3`. The match fails. +Здесь оператор `switch` последовательно сравнит `a` со всеми вариантами из `case`. -Then `4`. That's a match, so the execution starts from `case 4` until the nearest `break`. +Сначала `3`, затем – так как нет совпадения – `4`. Совпадение найдено, будет выполнен этот вариант, со строки `alert( 'Exactly!' )` и далее, до ближайшего `break`, который прервёт выполнение. -**If there is no `break` then the execution continues with the next `case` without any checks.** +**Если `break` нет, то выполнение пойдёт ниже по следующим `case`, при этом остальные проверки игнорируются.** -An example without `break`: +Пример без `break`: ```js run let a = 2 + 2; @@ -79,7 +79,7 @@ switch (a) { } ``` -In the example above we'll see sequential execution of three `alert`s: +В примере выше последовательно выполнятся три `alert`: ```js alert( 'Exactly!' ); @@ -87,10 +87,10 @@ alert( 'Too big' ); alert( "I don't know such values" ); ``` -````smart header="Any expression can be a `switch/case` argument" -Both `switch` and `case` allow arbitrary expressions. +````smart header="Любое выражение может быть `switch/case` аргументом" +Оба `switch` и `case` допускают любое выражение в качестве аргумента. -For example: +Например: ```js run let a = "1"; @@ -107,14 +107,14 @@ switch (+a) { alert("this doesn't run"); } ``` -Here `+a` gives `1`, that's compared with `b + 1` in `case`, and the corresponding code is executed. +В этом примере выражение `+a` вычисляется в `1`, что совпадает с выражением `b + 1` в `case`, и следовательно, код в этом блоке будет выполнен. ```` -## Grouping of "case" +## Группировка "case" -Several variants of `case` which share the same code can be grouped. +Несколько вариантов `case`, использующих один код, можно группировать. -For example, if we want the same code to run for `case 3` and `case 5`: +Для примера, выполним один и тот же код для `case 3` и `case 5`, сгруппировав их: ```js run no-beautify let a = 2 + 2; @@ -125,7 +125,7 @@ switch (a) { break; *!* - case 3: // (*) grouped two cases + case 3: // (*) группируем оба case case 5: alert('Wrong!'); alert("Why don't you take a math class?"); @@ -137,15 +137,15 @@ switch (a) { } ``` -Now both `3` and `5` show the same message. +Теперь оба варианта `3` и `5` выводят одно сообщение. -The ability to "group" cases is a side-effect of how `switch/case` works without `break`. Here the execution of `case 3` starts from the line `(*)` and goes through `case 5`, because there's no `break`. +Возможность группировать `case` это побочный эффект того, как `switch/case` работает без `break`. Здесь выполнение `case 3` начинается со строки `(*)` и продолжается в `case 5`, потому отсутствует `break`. -## Type matters +## Тип имеет значение -Let's emphasize that the equality check is always strict. The values must be of the same type to match. +Нужно отметить, что проверка на равенство всегда строгая. Значения должны быть одного типа, чтобы выполнялось равенство. -For example, let's consider the code: +Для примера, давайте рассмотрим следующий код: ```js run let arg = prompt("Enter a value?"); @@ -167,6 +167,6 @@ switch (arg) { } ``` -1. For `0`, `1`, the first `alert` runs. -2. For `2` the second `alert` runs. -3. But for `3`, the result of the `prompt` is a string `"3"`, which is not strictly equal `===` to the number `3`. So we've got a dead code in `case 3`! The `default` variant will execute. +1. Для `'0'` и `'1'` выполнится первый `alert`. +2. Для `'2'` -- второй `alert`. +3. Но для `3`, результат выполнения `prompt` будет строка `"3"`, которая не соответствует строгому равенству `===` с числом `3`. Таким образом, мы имеем "мёртвый код" в `case 3`! Выполнится вариант `default`. diff --git a/1-js/02-first-steps/14-function-basics/1-if-else-required/solution.md b/1-js/02-first-steps/14-function-basics/1-if-else-required/solution.md index e41c80418a..d565afb420 100644 --- a/1-js/02-first-steps/14-function-basics/1-if-else-required/solution.md +++ b/1-js/02-first-steps/14-function-basics/1-if-else-required/solution.md @@ -1 +1 @@ -No difference. \ No newline at end of file +Оба варианта функции работают одинаково, отличий нет. diff --git a/1-js/02-first-steps/14-function-basics/1-if-else-required/task.md b/1-js/02-first-steps/14-function-basics/1-if-else-required/task.md index 4f69a5c8c3..a760abd97f 100644 --- a/1-js/02-first-steps/14-function-basics/1-if-else-required/task.md +++ b/1-js/02-first-steps/14-function-basics/1-if-else-required/task.md @@ -1,12 +1,12 @@ -importance: 4 +важность: 4 --- -# Is "else" required? +# Обязателен ли "else"? -The following function returns `true` if the parameter `age` is greater than `18`. +Следующая функция возвращает `true`, если параметр `age` больше `18`. -Otherwise it asks for a confirmation and returns its result: +В ином случае она задаёт вопрос посредством вызова `confirm` и возвращает его результат: ```js function checkAge(age) { @@ -21,7 +21,7 @@ function checkAge(age) { } ``` -Will the function work differently if `else` is removed? +Будет ли эта функция работать как-то иначе, если убрать `else`? ```js function checkAge(age) { @@ -35,4 +35,4 @@ function checkAge(age) { } ``` -Is there any difference in the behavior of these two variants? +Есть ли хоть одно отличие в поведении этого варианта? diff --git a/1-js/02-first-steps/14-function-basics/2-rewrite-function-question-or/solution.md b/1-js/02-first-steps/14-function-basics/2-rewrite-function-question-or/solution.md index c8ee9618fc..86d172e19c 100644 --- a/1-js/02-first-steps/14-function-basics/2-rewrite-function-question-or/solution.md +++ b/1-js/02-first-steps/14-function-basics/2-rewrite-function-question-or/solution.md @@ -1,4 +1,4 @@ -Using a question mark operator `'?'`: +Используя оператор `?`: ```js function checkAge(age) { @@ -6,7 +6,7 @@ function checkAge(age) { } ``` -Using OR `||` (the shortest variant): +Используя оператор `||` (самый короткий вариант): ```js function checkAge(age) { @@ -14,4 +14,4 @@ function checkAge(age) { } ``` -Note that the parentheses around `age > 18` are not required here. They exist for better readabilty. +Обратите внимание, что круглые скобки вокруг `age > 18` не обязательны. Их наличие необходимо для более лучшего понимания. diff --git a/1-js/02-first-steps/14-function-basics/2-rewrite-function-question-or/task.md b/1-js/02-first-steps/14-function-basics/2-rewrite-function-question-or/task.md index 523bb127a8..b618821e3a 100644 --- a/1-js/02-first-steps/14-function-basics/2-rewrite-function-question-or/task.md +++ b/1-js/02-first-steps/14-function-basics/2-rewrite-function-question-or/task.md @@ -1,12 +1,12 @@ -importance: 4 +важность: 4 --- -# Rewrite the function using '?' or '||' +# Перепишите функцию, используя оператор '?' или '||' -The following function returns `true` if the parameter `age` is greater than `18`. +Следующая функция возвращает `true`, если параметр `age` больше `18`. -Otherwise it asks for a confirmation and returns its result. +В ином случае она задаёт вопрос `confirm` и возвращает его результат. ```js function checkAge(age) { @@ -18,9 +18,9 @@ function checkAge(age) { } ``` -Rewrite it, to perform the same, but without `if`, in a single line. +Перепишите функцию, чтобы она делала то же самое, но без `if`, в одну строку. -Make two variants of `checkAge`: +Сделайте два варианта функции `checkAge`: -1. Using a question mark operator `?` -2. Using OR `||` +1. Используя оператор `?` +2. Используя оператор `||` diff --git a/1-js/02-first-steps/14-function-basics/3-min/solution.md b/1-js/02-first-steps/14-function-basics/3-min/solution.md index 2236d9203f..60ea44ada2 100644 --- a/1-js/02-first-steps/14-function-basics/3-min/solution.md +++ b/1-js/02-first-steps/14-function-basics/3-min/solution.md @@ -1,4 +1,4 @@ -A solution using `if`: +Вариант решения с использованием `if`: ```js function min(a, b) { @@ -10,7 +10,7 @@ function min(a, b) { } ``` -A solution with a question mark operator `'?'`: +Вариант решения с оператором `?`: ```js function min(a, b) { @@ -18,4 +18,4 @@ function min(a, b) { } ``` -P.S. In the case of an equality `a == b` it does not matter what to return. \ No newline at end of file +P.S. В случае равенства `a == b` не имеет значения, что вернёт функция. diff --git a/1-js/02-first-steps/14-function-basics/3-min/task.md b/1-js/02-first-steps/14-function-basics/3-min/task.md index 50edd0d36f..0f14549823 100644 --- a/1-js/02-first-steps/14-function-basics/3-min/task.md +++ b/1-js/02-first-steps/14-function-basics/3-min/task.md @@ -1,16 +1,15 @@ -importance: 1 +важность: 1 --- -# Function min(a, b) +# Функция min(a, b) -Write a function `min(a,b)` which returns the least of two numbers `a` and `b`. +Напишите функцию `min(a,b)`, которая возвращает меньшее из чисел `a`,`b`. -For instance: +Пример вызовов: ```js min(2, 5) == 2 min(3, -1) == -1 min(1, 1) == 1 ``` - diff --git a/1-js/02-first-steps/14-function-basics/4-pow/solution.md b/1-js/02-first-steps/14-function-basics/4-pow/solution.md index 5ef20c3863..f6b17ed44e 100644 --- a/1-js/02-first-steps/14-function-basics/4-pow/solution.md +++ b/1-js/02-first-steps/14-function-basics/4-pow/solution.md @@ -20,4 +20,3 @@ if (n < 1) { alert( pow(x, n) ); } ``` - diff --git a/1-js/02-first-steps/14-function-basics/4-pow/task.md b/1-js/02-first-steps/14-function-basics/4-pow/task.md index f569320c7f..9a10353e28 100644 --- a/1-js/02-first-steps/14-function-basics/4-pow/task.md +++ b/1-js/02-first-steps/14-function-basics/4-pow/task.md @@ -1,10 +1,10 @@ -importance: 4 +важность: 4 --- -# Function pow(x,n) +# Функция pow(x,n) -Write a function `pow(x,n)` that returns `x` in power `n`. Or, in other words, multiplies `x` by itself `n` times and returns the result. +Напишите функцию `pow(x,n)`, которая возвращает `x` в степени `n`. Иначе говоря, умножает `x` на себя `n` раз и возвращает результат. ```js pow(3, 2) = 3 * 3 = 9 @@ -12,8 +12,8 @@ pow(3, 3) = 3 * 3 * 3 = 27 pow(1, 100) = 1 * 1 * ...* 1 = 1 ``` -Create a web-page that prompts for `x` and `n`, and then shows the result of `pow(x,n)`. +Создайте страницу, которая запрашивает `x` и `n`, а затем выводит результат `pow(x,n)`. [demo] -P.S. In this task the function should support only natural values of `n`: integers up from `1`. +P.S. В этой задаче функция обязана поддерживать только натуральные значения `n`, т.е. целые от `1` и выше. diff --git a/1-js/02-first-steps/14-function-basics/article.md b/1-js/02-first-steps/14-function-basics/article.md index 874890ab58..2134b14451 100644 --- a/1-js/02-first-steps/14-function-basics/article.md +++ b/1-js/02-first-steps/14-function-basics/article.md @@ -1,18 +1,18 @@ -# Functions +# Функции -Quite often we need to perform a similar action in many places of the script. +Зачастую нам надо повторять одно и то же действие во многих частях программы. -For example, we need to show a nice-looking message when a visitor logs in, logs out and maybe somewhere else. +Например, красиво вывести сообщение необходимо при приветствии посетителя, при выходе посетителя с сайта, ещё где-нибудь. -Functions are the main "building blocks" of the program. They allow the code to be called many times without repetition. +Чтобы не повторять один и тот же код во многих местах, придуманы функции. Функции являются основными «строительными блоками» программы. -We've already seen examples of built-in functions, like `alert(message)`, `prompt(message, default)` and `confirm(question)`. But we can create functions of our own as well. +Примеры встроенных функций вы уже видели – это `alert(message)`, `prompt(message, default)` и `confirm(question)`. Но можно создавать и свои. -## Function Declaration +## Объявление функции -To create a function we can use a *function declaration*. +Для создания функций мы можем использовать *объявление функции*. -It looks like this: +Пример объявления функции: ```js function showMessage() { @@ -20,13 +20,13 @@ function showMessage() { } ``` -The `function` keyword goes first, then goes the *name of the function*, then a list of *parameters* between the parentheses (empty in the example above) and finally the code of the function, also named "the function body", between curly braces. +Вначале идет ключевое слово `function`, после него *имя функции*, затем список *параметров* в круглых скобках (в примере выше он пустой) и, наконец, код функции, называемый "телом функции", расположенный внутри фигурных скобок. ![](function_basics.png) -Our new function can be called by its name: `showMessage()`. +Наша новая функция может быть вызвана по её имени: `showMessage()`. -For instance: +Например: ```js run function showMessage() { @@ -39,22 +39,22 @@ showMessage(); */!* ``` -The call `showMessage()` executes the code of the function. Here we will see the message two times. +Вызов `showMessage()` выполняет код функции. Здесь мы увидим сообщение дважды. -This example clearly demonstrates one of the main purposes of functions: to avoid code duplication. +Этот пример явно демонстрирует одно из главных предназначений функций: избавление от дублирования кода. -If we ever need to change the message or the way it is shown, it's enough to modify the code in one place: the function which outputs it. +Если понадобится поменять сообщение или способ его вывода – достаточно изменить его в одном месте: в функции, которая его выводит. -## Local variables +## Локальные переменные -A variable declared inside a function is only visible inside that function. +Переменные объявленные внутри функции, видны только внутри этой функции. -For example: +Например: ```js run function showMessage() { *!* - let message = "Hello, I'm JavaScript!"; // local variable + let message = "Hello, I'm JavaScript!"; // локальная переменная */!* alert( message ); @@ -62,12 +62,12 @@ function showMessage() { showMessage(); // Hello, I'm JavaScript! -alert( message ); // <-- Error! The variable is local to the function +alert( message ); // <-- будет ошибка, т.к. переменная видна только внутри функции ``` -## Outer variables +## Внешние переменные -A function can access an outer variable as well, for example: +У функции есть доступ к внешним переменным, например: ```js run no-beautify let *!*userName*/!* = 'John'; @@ -80,65 +80,65 @@ function showMessage() { showMessage(); // Hello, John ``` -The function has full access to the outer variable. It can modify it as well. +Функция обладает полным доступом к внешним переменным и может изменять их значение. -For instance: +Например: ```js run let *!*userName*/!* = 'John'; function showMessage() { - *!*userName*/!* = "Bob"; // (1) changed the outer variable + *!*userName*/!* = "Bob"; // (1) изменяем значение внешней переменной let message = 'Hello, ' + *!*userName*/!*; alert(message); } -alert( userName ); // *!*John*/!* before the function call +alert( userName ); // *!*John*/!* перед вызовом функции showMessage(); -alert( userName ); // *!*Bob*/!*, the value was modified by the function +alert( userName ); // *!*Bob*/!*, значение внешней переменной было изменено функцией ``` -The outer variable is only used if there's no local one. So an occasional modification may happen if we forget `let`. +Внешние переменные используются только если в теле функции нет локальных. Это случается, если мы забываем объявить их с помощью ключевого слова `let`. -If a same-named variable is declared inside the function then it *shadows* the outer one. For instance, in the code below the function uses the local `userName`. The outer one is ignored: +Если одноимённая переменная объявляется внутри функции, тогда она перекрывает внешнюю. Например, в коде ниже функция использует локальную переменную `userName`. Внешняя будет проигнорирована: ```js run let userName = 'John'; function showMessage() { *!* - let userName = "Bob"; // declare a local variable + let userName = "Bob"; // объявляем локальную переменную */!* let message = 'Hello, ' + userName; // *!*Bob*/!* alert(message); } -// the function will create and use its own userName +// функция создаст и будет использовать свою собственную локальную переменную userName showMessage(); -alert( userName ); // *!*John*/!*, unchanged, the function did not access the outer variable +alert( userName ); // *!*John*/!*, не изменилась, у функции нет доступа в внешней переменной ``` -```smart header="Global variables" -Variables declared outside of any function, such as the outer `userName` in the code above, are called *global*. +```smart header="Глобальные переменные" +Переменные, объявленные снаружи функции, такие как внешняя переменная `userName` в коде выше -- называются *Глобальными*. -Global variables are visible from any function (unless shadowed by locals). +*Глобальные переменные* видимы для любой функции (пока их не перекрывают одноимённые локальные переменные). -Usually, a function declares all variables specific to its task. Global variables only store project-level data, and it's important that these variables are accessible from anywhere. Modern code has few or no globals. Most variables reside in their functions. +Обычно в функции объявляются все необходимые переменные для выполнения её задачи. Глобальные переменные хранят данные на уровне проекта, и поэтому важна их доступность из любого места. В современном коде редко используются глобальные переменные. Почти все переменные локальные и находятся внутри функций. ``` -## Parameters +## Параметры -We can pass arbitrary data to functions using parameters (also called *function arguments*) . +Мы можем передать внутрь функции любую информацию, используя параметры (также называемые *аргументы функции*). -In the example below, the function has two parameters: `from` and `text`. +В примере ниже функции передаются два параметра: `from` и `text`. ```js run -function showMessage(*!*from, text*/!*) { // arguments: from, text +function showMessage(*!*from, text*/!*) { // агрументы: from, text alert(from + ': ' + text); } @@ -148,16 +148,16 @@ showMessage('Ann', "What's up?"); // Ann: What's up? (**) */!* ``` -When the function is called in lines `(*)` and `(**)`, the given values are copied to local variables `from` and `text`. Then the function uses them. +Когда функция вызывается в строках `(*)` и `(**)`, переданные значения копируются в локальные переменные `from` и `text`. Затем они используются в теле функции. -Here's one more example: we have a variable `from` and pass it to the function. Please note: the function changes `from`, but the change is not seen outside, because a function always gets a copy of the value: +Вот ещё один пример: у нас есть переменная `from` и мы передаём её функции. Обратите внимание: функция изменяет значение `from`, но это изменение не видно снаружи. Функция всегда получает только копию значения: ```js run function showMessage(from, text) { *!* - from = '*' + from + '*'; // make "from" look nicer + from = '*' + from + '*'; // немного украсим "from" */!* alert( from + ': ' + text ); @@ -167,23 +167,23 @@ let from = "Ann"; showMessage(from, "Hello"); // *Ann*: Hello -// the value of "from" is the same, the function modified a local copy +// значение "from" осталось прежним, функция изменила значение локальной переменной alert( from ); // Ann ``` -## Default values +## Параметры по умолчанию -If a parameter is not provided, then its value becomes `undefined`. +Если параметр не указан, то его значением становится `undefined`. -For instance, the aforementioned function `showMessage(from, text)` can be called with a single argument: +Например, вышеупомянутая функция `showMessage(from, text)` может быть вызвана с одним аргументом: ```js showMessage("Ann"); ``` -That's not an error. Such a call would output `"Ann: undefined"`. There's no `text`, so it's assumed that `text === undefined`. +Это не приведёт к ошибке. Такой вызов выведет `"Ann: undefined"`. В вызове не указан параметр `text`, поэтому предполагается, что `text === undefined`. -If we want to use a "default" `text` in this case, then we can specify it after `=`: +Если мы хотим задать параметру `text` значение по умолчанию, мы должны указать его после `=`: ```js run function showMessage(from, *!*text = "no text given"*/!*) { @@ -193,28 +193,28 @@ function showMessage(from, *!*text = "no text given"*/!*) { showMessage("Ann"); // Ann: no text given ``` -Now if the `text` parameter is not passed, it will get the value `"no text given"` +Теперь, если параметр `text` не указан, его значением будет `"no text given"` -Here `"no text given"` is a string, but it can be a more complex expression, which is only evaluated and assigned if the parameter is missing. So, this is also possible: +В данном случае `"no text given"` это строка, но на её месте могло бы быть и более сложное выражение, которое бы вычислялось и присваивалось при отсутствии параметра. Например: ```js run function showMessage(from, text = anotherFunction()) { - // anotherFunction() only executed if no text given - // its result becomes the value of text + // anotherFunction() выполнится только если не передан text + // результатом будет значение text } ``` -```smart header="Evaluation of default parameters" +```smart header="Вычисление параметров по умолчанию" -In JavaScript, a default parameter is evaluated every time the function is called without the respective parameter. In the example above, `anotherFunction()` is called every time `showMessage()` is called without the `text` parameter. This is in contrast to some other languages like Python, where any default parameters are evaluated only once during the initial interpretation. +В JavaScript параметры по умолчанию вычисляются каждый раз, когда функция вызывается без соответствующего параметра. В примере выше `anotherFunction()` будет вызываться каждый раз, когда `showMessage()` вызывается без параметра `text`. В отличие от других языков, таких как Python, в которых параметры по умолчанию вычисляются лишь один раз во время первоначальной интерпретации. ``` -````smart header="Default parameters old-style" -Old editions of JavaScript did not support default parameters. So there are alternative ways to support them, that you can find mostly in the old scripts. +````smart header="Использование параметров по умолчанию в ранних версиях JavaScript" +Ранние версии JavaScript не поддерживают параметры по умолчанию. Поэтому существуют альтернативные способы, которые могут встречаться в старых скриптах. -For instance, an explicit check for being `undefined`: +Например, явная проверка на `undefined`: ```js function showMessage(from, text) { @@ -228,11 +228,11 @@ function showMessage(from, text) { } ``` -...Or the `||` operator: +...Или с помощью оператора `||`: ```js function showMessage(from, text) { - // if text is falsy then text gets the "default" value + // Если значение text ложно, тогда присвоить параметру text значение по умолчанию text = text || 'no text given'; ... } @@ -242,11 +242,11 @@ function showMessage(from, text) { ```` -## Returning a value +## Возврат значения -A function can return a value back into the calling code as the result. +Функция может возвратить результат, который будет передан в вызвавший её код. -The simplest example would be a function that sums two values: +Простейшим примером может служить функция сложения двух чисел: ```js run no-beautify function sum(a, b) { @@ -257,9 +257,9 @@ let result = sum(1, 2); alert( result ); // 3 ``` -The directive `return` can be in any place of the function. When the execution reaches it, the function stops, and the value is returned to the calling code (assigned to `result` above). +Директива `return` может находиться в любом месте тела функции. Как только выполнение доходит до этого места, функция останавливается, и значение возвращается в вызвавший её код (присваивается переменной `result` выше). -There may be many occurrences of `return` in a single function. For instance: +Вызовов `return` может быть несколько, например: ```js run function checkAge(age) { @@ -283,9 +283,9 @@ if ( checkAge(age) ) { } ``` -It is possible to use `return` without a value. That causes the function to exit immediately. +Возможно использовать `return` и без значения. Это приведёт к немедленному выходу из функции. -For example: +Например: ```js function showMovie(age) { @@ -300,18 +300,18 @@ function showMovie(age) { } ``` -In the code above, if `checkAge(age)` returns `false`, then `showMovie` won't proceed to the `alert`. +В коде выше, если `checkAge(age)` вернёт `false`, `showMovie` не выполнит `alert`. -````smart header="A function with an empty `return` or without it returns `undefined`" -If a function does not return a value, it is the same as if it returns `undefined`: +````smart header="Функция с пустым `return` или без возврата `undefined`" +Если функция не возвращает значения, это всё равно, как если бы она возвращала `undefined`: ```js run -function doNothing() { /* empty */ } +function doNothing() { /* пусто */ } alert( doNothing() === undefined ); // true ``` -An empty `return` is also the same as `return undefined`: +Пустой `return` аналогичен `return undefined`: ```js run function doNothing() { @@ -322,80 +322,80 @@ alert( doNothing() === undefined ); // true ``` ```` -````warn header="Never add a newline between `return` and the value" -For a long expression in `return`, it might be tempting to put it on a separate line, like this: +````warn header="Никогда не добавляйте перевод строки между `return` и его значением" +Для длинного выражения в `return`, может быть заманчиво разместить его на нескольких отдельных строках, например так: ```js return (some + long + expression + or + whatever * f(a) + f(b)) ``` -That doesn't work, because JavaScript assumes a semicolon after `return`. That'll work the same as: +Код не выполнится, потому что интерпретатор JavaScript подставит точку с запятой после `return`. Для него это будет выглядеть так: ```js return*!*;*/!* (some + long + expression + or + whatever * f(a) + f(b)) ``` -So, it effectively becomes an empty return. We should put the value on the same line instead. +Таким образом, это фактически стало пустым `return`. Чтобы это работало, так как мы хотим, необходимо располагать значение `return` на этой же строке. ```` -## Naming a function [#function-naming] +## Выбор имени функции [#function-naming] -Functions are actions. So their name is usually a verb. It should be brief, as accurate as possible and describe what the function does, so that someone reading the code gets an indication of what the function does. +Функция - это действие. Поэтому имя функции обычно является глаголом. Оно должно быть простым, на сколько возможно точным и описывать действие функции. Чтобы программист, который будет читать код, получил верное представление о том, что делает функция. -It is a widespread practice to start a function with a verbal prefix which vaguely describes the action. There must be an agreement within the team on the meaning of the prefixes. +Как правило, используются глагольные префиксы, обозначающие общий характер действия, после которых следует уточнение. Обычно в командах разработчиков действуют соглашения, касающиеся значений этих префиксов. -For instance, functions that start with `"show"` usually show something. +Например, функции, начинающиеся с `"show"` обычно что-то показывают. -Function starting with... +Функции, начинающиеся с... -- `"get…"` -- return a value, -- `"calc…"` -- calculate something, -- `"create…"` -- create something, -- `"check…"` -- check something and return a boolean, etc. +- `"get…"` -- возвращают значение, +- `"calc…"` -- что-то вычисляют, +- `"create…"` -- что-то создают, +- `"check…"` -- что-то проверяют и возвращают boolean, и т.д. -Examples of such names: +Примеры таких имён: ```js no-beautify -showMessage(..) // shows a message -getAge(..) // returns the age (gets it somehow) -calcSum(..) // calculates a sum and returns the result -createForm(..) // creates a form (and usually returns it) -checkPermission(..) // checks a permission, returns true/false +showMessage(..) // показывает сообщение +getAge(..) // возвращает возраст (в каком либо значении) +calcSum(..) // вычисляет сумму и возвращает результат +createForm(..) // создаёт форму (и обычно возвращает её) +checkPermission(..) // проверяет доступ, возвращая true/false ``` -With prefixes in place, a glance at a function name gives an understanding what kind of work it does and what kind of value it returns. +Благодаря префиксам, при первом взгляде на имя функции становится понятным что делает её код, и какое значение она может возвращать. -```smart header="One function -- one action" -A function should do exactly what is suggested by its name, no more. +```smart header="Одна функция -- одно действие" +Функция должна делать только то, что явно подразумевается её названием. И это должно быть одним действием. -Two independent actions usually deserve two functions, even if they are usually called together (in that case we can make a 3rd function that calls those two). +Два независимых действия обычно подразумевают две функции, даже если предполагается, что они будут вызываться вместе (в этом случае мы можем создать третью функцию, которая будет их вызвать). -A few examples of breaking this rule: +Несколько примеров, которые нарушают это правило: -- `getAge` -- would be bad if it shows an `alert` with the age (should only get). -- `createForm` -- would be bad if it modifies the document, adding a form to it (should only create it and return). -- `checkPermission` -- would be bad if it displays the `access granted/denied` message (should only perform the check and return the result). +- `getAge` -- будет плохим выбором, если функция будет выводить `alert` с возрастом (должна только возвращать его). +- `createForm` -- будет плохим выбором, если функция будет изменять document, добавляя форму в него (должна только создавать форму и возвращать её). +- `checkPermission` -- будет плохим выбором, если функция будет отображать сообщение с текстом `access granted/denied` (должна только выполнять проверку и возвращать её результат). -These examples assume common meanings of prefixes. What they mean for you is determined by you and your team. Maybe it's pretty normal for your code to behave differently. But you should have a firm understanding of what a prefix means, what a prefixed function can and cannot do. All same-prefixed functions should obey the rules. And the team should share the knowledge. +Эти примеры предполагают общие смыслы префиксов. Что они значат для вас определяете вы и команда разработчиков, частью которой вы являетесь. Совершенно нормальным, если в вашем коде они будут означать другое. Но вы должны твёрдо понимать, что означают префиксы имён, что функция с ним может делать, а что нет. Все одно-префиксные функции должны подчиняться одним правилам. И все разработчики в команде должны знать об этом. ``` -```smart header="Ultrashort function names" -Functions that are used *very often* sometimes have ultrashort names. +```smart header="Сверхкороткие имена функций" +Имена функций, которые используются *очень часто*, иногда делают сверхкороткими. -For example, the [jQuery](http://jquery.com) framework defines a function with `$`. The [LoDash](http://lodash.com/) library has its core function named `_`. +Например, во фреймворке [jQuery](http://jquery.com) есть функция с именем `$`. В библиотеке [Lodash](http://lodash.com/) основная функция представлена именем `_`. -These are exceptions. Generally functions names should be concise and descriptive. +Это исключения. В освновном имена функций должны быть краткими и описательными. ``` -## Functions == Comments +## Функции == Комментарии -Functions should be short and do exactly one thing. If that thing is big, maybe it's worth it to split the function into a few smaller functions. Sometimes following this rule may not be that easy, but it's definitely a good thing. +Функции должны быть короткими и делать в точности одну вещь. Если эта вещь большая, имеет смысл разбить функцию на несколько меньших. Иногда следовать этому правилу непросто, но это определённо хорошее правило. -A separate function is not only easier to test and debug -- its very existence is a great comment! +Небольшие функции не только облегчает тестирование и отладку -- само существование таких функций, выполняет роль хороших комментариев! -For instance, compare the two functions `showPrimes(n)` below. Each one outputs [prime numbers](https://en.wikipedia.org/wiki/Prime_number) up to `n`. +Например, сравним ниже две функции `showPrimes(n)`. Каждая из них выводит [простое число](https://ru.wikipedia.org/wiki/%D0%9F%D1%80%D0%BE%D1%81%D1%82%D0%BE%D0%B5_%D1%87%D0%B8%D1%81%D0%BB%D0%BE) до `n`. -The first variant uses a label: +Первый вариант использует метку `nextPrime`: ```js function showPrimes(n) { @@ -405,12 +405,12 @@ function showPrimes(n) { if (i % j == 0) continue nextPrime; } - alert( i ); // a prime + alert( i ); // простое } } ``` -The second variant uses an additional function `isPrime(n)` to test for primality: +Второй вариант использует дополнительную функцию `isPrime(n)` для проверки на простое: ```js function showPrimes(n) { @@ -418,7 +418,7 @@ function showPrimes(n) { for (let i = 2; i < n; i++) { *!*if (!isPrime(i)) continue;*/!* - alert(i); // a prime + alert(i); // простое } } @@ -430,13 +430,13 @@ function isPrime(n) { } ``` -The second variant is easier to understand, isn't it? Instead of the code piece we see a name of the action (`isPrime`). Sometimes people refer to such code as *self-describing*. +Второй вариант более лёгок для понимания, не правда ли? Вместо куска кода мы видим название действия (`isPrime`). Иногда разработчики назвают такой код *самодокументируемым кодом*. -So, functions can be created even if we don't intend to reuse them. They structure the code and make it readable. +Таким образом, допустимо создавать функции даже если мы не планируем переиспользовать их. Такие функции структурируют код и делают его более понятным. -## Summary +## Итого -A function declaration looks like this: +Объявление функции имеет вид: ```js function name(parameters, delimited, by, comma) { @@ -444,18 +444,18 @@ function name(parameters, delimited, by, comma) { } ``` -- Values passed to a function as parameters are copied to its local variables. -- A function may access outer variables. But it works only from inside out. The code outside of the function doesn't see its local variables. -- A function can return a value. If it doesn't, then its result is `undefined`. +- Передаваемые значения копируются в параметры функции и становятся локальными переменными. +- Функции имеют доступ к внешним переменным. Но это работает только в изнутри наружу. Код вне функции не имеет доступа к её локальным переменным. +- Функция может возвращать значение. Если этого не происходит, тогда результ равен `undefined`. -To make the code clean and easy to understand, it's recommended to use mainly local variables and parameters in the function, not outer variables. +Для того, чтобы сделать код более чистым и понятным, рекомендуется использовать локальные переменные и параметры функций, не пользоваться внешними переменными. -It is always easier to understand a function which gets parameters, works with them and returns a result than a function which gets no parameters, but modifies outer variables as a side-effect. +Функция, которая получает параметры, работает с ними и затем возвращает результат, гораздо понятней функции, вызываемой без параметров, но изменяющей внешние переменные, что черевато побочными эффектами. -Function naming: +Именование функций: -- A name should clearly describe what the function does. When we see a function call in the code, a good name instantly gives us an understanding what it does and returns. -- A function is an action, so function names are usually verbal. -- There exist many well-known function prefixes like `create…`, `show…`, `get…`, `check…` and so on. Use them to hint what a function does. +- Имя функции должно понятно и чётко отражать, что она делает. Увидев её вызов в коде, вы должны тут же понимать, что она делает, и что возвращает. +- Функция - это действие, поэтому её имя обычно является глаголом. +- Существует множество хорошо известных префиксов имён функций, таких как: `create…`, `show…`, `get…`, `check…` и т.д. Пользуйтесь ими как подсказками, поясняющими, что делает функция. -Functions are the main building blocks of scripts. Now we've covered the basics, so we actually can start creating and using them. But that's only the beginning of the path. We are going to return to them many times, going more deeply into their advanced features. +Функции являются основными строительными блоками скриптов. Мы рассмотрели лишь основы функций в JavaScript, но уже сейчас можем создавать и использовать их. Это только начало пути. Мы будем неоднократно возвращаться к функциям и изучать их все более и более глубоко.