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
There's another very simple and concise syntax for creating functions, that's often better than Function Expressions.
3
+
Има още един много лесен и кратък синтаксис за създаване на функции, който често е по-добър от функционалните изрази.
4
4
5
-
It's called "arrow functions", because it looks like this:
5
+
Нарича се "arrow functions" (функции със стрелки / стрелкови функции), защото изглежда така:
6
6
7
7
```js
8
8
letfunc= (arg1, arg2, ...argN) => expression
9
9
```
10
10
11
-
...This creates a function`func`that accepts arguments`arg1..argN`, then evaluates the `expression` on the right side with their use and returns its result.
11
+
...Този код създава функция`func`която приема аргументи`arg1..argN`, след това изчислява `израза` от дясната страна, който използва аргументите и връща резултат.
12
12
13
-
In other words, it's the shorter version of:
13
+
С други думи това е по-кратката версия на:
14
14
15
15
```js
16
16
letfunc=function(arg1, arg2, ...argN) {
17
17
return expression;
18
18
};
19
19
```
20
20
21
-
Let's see a concrete example:
21
+
Нека видим конкретен пример:
22
22
23
23
```js run
24
24
letsum= (a, b) => a + b;
25
25
26
-
/*This arrow function is a shorter form of:
26
+
/*Тази функция със стрелка е по-кратката версия на:
27
27
28
28
let sum = function(a, b) {
29
29
return a + b;
@@ -33,79 +33,79 @@ let sum = function(a, b) {
33
33
alert( sum(1, 2) ); // 3
34
34
```
35
35
36
-
As you can, see `(a, b) => a + b`means a function that accepts two arguments named `a`and`b`. Upon the execution, it evaluates the expression `a + b`and returns the result.
36
+
Както виждате `(a, b) => a + b`означава функция, която приема два аргумента именувани `a`и`b`. По време на изпълнението, тя изчислява израза `a + b`и връща резултата.
37
37
38
-
-If we have only one argument, then parentheses around parameters can be omitted, making that even shorter.
38
+
-Ако имаме само един аргумент, скобите около параметъра може да не се пишат. Така синтаксисът става дори още по-кратък.
39
39
40
-
For example:
40
+
Например:
41
41
42
42
```js run
43
43
*!*
44
44
letdouble=n=> n *2;
45
-
//roughly the same as: let double = function(n) { return n * 2 }
45
+
//почти същото като: let double = function(n) { return n * 2 }
46
46
*/!*
47
47
48
48
alert( double(3) ); // 6
49
49
```
50
50
51
-
-If there are no arguments, parentheses will be empty (but they should be present):
51
+
-Ако няма аргументи, скобите ще са празни (но те трябва да присъстват):
52
52
53
53
```js run
54
-
let sayHi = () => alert("Hello!");
54
+
let sayHi = () => alert("Здравейте!");
55
55
56
56
sayHi();
57
57
```
58
58
59
-
Arrow functions can be used in the same way as Function Expressions.
59
+
Функциите със стрелки могат да се използват по същия начин като функционалните изрази.
60
60
61
-
For instance, to dynamically create a function:
61
+
Например за да се създаде функция динамично:
62
62
63
63
```js run
64
-
let age = prompt("What is your age?", 18);
64
+
let age = prompt("На каква възраст сте?", 18);
65
65
66
66
let welcome = (age < 18) ?
67
-
() => alert('Hello') :
68
-
() => alert("Greetings!");
67
+
() => alert('Здравейте') :
68
+
() => alert("Поздравления!");
69
69
70
70
welcome(); // ok now
71
71
```
72
72
73
-
Arrow functions may appear unfamiliar and not very readable at first, but that quickly changes as the eyes get used to the structure.
73
+
Функциите със стрелки може да изглеждат непонятни и трудно четими на пръв поглед, но това бързо се променя щом се свикне със структурата им.
74
74
75
-
They are very convenient for simple one-line actions, when we're just too lazy to write many words.
75
+
Те са много удобни за прости едноредови действия, когато не искаме да пишем твърде много излишен код.
76
76
77
-
## Multiline arrow functions
77
+
## Многоредови функции със стрелки
78
78
79
-
The examples above took arguments from the left of `=>` and evaluated the right-side expression with them.
79
+
Горният пример взе аргументите от лявата страна на `=>`и ги използва за да изчисли израза от дясната страна.
80
80
81
-
Sometimes we need something a little bit more complex, like multiple expressions or statements. It is also possible, but we should enclose them in curly braces. Then use a normal `return` within them.
81
+
Понякога имаме нужда от малко по-сложен код, като множество изрази или инструкции. Това може да се направи, но трябва да ги поставим между къдрави скоби. След това трябва да използваме `return`вътре в скобите.
82
82
83
-
Like this:
83
+
Ето така:
84
84
85
85
```js run
86
-
let sum = (a, b) => { // the curly brace opens a multiline function
86
+
let sum = (a, b) => { // къдравата скоба отваря многоредова функция
87
87
let result = a + b;
88
88
*!*
89
-
return result; // if we use curly braces, then we need an explicit "return"
89
+
return result; // ако използваме къдрави скоби, тогава имаме нужда от експлицитен (ясен, изричен) "return"
90
90
*/!*
91
91
};
92
92
93
93
alert( sum(1, 2) ); // 3
94
94
```
95
95
96
-
```smart header="More to come"
97
-
Here we praised arrow functions for brevity. But that's not all!
96
+
```smart header="Следва още"
97
+
Тук възхвалявахме функциите със стрелки заради тяхната краткост. Но това не е всичко!
98
98
99
-
Arrow functions have other interesting features.
99
+
Функциите със стрелки имат и други интересни свойства.
100
100
101
-
To study them in-depth, we first need to get to know some other aspects ofJavaScript, so we'll return to arrow functions later in the chapter <info:arrow-functions>.
101
+
За да ги изучим в дълбочина, първо трябва да опознаем някои други аспекти на JavaScript, така че ще се върнем към тези функции по-късно в глава <info:arrow-functions>.
102
102
103
-
For now, we can already use arrow functions for one-line actions and callbacks.
103
+
За сега вече можем да използваме функциите със стрелки за едноредови действия и callbacks (обратно извикване).
104
104
```
105
105
106
-
## Summary
106
+
## Обобщение
107
107
108
-
Arrow functions are handy for one-liners. They come in two flavors:
108
+
Функциите със стрелки са полезни за едноредови действия. Те могат да бъдат два вида:
109
109
110
-
1. Without curly braces: `(...args) => expression` -- the right side is an expression: the function evaluates it and returns the result.
111
-
2. With curly braces: `(...args) => { body }` -- brackets allow us to write multiple statements inside the function, but we need an explicit `return` to return something.
110
+
1.Без къдрави скоби:`(...args) => expression`--дясната страна е израз: функцията го изчислява и връща резултата.
111
+
2.С къдрави скоби:`(...args) => { body }`--скобите ни позволяват да пишем множество инструкции в една функция, но трябва изрично да ползваме`return`, за да върнем резултат.
0 commit comments