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
+
Hay otra sintaxis muy simple y concisa para crear funciones, que a menudo es mejor que las Expresiones de funciones.
4
4
5
-
It's called "arrow functions", because it looks like this:
5
+
Se llama "funciones de flecha", porque se ve así:
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
+
...Esto crea una función`func`que acepta parámetros`arg1..argN`, luego evalúa la`expression`de la derecha con su uso y devuelve su resultado.
12
12
13
-
In other words, it's the shorter version of:
13
+
En otras palabras, es la versión más corta de:
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
+
Veamos un ejemplo concreto:
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
+
/*Esta función de flecha es una forma más corta de:
27
27
28
28
let sum = function(a, b) {
29
29
return a + b;
@@ -33,32 +33,32 @@ 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
+
Como puedes ver `(a, b) => a + b`significa una función que acepta dos parámetros llamados`a`y`b`. Tras la ejecución, evalúa la expresión `a + b`y devuelve el resultado.
37
37
38
-
-If we have only one argument, then parentheses around parameters can be omitted, making that even shorter.
38
+
-Si solo tenemos un argumento, se pueden omitir paréntesis alrededor de los parámetros, lo que lo hace aún más corto.
39
39
40
-
For example:
40
+
Por ejemplo:
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
+
//Más o menos lo mismo que: 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
+
-Si no hay parámetros, los paréntesis estarán vacíos (pero deberían estar presentes):
52
52
53
53
```js run
54
54
let sayHi = () => alert("Hello!");
55
55
56
56
sayHi();
57
57
```
58
58
59
-
Arrow functions can be used in the same way as Function Expressions.
59
+
Las funciones de flecha se pueden usar de la misma manera que las expresiones de función.
60
60
61
-
For instance, to dynamically create a function:
61
+
Por ejemplo, para crear dinámicamente una función:
62
62
63
63
```js run
64
64
let age = prompt("What is your age?", 18);
@@ -70,42 +70,42 @@ let welcome = (age < 18) ?
70
70
welcome();
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
+
Las funciones de flecha pueden parecer desconocidas y poco legibles al principio, pero eso cambia rápidamente a medida que los ojos se acostumbran a la estructura.
74
74
75
-
They are very convenient for simple one-line actions, when we're just too lazy to write many words.
75
+
Son muy convenientes para acciones simples de una línea, cuando somos demasiado flojos para escribir muchas palabras.
76
76
77
-
## Multiline arrow functions
77
+
## Funciones de flecha multilínea
78
78
79
-
The examples above took arguments from the left of `=>` and evaluated the right-side expression with them.
79
+
Los ejemplos anteriores tomaron parámetros de la izquierda de`=>`y evaluaron el lado derecho de la expressión con ellos.
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
+
A veces necesitamos algo un poco más complejo, como múltiples expresiones o declaraciones. También es posible, pero debemos encerrarlos entre llaves. Luego usa un `return`normal dentro de ellas.
82
82
83
-
Like this:
83
+
Como esto:
84
84
85
85
```js run
86
-
let sum = (a, b) => { // the curly brace opens a multiline function
86
+
let sum = (a, b) => { // la llave abre una función multilínea
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; // si usamos llaves, entonces necesitamos un "return" explícito
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="Más por venir"
97
+
Aquí elogiamos las funciones de flecha por su brevedad. ¡Pero eso no es todo!
98
98
99
-
Arrow functions have other interesting features.
99
+
Las funciones de flecha tienen otras características interesantes.
100
100
101
-
To study them in-depth, we first need to get to know some other aspects of JavaScript, so we'll return to arrow functions later in the chapter <info:arrow-functions>.
101
+
Para estudiarlas en profundidad, primero debemos conocer algunos otros aspectos de JavaScript, por lo que volveremos a las funciones de flecha más adelante en el capítulo <info:arrow-functions>.
102
102
103
-
For now, we can already use arrow functions for one-line actions and callbacks.
103
+
Por ahora, ya podemos usar las funciones de flecha para acciones de una línea y devoluciones de llamada.
104
104
```
105
105
106
-
## Summary
106
+
## Resumen
107
107
108
-
Arrow functions are handy for one-liners. They come in two flavors:
108
+
Las funciones de flecha son útiles para líneas simples. Vienen en dos variantes:
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.Sin llaves:`(...args) => expression`--el lado derecho es una expresión: la función lo evalúa y devuelve el resultado.
111
+
2.Con llaves:`(...args) => { body }`--los paréntesis nos permiten escribir varias declaraciones dentro de la función, pero necesitamos un `return`explícito para devolver algo.
0 commit comments