Skip to content

1-js/02-first-steps/14-function-basics#148

Merged
iliakan merged 21 commits intojavascript-tutorial:masterfrom
dandgerson:1-js/02-first-steps/14-function-basics
May 14, 2019
Merged

1-js/02-first-steps/14-function-basics#148
iliakan merged 21 commits intojavascript-tutorial:masterfrom
dandgerson:1-js/02-first-steps/14-function-basics

Conversation

@dandgerson
Copy link
Member

Пересоздал PR. т.к. по ошибке вмёржил в мастер без апрува, и прежний откатили

@javascript-translate-bot javascript-translate-bot added the review needed Review needed, please approve or request changes label May 5, 2019
Copy link
Member

@lex111 lex111 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ревью было сделано в #106

@javascript-translate-bot javascript-translate-bot added needs +1 One more review needed and removed review needed Review needed, please approve or request changes labels May 6, 2019
Copy link
Member

@iliakan iliakan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Пожалуйста, внеси изменения. Спасибо!

Следующая функция возвращает `true`, если параметр `age` больше `18`.

Otherwise it asks for a confirmation and returns its result:
В ином случае она задаёт вопрос посредством вызова `confirm` и возвращает его результат:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В ином случае она запрашивает подтверждение через confirm и возвращает его результат:

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

готово

```

Note that the parentheses around `age > 18` are not required here. They exist for better readabilty.
Обратите внимание, что круглые скобки вокруг `age > 18` не обязательны. Их наличие необходимо для более лучшего понимания.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Они здесь для лучшей читаемости кода.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

готово

```

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` не имеет значения, что вернёт функция.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

, что возвращать

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

готово

```

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`, после него *имя функции*, затем список *параметров* в круглых скобках (в примере выше он пустой) и, наконец, код функции, называемый "телом функции", расположенный внутри фигурных скобок.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

, также называемый "телом функции", внутри фигурных скобок

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

готово

```

The outer variable is only used if there's no local one. So an occasional modification may happen if we forget `let`.
Внешние переменные используются только если в теле функции нет локальных. Это случается, если мы забываем объявить их с помощью ключевого слова `let`.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Внешняя переменная используется только если внутри функции нет такой локальной. (второе предложение удали плиз)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

готово

- `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.
Эти примеры предполагают общие смыслы префиксов. Что они значат для вас определяете вы и команда разработчиков, частью которой вы являетесь. Совершенно нормальным, если в вашем коде они будут означать другое. Но вы должны твёрдо понимать, что означают префиксы имён, что функция с ним может делать, а что нет. Все одно-префиксные функции должны подчиняться одним правилам. И все разработчики в команде должны знать об этом.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В этих примерах использовались общепринятые смыслы префиксов. Конечно, вы в команде можете принять и другие значения, но обычно они мало отличаются от общепринятых. В любом случае вы и ваша команда должны точно понимать, что значит префикс, что функция с ним может делать, а что нет.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

готово

Функции должны быть короткими и делать только что-то одно. Если это что-то большое, имеет смысл разбить функцию на несколько меньших. Иногда следовать этому правилу непросто, но это определённо хорошее правило.

A separate function is not only easier to test and debug -- its very existence is a great comment!
Небольшие функции не только облегчает тестирование и отладку -- само существование таких функций, выполняет роль хороших комментариев!
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

последняя зпт лишняя

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

готово

```

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`). Иногда разработчики называют такой код *самодокументируемым*.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

легче

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

готово

- 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`.
- Передаваемые значения копируются в параметры функции и становятся локальными переменными.
- Функции имеют доступ к внешним переменным. Но это работает только в изнутри наружу. Код вне функции не имеет доступа к её локальным переменным.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

только изнутри

- 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…` и т.д. Пользуйтесь ими как подсказками, поясняющими, что делает функция.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Есть много общепринятых префиксов, таких как: ... Желательно их использовать.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

готово

@javascript-translate-bot javascript-translate-bot added the changes requested Waiting for changes and /done from PR author label May 9, 2019
@javascript-translate-bot
Copy link
Contributor

Please make the requested changes. After it, add a comment "/done".
Then I'll ask for a new review 👻

@dandgerson
Copy link
Member Author

/done

@javascript-translate-bot javascript-translate-bot added review needed Review needed, please approve or request changes and removed changes requested Waiting for changes and /done from PR author labels May 14, 2019
@javascript-translate-bot javascript-translate-bot requested a review from a team May 14, 2019 15:01
@dandgerson
Copy link
Member Author

dandgerson commented May 14, 2019

Благодарю за внимательные правки. Илья, ваш стиль ревью немного отличается, от стиля Алексея. Нужно ли мне называть коммиты более подробно для каждой правки, для очевидности к какой правке они относятся? Например: update article -> update article: line 459

@iliakan
Copy link
Member

iliakan commented May 14, 2019

не нужно, все равно при просмотре изменений я не вижу описания коммитов

@iliakan
Copy link
Member

iliakan commented May 14, 2019

🚀

@iliakan iliakan merged commit 3ef6082 into javascript-tutorial:master May 14, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs +1 One more review needed review needed Review needed, please approve or request changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants