Arrow Functions in JavaScript

One of the most admired features in modern JavaScript is the introduction of arrow functions, using the new => token. And in this tutorial, I will be teaching you the fundamentals of writing arrow functions.

The arrow functions are easy to write, require less typing, and more intuitive scoping due to “this” binding.

Syntax of arrow functions

The core syntax of arrow functions look something like this:

() => {
    //function body
}

Or

(arg 1, arg 2, …, arg 3) => {

    //function body
}

Whenever you have an anonymous function, you can convert it into an arrow function.

Example of arrow functions

For example, the following is an anonymous function.

var today = function() {
    return new Date();
};

There is no word right before the keyword function to assign the function’s name in the given an example.

The above anonymous function can be re-written as an arrow function by removing the keyword “function” completely and inserting an arrow just before the opening braces of the function. These braces are supposed to define the block or scope of the function.

var today = () => {
    return new Date();
};

If we return one value, we don’t need to use the “return” keyword and curly braces.

So, you can further reduce the above function into the following:

var today = () => new Date();

Arrow functions arguments

[adinserter block=”2″] Just like a normal function, you can pass arguments into an arrow function.

Let’s create an anonymous function that takes two integer values and returns the sum of these two input variables.

var sum = function(x, y) {
    return x + y;
};

var sum = (x, y) - > x + y;

With arrow functions, you no longer need to use keywords like function, return, or even braces, if returning only one value.
Arrow function also simplifies the “this” value by inheriting it from the enclosing function. With a traditional approach, you have to define this value something like so:

function counter() {
    var self = this;
    self.count = 0;
    setInterval(function add() {
            self.count++;
        },
        1000);
} //function counter

function counter() {
    this.count = 0;
    setInterval(() => {
        this.count++
    }, 1000);
}
var c = new counter();

I hope you understand how arrow functions are written. You may feel more inclined towards writing arrow functions from now on, but they have their pros and cons like every other feature.

It would be best if you used these as another technique of writing code, not as a replacement for all functions.