DEV Community

Cover image for JavaScript Arrow Functions For Beginners
Danny
Danny

Posted on • Edited on

JavaScript Arrow Functions For Beginners

19/09/2020

Introduction

Hello and welcome to my first blog post. The most popular advice in the Twitter dev community lately (August 2020) is to start a blog. Even if you’re a total beginner when it comes to coding it’s still recommended. This is because trying to explain something to someone else helps solidify your own understanding of the subject. Plus there’s the bonus that on the off chance another beginner happens to find this blog, it might help them out too. So this is me trying to understand and explain arrow functions.

Arrow Functions

Arrow functions were introduced in ES6 (also known as ECMAScript 2015) to the joy of professional developers and to the despair of beginners everywhere. For professionals it meant they could write more concise code and for beginners it was one more thing on the pile that they needed to learn.

Regular Functions vs Arrow Functions

The best way to see the difference between regular functions and arrow functions is to compare the two. Let’s take a look at some regular functions and see how they would be written as arrow functions. The following code creates a function that logs “Hello” in the console and calls that function:

function regularFunction() {
  console.log("Hello");
}

regularFunction();
Enter fullscreen mode Exit fullscreen mode

And here is the function above written as an arrow function:

const arrowFunction = () => {
  console.log("Hello");
};

arrowFunction();
Enter fullscreen mode Exit fullscreen mode

Both functions do exactly the same thing.

Using Parameters

The example functions above did not take any parameters so we left the parentheses ‘()’ empty. However, arrow functions can also accept parameters. The following regular function adds two numbers together:

function regularFunction(a, b) {
  console.log(a + b);
}

regularFunction(2, 3);
Enter fullscreen mode Exit fullscreen mode

This calls the function with the arguments ‘2’ and ‘3’, adds them together and then logs the answer in the console. Here’s the same function written as an arrow function with the same parameters and arguments:

let arrowFunction = (a, b) => {
  console.log(a + b);
};

arrowFunction(2, 3);
Enter fullscreen mode Exit fullscreen mode

Now you’re probably thinking the same as me: “Wait a minute, this looks like more code than we had before! I'm not going to count the characters but one of these => has definitely been added. How is this better?” Well, it’s not better as far as I can tell but that’s because we haven’t used the shiny new syntax yet.

Syntactic Sugar

As a beginner, I console log everything so I can see if the code is working the way I expect it to (it usually isn’t). So just for fun, let’s go back a step and pretend I’m a confident coder that knows what they’re doing and use return instead of console.log().

Here’s our arrow function using return instead of console.log():

let arrowFunction = (a, b) => {
  return a + b;
};
Enter fullscreen mode Exit fullscreen mode

Now here comes the syntactic sugar (a difference in syntax) that developers crave so much. If the arrow function only returns a single value, you do not need to include the return keyword or the curly braces {}. Once they’re gone you can move the rest of the code up to the first line. This turns our arrow function into the following:

let arrowFunction = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

Which I’ll admit does look more concise.

Breakdown

Here’s a breakdown of each part to help understand what’s going on:

let arrowFunction = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

let arrowFunction = assigns the function to a variable called arrowFunction.
(a, b) are the parameters of the function. If there is only one parameter, you do not need to wrap it inside parentheses.
=> you can think of this as an arrow pointing to the function body.
a + b the code that will be returned once the function has ran.

A Slightly More Complex Example

Arrow functions are more convenient when used instead of anonymous functions (functions without a name). Here is a common example of fetching data from an API containing regular functions:

fetch("https://picsum.photos/v2/list")
  .then(function (response) {
    return response.json();
  })
  .then(function (data) {
    console.log(data);
})
Enter fullscreen mode Exit fullscreen mode

Here is the same example using arrow functions:

fetch("https://picsum.photos/v2/list")
  .then(response => response.json())
  .then(data => console.log(data));
}
Enter fullscreen mode Exit fullscreen mode

Arrow functions are starting to look better now!

Scope

An important point to be aware of is that arrow functions do not have their own scope. That means if you use the this keyword inside an arrow function, it will not refer to the scope of the arrow function but will refer to the scope of whatever the arrow function is inside instead.

Are Arrow Functions Popular?

Yes. Every JavaScript tutorial made after 2015 that I’ve come across will have arrow functions thrown in like there’s no tomorrow. Pretend each one of these sprinkles is an arrow function and the person is a developer:

A developer bathing in arrow functions

This is just a conservative estimate for illustrative purposes. The real number of arrow functions per tutorial is much higher.

Conclusion

Well it turns out the Twitter dev community was right. I can watch a video on a topic and think I understand it. I can write the code by myself and keep tweaking it until it works and think I understand it. But tell me to imagine I'm explaining it to another beginner and I've got nothing. This tiny blog post took me a few hours to make. I hope this helped someone but if not then no problem. It’s definitely helped me which is why I did it. Bye-bye.

Special Thanks

Special thanks to Laura Harvey (@lauracharvey on Twitter) for proofreading and for the feedback!

Sources

w3schools - https://www.w3schools.com/js/js_arrow_function.asp

MDN Web Docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

freeCodeCamp - https://www.freecodecamp.org/

Web Dev Simplified - JavaScript ES6 Arrow Functions Tutorial https://www.youtube.com/watch?v=h33Srr5J9nY

SaiD Hayani - https://www.freecodecamp.org/news/write-less-do-more-with-javascript-es6-5fd4a8e50ee2/

Cynthia Lee - https://www.freecodecamp.org/news/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26/

Top comments (2)

Collapse
 
naresh profile image
Naresh Poonia

Nice post, Danny.

I still have a hard time understanding Javascript because there are so many rules for arrow functions and it gets a little difficult for a code newbie to understand.
For Example

function isPositive(number) {
return number >= 0
}
can be written as
let isPositve = number => number >= 0
Because for single parameter, function paranthesis is not required.

This is just one rule out of many arrow function rules

Collapse
 
dannysblog profile image
Danny

Thanks!

Yes I still have a hard time with this sort of thing too. Especially with those quizzes people post on Twitter that are deliberately confusing. I think variable names need to be as descriptive as possible for code newbies

If I was going to use this in my code:
let isPositve = number => number >= 0
I would probably change number to isThisNumberPositive to make:
let isPositve = isThisNumberPositive => isThisNumberPositive >= 0;
It's probably not professional but it helps me to understand it for now