30 Days Of JavaScript

Day 6: Functions Part 2

Lesson 2: Arrow Functions

There are a couple of ways to declare a function in JavaScript.

The first you have already been using:

1function functionName(arg1, arg2, arg3) {
2  return someValue;
3}

What this is saying is:

Create a function (){ } and store it in functionName

It might sound odd to break it up like this, create (){ } and then store functionName. But that is what's happening under the hood, and it becomes even clearer with the other function syntax I'm about to show you.

Arrow function syntax is the alternative, it was added to the language much later. It's a shorter syntax and has some interesting language behaviours that won't make much sense at the moment.

So, we'll look at the syntax but skip the nitty gritty for now on the the language issues it solves. Here is a rewrite of the function above in arrow syntax

1const functionName = (arg1, arg2, arg3) => {
2  return someValue;
3};

The reason this is called an arrow function is that is uses => in the syntax when it creates the function () => {}; It then stores the function in a constant called functionName. If we write it on one line you can see this clearly: const functionName = () => {}

Again, that is:

  1. Create function: () => {}

  2. Save in constant const functionName =

This means that our function now lives in functionName, with this syntax it becomes obvious that we can pass it around and we can call it when we want to.

You call it just the same as the other syntax like functionName() as you can see in the playground below:

Let's use a real example now by converting one of our earlier functions into an arrow function:

It works exactly the same!

Well sort of, there is a big difference in how this function is scoped that makes it significantly more portable, it gets around a host of issues web developers had in the mid 2000s. We won't go into that now because:

  1. It's not that important right now
  2. It will confuse you massively (because it does for everyone new to JavaScript)
  3. Again, it's just not that important right now.

Well, with that frustrating finale let's dive into the next lesson.

Outline

Go Pro?

Upgrade to Pro for quizzes, tracked progress and a completion certificate for just $25 🚀

Want more developer tips, tricks and tools?
Then follow me:
FREE Coding Career Quick Start Guide 🚀
Discover the best way to learn to code, how to land a job and valuable resources to help your journey in this free 15 page value packed guide.
Looking to email me? You can get me on my first name at allthecode.co