At first glance the arrow function syntax may seem confusing, but it quickly becomes intuitive once you understand the rules behind it.
What are arrow functions?
Arrow functions are just a shorthand syntax to create normal javascript functions. In it's most basic form, it simply dropped the function keyword and added an arrow => between the parameters and function body.
// both function definitions are equal
// traditional function definition
function(){
return 1
}
// basic arrow function syntax:
()=>{
return 1
}
The basic form of an arrow function is not all that different from the definition syntax. But arrow functions have additional special rules for some cases that make them harder to get at first glance.
Additional rules for arrow functions
If the function returns only a single value, the parenthesis ()
can be omitted:
// both function definitions are equal
(n) => {
return 1
}
n => {
return 1
}
Additionally, if the function body can be expressed as a single line, the curly braces {}
and the return
keyword can be omitted as well:
// both function definitions are equal
n => {
return 1
}
n => 1
Clearing up the confusion
Most of the confusion around arrow functions stems from the multitude of different syntaxes it may have. To give you an idea of how many there are, here are all possible definitions of the same function:
// all function definitions are equal
function(n){
return 1
}
(n) => {
return 1
}
n => {
return 1
}
(n) => return 1
n => return 1
(n) => 1
n => 1
One little caveat with arrow functions is that their name is not part of the syntax. Instead, you will need to assign them to a variable if you need a named function instead of an anonymous one:
// both function definitions are equal
function sample(){
return 1
}
let sample = () => 1
Which one you use is ultimately up to you, their difference is purely the line length and readability for the developer. The old functions will work just as well as the new arrow function syntax.