diff --git a/1-js/02-first-steps/02-structure/article.md b/1-js/02-first-steps/02-structure/article.md index b18aab19e4..1b859053ee 100644 --- a/1-js/02-first-steps/02-structure/article.md +++ b/1-js/02-first-steps/02-structure/article.md @@ -1,44 +1,44 @@ -# Code structure +# Структура кода -The first thing we'll study is the building blocks of code. +Сначала рассмотрим основные "строительные блоки" кода. -## Statements +## Инструкции -Statements are syntax constructs and commands that perform actions. +Инструкции -- это синтаксические конструкции и команды, которые выполняют действия. -We've already seen a statement, `alert('Hello, world!')`, which shows the message "Hello, world!". +Мы уже видели инструкцию, `alert('Hello, world!')`, которая отображает сообщение "Привет, мир!". -We can have as many statements in our code as we want. Statements can be separated with a semicolon. +В нашем коде может быть столько инструкций, сколько мы захотим. Инструкции могут отделяться точкой с запятой. -For example, here we split "Hello World" into two alerts: +Например, здесь мы разделили сообщение "Привет Мир" на два вызова alert: ```js run no-beautify -alert('Hello'); alert('World'); +alert('Привет'); alert('Мир'); ``` -Usually, statements are written on separate lines to make the code more readable: +Обычно, каждую инструкцию пишут на новой строке, чтобы код было легче читать: ```js run no-beautify -alert('Hello'); -alert('World'); +alert('Привет'); +alert('Мир'); ``` -## Semicolons [#semicolon] +## Точка с запятой [#semicolon] -A semicolon may be omitted in most cases when a line break exists. +В большинстве случаев точку с запятой можно опустить, если есть переход на новую строку. -This would also work: +Так тоже будет работать: ```js run no-beautify -alert('Hello') -alert('World') +alert('Привет') +alert('Мир') ``` -Here, JavaScript interprets the line break as an "implicit" semicolon. This is called an [automatic semicolon insertion](https://tc39.github.io/ecma262/#sec-automatic-semicolon-insertion). +В этом случае JavaScript интерпретирует перенос строки как "неявную" точку с запятой. Это называется [автоматическая вставка точки с запятой](https://tc39.github.io/ecma262/#sec-automatic-semicolon-insertion). -**In most cases, a newline implies a semicolon. But "in most cases" does not mean "always"!** +**В большинстве случаев новая строка подразумевает точку с запятой. Но "в большинстве случаев" не значит "всегда"!** -There are cases when a newline does not mean a semicolon. For example: +В некоторых ситуациях новая строка не означает точку с запятой. Например: ```js run no-beautify alert(3 + @@ -46,114 +46,114 @@ alert(3 + + 2); ``` -The code outputs `6` because JavaScript does not insert semicolons here. It is intuitively obvious that if the line ends with a plus `"+"`, then it is an "incomplete expression", so the semicolon is not required. And in this case that works as intended. +Код выведет `6` потому что JavaScript не вставляет здесь точку с запятой. Интуитивно очевидно, что если строка заканчивается знаком `"+"`, значит это "незавершенное выражение", поэтому точка с запятой не требуется. И в этом случае всё работает как задумано. -**But there are situations where JavaScript "fails" to assume a semicolon where it is really needed.** +**Но есть ситуации, где JavaScript "забывает" вставить точку с запятой там, где она нужна.** -Errors which occur in such cases are quite hard to find and fix. +Ошибки, которые при этом появляются, достаточно сложно обнаруживать и исправлять. -````smart header="An example of an error" -If you're curious to see a concrete example of such an error, check this code out: +````smart header="Пример ошибки" +Если вы хотите увидеть конкретный пример такой ошибки, обратите внимание на этот код: ```js run [1, 2].forEach(alert) ``` -No need to think about the meaning of the brackets `[]` and `forEach` yet. We'll study them later. For now, just remember the result of the code: it shows `1` then `2`. +Пока нет необходимости знать значение скобок `[]` и `forEach`. Мы изучим их позже. Пока что, просто запомните результат выполнения этого кода: выводится `1`, а затем `2`. -Now, let's add an `alert` before the code and *not* finish it with a semicolon: +А теперь добавим `alert` перед кодом и *не* поставим в конце точку с запятой: ```js run no-beautify -alert("There will be an error") +alert("Сейчас будет ошибка") [1, 2].forEach(alert) ``` -Now if we run the code, only the first `alert` is shown and then we have an error! +Теперь, если запустить код, выведется только первый `alert`, а затем мы получим ошибку! -But everything is fine again if we add a semicolon after `alert`: +Всё исправится, если мы поставим точку с запятой после `alert`: ```js run -alert("All fine now"); +alert("Теперь всё в порядке"); [1, 2].forEach(alert) ``` -Now we have the "All fine now" message followed by `1` and `2`. +Теперь мы получим сообщение "Теперь всё в порядке", следом за которым будут `1` и `2`. -The error in the no-semicolon variant occurs because JavaScript does not assume a semicolon before square brackets `[...]`. +В первом примере без точки с запятой возникает ошибка, потому что JavaScript не вставляет точку с запятой перед квадратными скобками `[...]`. -So, because the semicolon is not auto-inserted, the code in the first example is treated as a single statement. Here's how the engine sees it: +Итак, поскольку точка с запятой не вставляется автоматически, код в первом примере выполняется как одна инструкция. Вот как движок видит его: ```js run no-beautify -alert("There will be an error")[1, 2].forEach(alert) +alert("Сейчас будет ошибка")[1, 2].forEach(alert) ``` -But it should be two separate statements, not one. Such a merging in this case is just wrong, hence the error. This can happen in other situations. +Но это должны быть две отдельные инструкции, а не одна. Такое слияние, в данном случае, неправильное, от того и ошибка. Это может произойти и в некоторых других ситуациях. ```` -We recommend putting semicolons between statements even if they are separated by newlines. This rule is widely adopted by the community. Let's note once again -- *it is possible* to leave out semicolons most of the time. But it's safer -- especially for a beginner -- to use them. +Мы рекомендуем ставить точку с запятой между инструкциями, даже если они отделены переносами строк. Это правило широко используется в сообществе разработчиков. Стоит отметить ещё раз -- в большинстве случаев *можно* опускать точку с запятой. Но безопаснее -- особенно для новичка -- использовать их. -## Comments +## Комментарии -As time goes on, programs become more and more complex. It becomes necessary to add *comments* which describe what the code does and why. +Со временем программы становятся всё сложнее и сложнее. Возникает необходимость добавлять *комментарии*, которые бы описывали что делает код и почему. -Comments can be put into any place of a script. They don't affect its execution because the engine simply ignores them. +Комментарии могут находиться в любом месте скрипта. Они не влияют на его выполнение, поскольку движок просто игнорирует их. -**One-line comments start with two forward slash characters `//`.** +**Однострочные комментарии начинаются с двойной косой черты `//`.** -The rest of the line is a comment. It may occupy a full line of its own or follow a statement. +Часть строки после `//` считается комментарием. Такой комментарий может как занимать строку целиком, так и находиться после инструкции. Like here: ```js run -// This comment occupies a line of its own -alert('Hello'); +// Этот комментарий занимает всю строку +alert('Привет'); -alert('World'); // This comment follows the statement +alert('Мир'); // Этот комментарий следует за инструкцией ``` -**Multiline comments start with a forward slash and an asterisk /* and end with an asterisk and a forward slash */.** +**Многострочные комментарии начинаются косой чертой со звёздочкой /* и заканчиваются звёздочкой с косой чертой */.** -Like this: +Как вот здесь: ```js run -/* An example with two messages. -This is a multiline comment. +/* Пример с двумя сообщениями. +Это - многострочный комментарий. */ -alert('Hello'); -alert('World'); +alert('Привет'); +alert('Мир'); ``` -The content of comments is ignored, so if we put code inside /* ... */, it won't execute. +Содержимое комментария игнорируется, поэтому, если мы поместим внутри код /* ... */, он не будет исполняться. -Sometimes it can be handy to temporarily disable a part of code: +Это бывает удобно для временного отключения участка кода: ```js run -/* Commenting out the code -alert('Hello'); +/* Закомментировали код +alert('Привет'); */ -alert('World'); +alert('Мир'); ``` -```smart header="Use hotkeys!" -In most editors, a line of code can be commented out by pressing the `key:Ctrl+/` hotkey for a single-line comment and something like `key:Ctrl+Shift+/` -- for multiline comments (select a piece of code and press the hotkey). For Mac, try `key:Cmd` instead of `key:Ctrl`. +```smart header="Используйте горячие клавиши!" +В большинстве редакторов строку кода можно закомментировать, нажав комбинацию клавиш `key:Ctrl+/` для однострочного комментария и что-то вроде `key:Ctrl+Shift+/` -- для многострочных комментариев (выделите кусок кода и нажмите комбинацию клавиш). В системе Mac попробуйте `key:Cmd` вместо `key:Ctrl`. ``` -````warn header="Nested comments are not supported!" -There may not be `/*...*/` inside another `/*...*/`. +````warn header="Вложенные комментарии не поддерживаются!" +Не может быть `/*...*/` внутри `/*...*/`. -Such code will die with an error: +Такой код "умрёт" с ошибкой: ```js run no-beautify /* - /* nested comment ?!? */ + /* вложенный комментарий ?!? */ */ -alert( 'World' ); +alert( 'Мир' ); ``` ```` -Please, don't hesitate to comment your code. +Не стесняйтесь использовать комментарии в своём коде. -Comments increase the overall code footprint, but that's not a problem at all. There are many tools which minify code before publishing to a production server. They remove comments, so they don't appear in the working scripts. Therefore, comments do not have negative effects on production at all. +Комментарии увеличивают размер кода, но это не проблема. Есть множество инструментов, которые минифицируют код перед публикацией на рабочий сервер. Они убирают комментарии, так что они не содержатся в рабочих скриптах. Таким образом, комментарии никаким образом не вредят рабочему коду. -Later in the tutorial there will be a chapter that also explains how to write better comments. +Позже в учебнике будет глава , которая объяснит, как лучше писать комментарии.