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:

function (a) {
  return a + 100;
}

To “convert” this into an arrow function, we first remove the word function and place an arrow => between the end parantheses ) and curly brackets {.

(a) => {
  return a + 100;
}

We can then remove the body brackets and return since return is implied without brackets.

(a) => a + 100;

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:

function (a, b) {
  return a + b + 100;
}

First, we remove the word function and place an arrow => between the closing parantheses ) and open body bracket {.

(a, b) => {
  return a + b + 100;
}

Then, remove the body brackets and the word return, since return is implied when no body brackets are used.

(a, b) => a + b + 100;

The steps are the same if we have a function with no parameters. An example looks like:

() => 100;

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:

function (a, b) {
  let chuck = 42;
  return a + b + chuck;
}

We apply the same steps but must include the body brackets and return.

(a, b) => {
  let chuck = 42;
  return a + b + chuck;
}

Functions with Names

If we have a function with a name, such as:

function bob (a) {
  return a + 100;
}

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:

let bob = (a) => a + 100;

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