Arrow Functions
An arrow function is like a normal function just with 4 key differences:
- They have a different syntax (duh).
- There is no form of arrow function declaration, only expressions.
- They don't get their own
this
. - They have an implicit return.
1. Different syntax
Here is the syntax of an arrow function compared to a regular function
keyword. I use Immediately Invoked Function Expression for both functions.
Notice that if an arrow function takes a single argument without any fanciness like destructuring, you may omit the brackets around its parameters.
No arguments: you need brackets.
One argument: you can omit brackets.
Default parameters: you need brackets.
Destructuring: you need brackets.
More than one argument: you need brackets.
2. Only expressions
You can also name a function by writing a variable name after the function
keyword. This is called "function declaration". There are no function declarations for arrow functions, just anonymous function expressions.
The difference between a function declaration and a function expression is that they are parsed at different times. The declaration is defined everywhere in its scope, whereas the expression is only defined when its line is reached.
You can also see the difference between const
and var
here. Since foo
was declared using the var
keyword, it is hoisted, and its value is undefined
. foo()
tries to call undefined
, but its obviously not a function. Since const
doesn't hoist invoking bar
throws a reference error.
3. No this
Like other languages, JavaScript has a this
keyword. There are several ways this
is bound explicitly or implicitly. We are only going to focus on the behavior relevant to arrow functions.
Using the function
keyword, this
references the object. However, the arrow function doesn't get its own this
. Therefore wheels
is undefined because the global object doesn't have a property wheels
.
To understand this
, play Eric Elliott's "What is this?".
4. Implicit return
In the previous code snippet, we used the return
keyword to return values from the functions. Nevertheless, arrow functions don't need to do that. If your function body is a single expression, you can omit the curly braces and the expression gets returned automatically.
Using implicit returns, we can simplify the examples from the syntax section.
Implicit returns become especially handy for currying, which is when a function returns another function until it returns its final value.
add
is a function that takes in a
and returns a function that takes in b
that returns the sum of a
and b
. The function that takes in b
remembers a
in its closure.