11. Arrow
Arrow functions (arrow) are a compact alternative to traditional functions. They're not for every situation since they don't have their own context, they reference their parent's. So it's not recommended for building objects: it can't be used in constructors, methods, this, super, call, apply, bind, and yield. However, despite all that, it helps simplify the syntax and works well in function-oriented programming.
const listaDeNumeros = [1, 2, 3, 4];
const listaDeNumerosMas10 = listaDeNumeros.map(numero => numero + 10);
console.log(listaDeNumerosMas10);
// [11, 12, 13, 14]
If you want it to not behave as an anonymous function, you can store it in a variable.
const aumentar10 = numero => numero + 10;
console.log(aumentar10(5));
// 15
Its structure varies depending on the number of arguments or lines in its body.
No argument
() => cuerpo
Its equivalent would be as follows.
function () {
return cuerpo
}
For example.
setTimeout(() => console.log("He tardado 2s en aparecer"), 2000)
One argument
argumento1 => cuerpo
Its equivalent would be as follows.
function (argumento1) {
return cuerpo
}
Another example would be the function from the beginning.
numero => numero + 10
Or also.
function (numero) {
return numero + 10;
}
Several arguments
(argumento1, argumento2, argumento3) => cuerpo
Its equivalent would be as follows.
function (argumento1, argumento2, argumento3) {
return cuerpo
}
An example.
const total = [10, 20, 30].reduce((total, numero) => total + numero);
console.log(total);
// 60
Or also.
const total = [10, 20, 30].reduce(function (total, numero) {
return total + numero;
})
console.log(total);
// 60
Several lines in the body
() => {
cuerpo
return cuerpo
}
Its equivalent would be as follows.
function () {
cuerpo
return cuerpo
}
An example.
setInterval(() => {
const miFecha = new Date();
console.log(miFecha.getSeconds());
}, 1000);
// 34
// 35
// ...
Or also.
setInterval(function() {
const miFecha = new Date();
console.log(miFecha.getSeconds());
}, 1000);
// 34
// 35
// ...
This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.
Desafíos de programación atemporales y multiparadigmáticos
Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.
Buy the bookWill you buy me a coffee?
This is how I keep writing without ads or paywalls.
Sure, it's on me!
Comments
There are no comments yet.