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.
Building SPAs with Django and HTML Over the Wire: Learn to build real-time single page applications with Python
The HTML over WebSockets approach simplifies single-page application (SPA) development and lets you bypass learning a JavaScript rendering framework such as React, Vue, or Angular, moving the logic to Python. This web application development book provides you with all the Django tools you need to simplify your developments with real-time results.
Buy the bookHelp me keep writing
Every coffee gives me a push toward the next article.
Sure, it's on me!
Comments
There are no comments yet.