Arrow functions · Funciones de flecha
Arrow functions
- A shorter way to write a function:
const square = (n) => n * n;. - With a single expression after
=>, the value is returned automatically — noreturn, no{ }.
Funciones de flecha
- Una forma más corta de escribir una función:
const square = (n) => n * n;. - Con una sola expresión después de
=>, el valor se retorna automáticamente — no hace faltareturn, ni{ }.
const square = (n) => n * n;
console.log(square(5)); // → 25
More than one parameter
- List the parameters in the brackets, separated by commas.
Más de un parámetro
- Enumera los parámetros entre corchetes, separados por comas.
const add = (a, b) => a + b;
console.log(add(3, 4)); // → 7
Watch out
- Need a longer body? Use
{ }and then you must writereturnyourself. - Arrow functions shine as short helpers — you will hand them to
.mapand.filterwhen we reach array methods.
Ten cuidado
- ¿Necesitas un cuerpo más largo? Usa
{ }y entonces debes escribirreturntú mismo. - Las funciones de flecha brillan como ayudantes breves — las pasarás a
.mapy.filtercuando lleguemos a los métodos de arrays.
Common mistakes
x => x + 1is a short function; with no braces it returns the expression.- Arrow functions are handy as arguments to array methods.
Errores comunes
x => x + 1es una función corta; sin llaves retorna la expresión.- Las funciones de flecha son útiles como argumentos para los métodos de arrays.
Now you try
- Write each arrow function.
- Press Check answer to test it.
Ahora prueba tú
- Escribe cada función de flecha.
- Pulsa Comprobar respuesta para verificarla.
Write an arrow function triple that returns its argument times 3: const triple = (n) => n * 3;. · Escribe una función de flecha triple que devuelva su argumento multiplicado por 3: const triple = (n) => n * 3;.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Write an arrow function add with two parameters that returns their sum. · Escribe una función de flecha add con dos parámetros que devuelva su suma.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Write an arrow function isEven that returns true when its argument is even (n % 2 === 0). · Escribe una función de flecha isEven que devuelva true cuando su argumento sea par (n % 2 === 0).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.