Question:
When to use an arrow function in JavaScript?
() => { console.log('test'); }
function() { console.log('test'); }
Answer:
This new syntax for functions introduced in ES6 is functionally equivalent to normal functions in most situations, however it is important to note the following differences:
-
Value of
this
, normal functions capture the value ofthis
as the global object (orundefined
in strict mode ):function Persona() { this.edad = 0; setInterval(function crecer() { this.edad++; // error lógico, no se refieren a la misma variable }, 1000); }
While arrow functions capture that value from the immediate outer scope :
function Persona(){ this.edad = 0; setInterval(() => { this.edad++; // correcto, this se refiere a una instancia de Persona }, 1000); }
-
Arguments, normal functions have access to a special variable called
arguments
that is similar to an array and contains references to the arguments that are passed to a function:function foo(arg1, arg2) { console.log(arguments[0]); } foo("hola", "mundo"); // imprime "hola"
In arrow functions,
arguments
refers to a variable in the outer scope , if this variable does not exist its value isundefined
:var arguments = 42; var arr = () => arguments; arr(); // 42
Despite this, a similar functionality can be implemented with the rest parameters :
var foo = (...args) => {console.log(args[0])}; foo("hola", "mundo"); // Imprime "hola"
-
If an arrow function simply returns a single line of code, you can omit the brackets from the declaration and the return keyword. This tells the arrow function to return the statement.
const double = (num) => num * 2;
-
Keyword
yield
, this reserved word was also introduced in ES6 and is used in generator functions , however it cannot be used in arrow functions.
Arrow functions provide a more elegant and compact syntax when used as callbacks , so they can be used in almost the same situations as normal functions, and will probably be preferred in future versions of EcmaScript, you just have to take into account the differences. above so as not to make mistakes.