You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In JavaScript a function is a value. Just like a string or a number.
3
+
Function Expression is analternative syntax for creating a function.
4
4
5
-
Let's output it using `alert`:
5
+
It looks like this:
6
6
7
7
```js
8
8
//+ run
9
+
letfunc=function(parameters) {
10
+
// body
11
+
};
12
+
```
13
+
14
+
For instance:
15
+
16
+
```js
17
+
//+ run
18
+
letsayHi=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
+
functionsayHi(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
9
42
functionsayHi() {
10
43
alert( "Hello" );
11
44
}
45
+
```
12
46
13
-
*!*
14
-
alert( sayHi ); // shows the function code
15
-
*/!*
47
+
...Or as a function expression:
48
+
49
+
```js
50
+
letsayHi=function() {
51
+
alert( "Hello" );
52
+
}
16
53
```
17
54
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`.
19
56
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.
21
58
22
-
[cut]
59
+
We can even show it using `alert`:
23
60
61
+
```js
62
+
//+ run
63
+
functionsayHi() {
64
+
alert( "Hello" );
65
+
}
66
+
67
+
*!*
68
+
alert( sayHi ); // shows the function code
69
+
*/!*
70
+
```
24
71
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:
26
75
27
76
```js
28
77
//+ run no-beautify
29
-
functionsayHi() { // (1)
78
+
functionsayHi() { // (1) create
30
79
alert( "Hello" );
31
80
}
32
81
33
-
let func = sayHi; // (2)
34
-
func(); // Hello // (3)
82
+
let func = sayHi; // (2) copy
83
+
func(); // Hello // (3) callable!
35
84
36
-
sayHi =null; // (4)
37
-
sayHi(); // error
85
+
sayHi =null; // (4) kill old
86
+
sayHi(); // error! (null now)
38
87
```
39
88
40
89
<ol>
@@ -46,54 +95,24 @@ Please note again: there are no brackets after `sayHi`. If they were, then the c
46
95
<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>
47
96
</ol>
48
97
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\""]
50
101
Regular values like strings or numbers represent the *data*.
51
102
52
103
A function can be perceived as an *action*.
53
104
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.
55
106
[/smart]
56
107
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
-
letfunc=function(parameters) {
66
-
// body
67
-
};
68
-
```
69
-
70
-
For instance:
71
-
72
-
```js
73
-
//+ run
74
-
letsayHi=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
-
functionsayHi(person) {
85
-
alert( `Hello, ${person}` );
86
-
}
87
-
```
88
-
89
108
90
109
## Comparison with Function Declaration
91
110
92
111
The "classic" syntax of the function that looks like `function name(params) {...}` is called a "Function Declaration".
93
112
94
113
We can formulate the following distinction:
95
114
<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.
97
116
98
117
```js
99
118
// Function Declaration
@@ -103,24 +122,29 @@ function sum(a, b) {
103
122
```
104
123
105
124
</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.
107
126
127
+
Here the function is created to the right side of an assignment:
108
128
```js
109
129
// Function Expression
110
130
letsum=function(a, b) {
111
131
return a + b;
112
132
}
113
133
```
134
+
Soon we're going to see more use cases.
114
135
</li>
115
136
</ul>
116
137
117
138
The main difference between them is the creation time.
118
139
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>
120
144
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.
122
146
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.
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 `(*)`.
154
176
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.
156
178
157
179
## Anonymous functions
158
180
159
181
As a function is a value, it can be created on-demand and passed to another place of the code.
160
182
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.
162
184
163
185
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()`.
164
186
@@ -171,7 +193,7 @@ function ask(question, yes, no) {
171
193
}
172
194
```
173
195
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.
175
197
176
198
So, how do we use it?
177
199
@@ -200,79 +222,31 @@ ask("Should we proceed?",
200
222
);
201
223
```
202
224
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.
206
226
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.
208
228
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.
210
230
211
-
## new Function
212
-
213
-
Существует ещё один способ создания функции, который используется очень редко, но упомянем и его для полноты картины.
214
-
215
-
Он позволяет создавать функцию полностью "на лету" из строки, вот так:
216
-
217
-
```js
218
-
//+ run
219
-
let sum =newFunction('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
240
232
241
233
<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>
244
243
</ul>
245
244
246
-
Между этими двумя основными способами создания функций есть следующие различия:
247
-
248
-
<tableclass="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:
276
250
277
251
```js
278
252
//+ no-beautify
@@ -283,6 +257,7 @@ let f = function() { ... }
283
257
functionf() { ... }
284
258
```
285
259
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.
287
263
288
-
Используйте Function Expression только там, где это действительно нужно и удобно.
0 commit comments