Skip to content

Arrow functions, the basics #334

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ ask(
);
```

Looks short and clean, right?
Se ve corto y limpio, ¿verdad?
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

# Rewrite with arrow functions
# Reescribe con funciones de flecha

Replace Function Expressions with arrow functions in the code below:
Reemplace las expresiones de función con funciones de flecha en el código a continuación:

```js run
function ask(question, yes, no) {
Expand Down
62 changes: 31 additions & 31 deletions 1-js/02-first-steps/17-arrow-functions-basics/article.md
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
# Arrow functions, the basics
# Funciones Flecha, lo básico

There's another very simple and concise syntax for creating functions, that's often better than Function Expressions.
Hay otra sintaxis muy simple y concisa para crear funciones, que a menudo es mejor que las Expresiones de funciones.

It's called "arrow functions", because it looks like this:
Se llama "funciones de flecha", porque se ve así:

```js
let func = (arg1, arg2, ...argN) => expression
```

...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.
...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.

In other words, it's the shorter version of:
En otras palabras, es la versión más corta de:

```js
let func = function(arg1, arg2, ...argN) {
return expression;
};
```

Let's see a concrete example:
Veamos un ejemplo concreto:

```js run
let sum = (a, b) => a + b;

/* This arrow function is a shorter form of:
/* Esta función de flecha es una forma más corta de:

let sum = function(a, b) {
return a + b;
Expand All @@ -33,32 +33,32 @@ let sum = function(a, b) {
alert( sum(1, 2) ); // 3
```

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.
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.

- If we have only one argument, then parentheses around parameters can be omitted, making that even shorter.
- Si solo tenemos un argumento, se pueden omitir paréntesis alrededor de los parámetros, lo que lo hace aún más corto.

For example:
Por ejemplo:

```js run
*!*
let double = n => n * 2;
// roughly the same as: let double = function(n) { return n * 2 }
// Más o menos lo mismo que: let double = function(n) { return n * 2 }
*/!*

alert( double(3) ); // 6
```

- If there are no arguments, parentheses will be empty (but they should be present):
- Si no hay parámetros, los paréntesis estarán vacíos (pero deberían estar presentes):

```js run
let sayHi = () => alert("Hello!");

sayHi();
```

Arrow functions can be used in the same way as Function Expressions.
Las funciones de flecha se pueden usar de la misma manera que las expresiones de función.

For instance, to dynamically create a function:
Por ejemplo, para crear dinámicamente una función:

```js run
let age = prompt("What is your age?", 18);
Expand All @@ -70,42 +70,42 @@ let welcome = (age < 18) ?
welcome();
```

Arrow functions may appear unfamiliar and not very readable at first, but that quickly changes as the eyes get used to the structure.
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.

They are very convenient for simple one-line actions, when we're just too lazy to write many words.
Son muy convenientes para acciones simples de una línea, cuando somos demasiado flojos para escribir muchas palabras.

## Multiline arrow functions
## Funciones de flecha multilínea

The examples above took arguments from the left of `=>` and evaluated the right-side expression with them.
Los ejemplos anteriores tomaron parámetros de la izquierda de `=>` y evaluaron el lado derecho de la expressión con ellos.

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.
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.

Like this:
Como esto:

```js run
let sum = (a, b) => { // the curly brace opens a multiline function
let sum = (a, b) => { // la llave abre una función multilínea
let result = a + b;
*!*
return result; // if we use curly braces, then we need an explicit "return"
return result; // si usamos llaves, entonces necesitamos un "return" explícito
*/!*
};

alert( sum(1, 2) ); // 3
```

```smart header="More to come"
Here we praised arrow functions for brevity. But that's not all!
```smart header="Más por venir"
Aquí elogiamos las funciones de flecha por su brevedad. ¡Pero eso no es todo!

Arrow functions have other interesting features.
Las funciones de flecha tienen otras características interesantes.

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>.
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>.

For now, we can already use arrow functions for one-line actions and callbacks.
Por ahora, ya podemos usar las funciones de flecha para acciones de una línea y devoluciones de llamada.
```

## Summary
## Resumen

Arrow functions are handy for one-liners. They come in two flavors:
Las funciones de flecha son útiles para líneas simples. Vienen en dos variantes:

1. Without curly braces: `(...args) => expression` -- the right side is an expression: the function evaluates it and returns the result.
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.
1. Sin llaves: `(...args) => expression` -- el lado derecho es una expresión: la función lo evalúa y devuelve el resultado.
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.