Skip to content

Commit 6fd7a2f

Browse files
committed
en
1 parent 547854a commit 6fd7a2f

File tree

2 files changed

+103
-128
lines changed

2 files changed

+103
-128
lines changed

1-js/2-first-steps/18-function-basics/article.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Functions
1+
# Function basics
22

33
Quite often we need to perform a similar action in many places of the script.
44

Lines changed: 102 additions & 127 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,89 @@
11
# Function expressions
22

3-
In JavaScript a function is a value. Just like a string or a number.
3+
Function Expression is analternative syntax for creating a function.
44

5-
Let's output it using `alert`:
5+
It looks like this:
66

77
```js
88
//+ run
9+
let func = function(parameters) {
10+
// body
11+
};
12+
```
13+
14+
For instance:
15+
16+
```js
17+
//+ run
18+
let sayHi = function(person) {
19+
alert( `Hello, ${person}` );
20+
};
21+
22+
sayHi('John'); // Hello, John
23+
```
24+
25+
The function created in the example above is fully functional and identical to:
26+
27+
```js
28+
function sayHi(person) {
29+
alert( `Hello, ${person}` );
30+
}
31+
```
32+
33+
## Function is a value
34+
35+
Function Expressions clearly demonstrate one simple thing.
36+
37+
**In JavaScript, function is a kind of a value.**
38+
39+
We can declare it as we did before:
40+
41+
```js
942
function sayHi() {
1043
alert( "Hello" );
1144
}
45+
```
1246

13-
*!*
14-
alert( sayHi ); // shows the function code
15-
*/!*
47+
...Or as a function expression:
48+
49+
```js
50+
let sayHi = function() {
51+
alert( "Hello" );
52+
}
1653
```
1754

18-
Note that there are no brackets after `sayHi` in the last line. The function is not called there.
55+
The meaning of these lines is the same: create a function, put it into the variable `sayHi`.
1956

20-
The code above only shows the string representation of the function, that is it's source code.
57+
Yes, no matter, how it is defined -- it's just a value.
2158

22-
[cut]
59+
We can even show it using `alert`:
2360

61+
```js
62+
//+ run
63+
function sayHi() {
64+
alert( "Hello" );
65+
}
66+
67+
*!*
68+
alert( sayHi ); // shows the function code
69+
*/!*
70+
```
2471

25-
As the function is a value, we can copy it to another variable:
72+
Note that there are no brackets after `sayHi` in the last line. The function is not called there. Instead the `alert` shows it's string representation, that is the source code.
73+
74+
As the function is a value, we can also copy it to another variable:
2675

2776
```js
2877
//+ run no-beautify
29-
function sayHi() { // (1)
78+
function sayHi() { // (1) create
3079
alert( "Hello" );
3180
}
3281

33-
let func = sayHi; // (2)
34-
func(); // Hello // (3)
82+
let func = sayHi; // (2) copy
83+
func(); // Hello // (3) callable!
3584

36-
sayHi = null; // (4)
37-
sayHi(); // error
85+
sayHi = null; // (4) kill old
86+
sayHi(); // error! (null now)
3887
```
3988

4089
<ol>
@@ -46,54 +95,24 @@ Please note again: there are no brackets after `sayHi`. If they were, then the c
4695
<li>...We can overwrite `sayHi` easily. As well as `func`, they are normal variables. Naturally, the call attempt would fail in the case `(4)`.</li>
4796
</ol>
4897

49-
[smart header="A function is an \"action value\""]
98+
Again, it does not matter how to create a function here. If we change the first line above into a Function Expression: `let sayHi = function() {`, everything would be the same.
99+
100+
[smart header="A function is a value representing an \"action\""]
50101
Regular values like strings or numbers represent the *data*.
51102

52103
A function can be perceived as an *action*.
53104

54-
A function declaration creates that action and puts it into a variable of the given name. Then we can run it via brackets `()` or copy into another variable.
105+
We can copy it between variables and run when we want.
55106
[/smart]
56107

57-
## Function Expression [#function-expression]
58-
59-
There is an alternative syntax for creating a function. It much more clearly shows that a function is just a kind of a value.
60-
61-
It is called "Function Expression" and looks like this:
62-
63-
```js
64-
//+ run
65-
let func = function(parameters) {
66-
// body
67-
};
68-
```
69-
70-
For instance:
71-
72-
```js
73-
//+ run
74-
let sayHi = function(person) {
75-
alert( `Hello, ${person}` );
76-
};
77-
78-
sayHi('John'); // Hello, John
79-
```
80-
81-
The function created in the example above is fully functional and identical to:
82-
83-
```js
84-
function sayHi(person) {
85-
alert( `Hello, ${person}` );
86-
}
87-
```
88-
89108

90109
## Comparison with Function Declaration
91110

92111
The "classic" syntax of the function that looks like `function name(params) {...}` is called a "Function Declaration".
93112

94113
We can formulate the following distinction:
95114
<ul>
96-
<li>*Function Declaration* -- is a function, declared as a separate code statement.
115+
<li>*Function Declaration* -- is a function, declared as a separate statement.
97116

98117
```js
99118
// Function Declaration
@@ -103,24 +122,29 @@ function sum(a, b) {
103122
```
104123

105124
</li>
106-
<li>*Function Expression* -- is a function, created in the context of an another expression, for example, an assignment.
125+
<li>*Function Expression* -- is a function, created anywhere inside an expression.
107126

127+
Here the function is created to the right side of an assignment:
108128
```js
109129
// Function Expression
110130
let sum = function(a, b) {
111131
return a + b;
112132
}
113133
```
134+
Soon we're going to see more use cases.
114135
</li>
115136
</ul>
116137

117138
The main difference between them is the creation time.
118139

119-
**Function Declarations are processed before the code begins to execute.**
140+
<ul>
141+
<li>Function Declarations are processed before the code begins to execute.</li>
142+
<li>Function Expressions are created when the execution reaches them.</li>
143+
</ul>
120144

121-
In other words, when JavaScript prepares to run the code block, it looks for Function Declarations in it and creates the functions. We can think of it as an "initialization stage". Then it runs the code.
145+
In other words, when JavaScript prepares to run the code block, it looks for Function Declarations in it and creates the functions. We can think of it as an "initialization stage". Then it runs the code. And while the code is running, Function Expressions can be created.
122146

123-
As a side-effect, functions declared as Function Declaration can be called before they are defined.
147+
As a side-effect, functions declared as Function Declaration can be called earlier than they are defined.
124148

125149
For instance, this works:
126150

@@ -148,17 +172,15 @@ let sayHi = function(name) { // (*)
148172
};
149173
```
150174

151-
Function Expressions are created in the process of evaluation of the expression with them.
152-
153-
So, in the code above, the function is created and assigned to sayHi only when the execution reaches line `(*)`.
175+
Function Expressions are created in the process of evaluation of the expression with them. So, in the code above, the function is created and assigned to `sayHi` only when the execution reaches the line `(*)`.
154176

155-
Usually this is viewed as a bonus of the Function Declaration. Convenient, isn't it? Gives more freedom in how to organize our code.
177+
Usually, a Function Declaration is preferable because of that. It gives more freedom in how to organize our code.
156178

157179
## Anonymous functions
158180

159181
As a function is a value, it can be created on-demand and passed to another place of the code.
160182

161-
For instance, let's consider the following task, coming from a real-life.
183+
For instance, let's consider the following real-life task.
162184

163185
Function `ask(question, yes, no)` should accept a question and two other functions: `yes` and `no`. It asks a question and, if the user responds positively, executes `yes()`, otherwise `no()`.
164186

@@ -171,7 +193,7 @@ function ask(question, yes, no) {
171193
}
172194
```
173195

174-
In real-life `ask` is usually much more complex. It draws a nice windows instead of the simple `confirm` to ask a question. But that would make it much longer, so here we skip this part.
196+
In real-life `ask` will be usually much more complex, because it draws a nice windows and takes care about how to preent the `question` to the user, but here we don't care about that. Just `confirm` is enough.
175197

176198
So, how do we use it?
177199

@@ -200,79 +222,31 @@ ask("Should we proceed?",
200222
);
201223
```
202224

203-
So, we can declare a function in-place, right when we need it.
204-
205-
Such functions are sometimes called "anonymous" meaning that they are defined without a name.
225+
So, we can declare a function in-place, exactly when we need it.
206226

207-
And here, if we don't plan to call the function again, why should we give it a name? Let's just declare it where needed and pass on.
227+
These functions are sometimes called "anonymous" meaning that they are defined without a name. So to say, we can't reuse this function anywhere outside of `ask`. And that's fine here.
208228

209-
That's very natural and in the spirit of JavaScript.
229+
Creating functions in-place is very natural and in the spirit of JavaScript.
210230

211-
## new Function
212-
213-
Существует ещё один способ создания функции, который используется очень редко, но упомянем и его для полноты картины.
214-
215-
Он позволяет создавать функцию полностью "на лету" из строки, вот так:
216-
217-
```js
218-
//+ run
219-
let sum = new Function('a,b', ' return a+b; ');
220-
221-
let result = sum(1, 2);
222-
alert( result ); // 3
223-
```
224-
225-
То есть, функция создаётся вызовом `new Function(params, code)`:
226-
<dl>
227-
<dt>`params`</dt>
228-
<dd>Параметры функции через запятую в виде строки.</dd>
229-
<dt>`code`</dt>
230-
<dd>Код функции в виде строки.</dd>
231-
</dl>
232-
233-
Таким образом можно конструировать функцию, код которой неизвестен на момент написания программы, но строка с ним генерируется или подгружается динамически во время её выполнения.
234-
235-
Пример использования -- динамическая компиляция шаблонов на JavaScript, мы встретимся с ней позже, при работе с интерфейсами.
236-
237-
## Итого
238-
239-
Функции в JavaScript являются значениями. Их можно присваивать, передавать, создавать в любом месте кода.
231+
## Summary
240232

241233
<ul>
242-
<li>Если функция объявлена в *основном потоке кода*, то это Function Declaration.</li>
243-
<li>Если функция создана как *часть выражения*, то это Function Expression.</li>
234+
<li>
235+
Functions are values. They can be assigned, copied or declared in any place of the code.
236+
<ul>
237+
<li>If the function is declared as a separate statement -- it's called a Function Declaration.</li>
238+
<li>If the function is created as a part of an expression -- it's a Function Expression.</li>
239+
</ul>
240+
</li>
241+
<li>Function Declarations are processed before the code is executed. JavaScript scans the code, looks for them and creates corresponding functions.</li>
242+
<li>Function Expressions are created when the execution flow reaches them.</li>
244243
</ul>
245244

246-
Между этими двумя основными способами создания функций есть следующие различия:
247-
248-
<table class="table-bordered">
249-
<tr>
250-
<th></th>
251-
<th>Function Declaration</th>
252-
<th>Function Expression</th>
253-
</tr>
254-
<tr>
255-
<td>Время создания</td>
256-
<td>До выполнения первой строчки кода.</td>
257-
<td>Когда управление достигает строки с функцией.</td>
258-
</tr>
259-
<tr>
260-
<td>Можно вызвать до объявления </td>
261-
<td>`Да` (т.к. создаётся заранее)</td>
262-
<td>`Нет`</td>
263-
</tr>
264-
<tr>
265-
<td>Условное объявление в `if`</td>
266-
<td>`Не работает`</td>
267-
<td>`Работает`</td>
268-
</tr>
269-
</table>
270-
271-
Иногда в коде начинающих разработчиков можно увидеть много Function Expression. Почему-то, видимо, не очень понимая происходящее, функции решают создавать как `let func = function()`, но в большинстве случаев обычное объявление функции -- лучше.
272-
273-
**Если нет явной причины использовать Function Expression -- предпочитайте Function Declaration.**
274-
275-
Сравните по читаемости:
245+
Novice programmers sometimes overuse Function Expressions. Somewhy, maybe not quite understanding what's going on, they create functions like `let func = function()`.
246+
247+
But in most cases Function Declaration is preferable.
248+
249+
Compare, which one is more readable:
276250

277251
```js
278252
//+ no-beautify
@@ -283,6 +257,7 @@ let f = function() { ... }
283257
function f() { ... }
284258
```
285259

286-
Function Declaration короче и лучше читается. Дополнительный бонус -- такие функции можно вызывать до того, как они объявлены.
260+
Function Declaration is shorter and more obvious. The additional bonus -- it can be called before the declaration.
261+
262+
Use Function Expression only when the function must be created at-place, inside another expression.
287263

288-
Используйте Function Expression только там, где это действительно нужно и удобно.

0 commit comments

Comments
 (0)