There are two benefits to arrow functions.
- Shorter syntax
=>
compared to function expressions. this
is picked from the lexical scope (also called static scope).
Arrow functions are always anonymous. The examples are below:
Function without any parameters
The above code is equivalent of the below:
Using Arrow function with map
The above code is equivalent of the below:
Function with 1 parameter
The above code is equivalent of the below:
Function with more than 2 parameters
The above code is equivalent of the below:
this reference
The source of this is an important distinguishing aspect of arrow functions:
- Traditional functions have a
dynamic this
; its value is determined by how they are called. - Arrow functions have a
lexical this
; its value is determined by the surrounding scope.
The following variables are all lexical inside arrow functions:
arguments
super
this
new.target
An arrow function does not create its own this context, so this has the original meaning from the enclosing context.
Working with this
until traditional way
The above code is equivalent of the below:
Returning object literals
The object literal returned by this arrow function is like below:
The above code is equivalent of the below: