Getting Started with ES6 Arrow Functions in JavaScript

Getting Started with ES6 Arrow Functions in JavaScript

In this article, we will walk through the basics of ES6 arrow functions in javascript and discuss their benefits.

With ES6 JavaScript came many updates to the language including the spread operator, object destructuring, new type of variables, and more. On top of all those amazing features came arrow functions, a new and concise way to write functions.

Table of Contents

  • ES5 Functions
  • Your First ES6 Arrow Function
  • Removing Unnecessary Parenthesis
  • Implicit Return
  • Using Arrow Functions in Map and Filter
  • 'This' Binding with Arrow Functions
  • Wrap Up 

ES5 Functions

Let's start with looking at how we defined functions with ES5 JavaScript. To do define a function, it required the function keyword. For example, if we wanted to define a function that would multiply a number by two, it would look something like this.

function multiplyByTwo(num){
    return num * 2;
}

We could also define the function and assign it to a variable if we wanted to.

const multiplyByTwo = function(num){
    return num * 2;
}

Regardless of which way you do it, the keyword function has to be included.

Your First ES6 Arrow Function

To create an arrow function, you don't need the keyword function. In fact, you basically remove that keyword and add an arrow right after the parameters but before the open curly bracket. It would look like this.

const multiplyByTwo = (num) => {
    return num * 2;
}

At this point, it doesn't look substantially different than the "old" way to do it, but we can make a few enhancements.

Removing Unnecessary Parenthesis

The parenthesis around the parameters are required if there are no parameters or more than one parameter. However, when your arrow function only has one parameter, you can leave out the parenthesis to simplify it a bit like so.

const multiplyByTwo = num => {
    return num * 2;
}

Implicit Return

Often times, we write functions that return after just one line of code. With the "old" way of writing functions, the number of lines in the function didn't affect how you defined the function. With arrow functions, it can.

If the only thing you want to do in a function is a one-line return, you can use *implicit return *_to greatly simplify your function. While using implicit return, you don't need the curly braces or the _return keyword. It would look like this.

const multiplyByTwo = num => num * 2;

One thing to think about it is that you can still use the implicit return syntax even if you don't necessarily need to return anything. In other words, if the callers of your function are not expecting it to return anything, then having it return something doesn't matter.

For example, if I just wanted to print something to the console, I could use implicit return to shorten the length of the function.

const printName = (first, last) => console.log(`${first} ${last}`);

Using Arrow Functions in Map and Filter

One of the most common places you'll see arrow functions used are with JavaScript Array methods like map, reduce, filter, etc. By use arrow functions with these methods, you can make complete array transformations in just one line.

Let's look at two examples, one with map and one with filter. For the map version, let's say we want to convert an array by multiplying each number by two. It would look something like this.

const twodArray = [1,2,3,4].map( num => num * 2);

Notice with this arrow function, I left off the parenthesis (because there's only one parameter) and used implicit return. This kept the entire transformation to one line!

Now, let's do another with filter. Let's say we want to filter all numbers that are not even.

const filteredArray = [1,2,3,4].filter( num => num % 2 == 0);

Again, no parenthesis and implicit return. Super quick to make array transformations with just one!

'This' Binding with Arrow Functions

The conversation around the _this _keyword is definitely intermediate JavaScript, so you might need to do a little bit of additional research for this section. Regardless, let's start with an example using an ES5 function definition inside of a person object.

const person = {
    first: "James",
    last: "Quick",
    getName: function() {
        this.first + " " + this.last
    }
}

In this case, we created a person object with a first and last name as well as a getName() function that returns the full name of the person. Inside of the function, we are trying to reference the first and last properties, by calling this.first and this.last.

When ES5 functions are defined in an object, 'this' refers to the object itself.

The reason we are able to access those properties through the this keyword, is that when those functions are defined inside of an object, it is automatically bound to the object itself. Therefore, with ES5 functions, we can still reference the object propreties by using 'this'.

Arrow functions don't bind anything to the keyword 'this'.

However, when you use arrow functions, things change a bit. Arrow functions don't do any binding for the keyword this. Therefore, if we were to change the function definition to be an arrow functions, things wouldn't work.

const person = {
    first: "James",
    last: "Quick",
    getName: () => {
        return this.first + " " + this.last
    }
}

In this case, undefined would be printed for both the first and last property. The reason is since the keyword 'this' is not bound to the person object, it doesn't have a first and last variable to refer to.

Understanding the difference between using this in arrow functions is really important!

Wrap Up

Arrow functions are one of many nifty little features of ES6 JavaScript. You will see them used more and more in examples and documentation, so it's worth learning how they work. Not to mention, they can significantly improve the conciseness and readability of your code!

javascript es6 web-development

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Best Web and App Development Company in Ahmedabad

Contact DataPierce for any questions or queries you have about website development, designing, marketing projects or any small or enterprise software development.

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

For World Class Web Development Services in India visit RB Genie

Do you want excellent and world class web development services for your valuable projects? Contact **RB Genie **now, we have more than 8 years experienced team of web developers, which specializes in overall web design and website development...

JavaScript developers should you be using Web Workers?

Do you think JavaScript developers should be making more use of Web Workers to shift execution off of the main thread?