Arrow Functions in JavaScript
In this post, I’ll just quickly go over how to use arrow functions in JavaScript. This is more so for me just so that I remember how to use them. This blog is based on the MDN Web Docs.
Single Parameter Functions
First, let’s start off with a traditional function:
To “convert” this into an arrow function, we first remove the word function
and place an arrow =>
between the end parantheses )
and curly brackets {
.
We can then remove the body brackets and return
since return
is implied without brackets.
If we’re only passing in a single parameter, we can also remove the paratheses but, personally, it makes it easier to read with the parantheses.
Multiple Parameter Functions
Once again, we start off with a traditional function, but this time with multiple parameters:
First, we remove the word function
and place an arrow =>
between the closing parantheses )
and open body bracket {
.
Then, remove the body brackets and the word return
, since return is implied when no body brackets are used.
The steps are the same if we have a function with no parameters. An example looks like:
More Than Just a Return
Now, if we have multiple lines in our function, then we must use the body brackets {}
and return
.
Let’s convert the following function:
We apply the same steps but must include the body brackets and return
.
Functions with Names
If we have a function with a name, such as:
We just need to store the arrow function in a variable. So, after converting the traditional function to an arrow function, it will look like:
That’s the extend to what I’ll go to with arrow functions. You can read the rest on the MDN Web Docs
So, 今天就讲到这,
Timothy Wang