Understanding Arrow Functions in Javascript
While learning React, I used arrow functions quite a bit, but I never deeply understood how they work or when to use them. It’s time to dive deeper.
Differences between an arrow function expression and a traditional function expression:
- Can’t use
this
orsuper
, and should not be used asmethods
- Doesn’t have arguments
- Not ideal for methods that require scope, such as
call
,apply
, andbind
- Can’t be used as a
constructor
- Can’t use
yield
Comparing the same function written traditionally and then as an arrow function:
Single Argument:
- Traditional:
function (sum) {
return sum + 666
}
- Arrow:
sum => sum + 666
Note: return
is implied on a single-line arrow function.
So, for single argument arrow functions, you don’t need to use a parenthesis for the argument. However, for multiple or no arguments, you do need to use parenthesis.
Multiple arguments:
- Traditional:
function (a, b) {
return a + b + 666
}
- Arrow:
(a, b) => a + b + 666
No arguments:
- Traditional:
let a = 4
let b = 25
function () {
return a + b + 7
}
- Arrow:
let a = 4
let b = 25
() => a + b + 7
So far, these functions have required a single line (in their arrow form). If your arrow function requires multiple lines, you need to use {}
and return
, since the arrow function can’t guess what you want returned with multiple lines.
Multiple line functions:
- Traditional:
function (a, b) {
let triangles = 3
return a + b + triangles
}
- Arrow:
(a, b) => {
let triangles = 3
return a + b + triangles
}
For named functions, treat arrow functions as variables.
Named functions:
- Traditional:
function triangles(a) {
return a + 666
}
- Arrow:
let triangles = a => a + 666
Syntax:
- If you want to return an object, you have to put it in parenthesis:
spider => ({type: 'guard'})// returns {type: 'guard'}
- The params must be on the same line as the arrow:
Won’t work:
var chokes = (a, b, c)
=> 'great';
// SyntaxError: expected expression, got '=>'
Will work:
var chokes = (a, b, c) =>
'great';var chokes = (a, b, c) => (
'great'
);var chokes = (a, b, c) => {
return 'great'
};var chokes = (
a,
b,
c
) => 'great';
Biggest takeaways:
On one line, it can be extremely simple, not requiring parenthesis, brackets, or return statements. If I use brackets, I need to use a return
statement, and that goes for multiple line arrow functions, too.
References