Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Arrow function in Javascript

Arrow function in Javascript

In this chapter, you will learn about what is arrow function in Javascript and how they are special from a regular function. The arrow functions been introduced in ES6 and also called as a fat function. Now let us see the advantages and limitations of arrow function

Advantages:

  1. Provides a more concise syntax for writing function expressions
  2. They share the surrounding this keyword
  3. Simply use this keyword of the function they are written in
  4. Have a lexical this variable
  5. Can be used as a shorthand function

Limitations:

  1. Does not have its own bindings to this, in other words, don’t have their own this instance
  2. Should not be used as methods.
  3. Does not have arguments
  4. Not suitable for the call, apply and bind methods
  5. Can not be used as constructors
  6. Can not use yield, within its body

Syntax:
The arrow function can be defined as follows

var employeeFullName = (firstName, lastName) => {
    console.log('Employee Full Name : '+ firstName + ' '+ lastName);
}
employeeFullName('Stark','Mickel');

// output
// Employee Full Name : Stark Mickel

Now let’s see the below code snippet which contains a regular function and prints the employee details. You can notice that the details method is accessing the person properties from the keyword this.

var person = {
    name: 'Stark',
    dep: 'IT',
    salary: 5000,
    phoneNumber: 9988000,
    details: function() {
        console.log('*********** The details of employee ***********');
        console.log('Employee name : '+this.name);
        console.log('Employee dep : '+this.dep);
        console.log('Employee salary : '+this.salary);
        console.log('Employee phone number  : '+this.phoneNumber);
    }
};

person.details();

// Output
// *********** The details of employee ***********
// Employee name : Stark
// Employee dep : IT
// Employee salary : 5000
// Employee phone number  : 9988000

Now, let’s take the same code snippet and add function expressions. As we can see in the below code snippet the variables are undefined.

var person = {
    name: 'Stark',
    dep: 'IT',
    salary: 5000,
    phoneNumber: 9988000,
    details: function() {
        console.log('*********** The details of employee ***********');
        console.log('Employee name : '+this.name);
        var employeeDep = function () {
            console.log('Employee dep : '+this.dep);
        };
        var employeeSalary = function () {
            console.log('Employee salary : '+this.salary);
        };
        var employeePhone = function () {
            console.log('Employee phone number  : '+this.phoneNumber);
        };
        employeeDep();
        employeeSalary();
        employeePhone();
    }
};

person.details();

// Output
// *********** The details of employee ***********
// Employee name : Stark
// Employee dep : undefined
// Employee salary : undefined
// Employee phone number  : undefined

Now how can we solve the above problem? we can solve the above issue with the self instance as follows.

var person = {
    name: 'Stark',
    dep: 'IT',
    salary: 5000,
    phoneNumber: 9988000,
    details: function() {
        console.log('*********** The details of employee ***********');
        console.log('Employee name : '+this.name);
        var self =this;
        var employeeDep = function () {
            console.log('Employee dep : '+self.dep);
        };
        var employeeSalary = function () {
            console.log('Employee salary : '+self.salary);
        };
        var employeePhone = function () {
            console.log('Employee phone number  : '+self.phoneNumber);
        };
        employeeDep();
        employeeSalary();
        employeePhone();
    }
};

person.details();

// Output
// *********** The details of employee ***********
// Employee name : Stark
// Employee dep : IT
// Employee salary : 5000
// Employee phone number  : 9988000

Now we will move to the arrow function. Let us change the regular function to arrow function in the same example.
After changing the regular function into the arrow function we got the same output. So if you remember the point “The more advantage of an arrow function is that they share the surrounding this keyword”.

var person = {
    name: 'Stark',
    dep: 'IT',
    salary: 5000,
    phoneNumber: 9988000,
    details: function() {
        console.log('*********** The details of employee ***********');
        console.log('Employee name : '+this.name);
        var employeeDep = () => {
            console.log('Employee dep : '+this.dep);
        };
        var employeeSalary = () => {
            console.log('Employee salary : '+this.salary);
        };
        var employeePhone = () => {
            console.log('Employee phone number  : '+this.phoneNumber);
        };
        employeeDep();
        employeeSalary();
        employeePhone();
    }
};

person.details();

// Output
// *********** The details of employee ***********
// Employee name : Stark
// Employee dep : IT
// Employee salary : 5000
// Employee phone number  : 9988000

As we can observe in the above code snippet, we are not assigning this instance to self, instead, we are using this instance itself. So this shows that the arrow functions can share the surrounding this keyword. Now we will go further in-depth to understand how arrow function can use the lexical environment. Now create an employee object

function employee(name, dep) {
    this.name = name;
    this.dep = dep;
}
employee.prototype.task = function(task) {
    var listTask = task.map(function(item){
        console.log(this.name+' has the task '+item);
    });
}
let taskList = ['JIRA-123','JIRA-124','JIRA-125'];
new employee('Stark','IT').task(taskList);

// output
// has the task JIRA-123
// has the task JIRA-124
// has the task JIRA-125

As we can see in the above code snippet, we cant access the name property of an employee object inside the map function. Because its the inner new function and it doesn’t point to this instance. Now we can solve the above problem by using the bind() method, for more details on bind go though

function employee(name, dep) {
    this.name = name;
    this.dep = dep;
}
employee.prototype.task = function(task) {
    var listTask = task.map(function(item){
        console.log(this.name+' has the task '+item);
    }.bind(this));
}
let taskList = ['JIRA-123','JIRA-124','JIRA-125'];
new employee('Stark','IT').task(taskList);

// output
// Stark has the task JIRA-123
// Stark has the task JIRA-124
// Stark has the task JIRA-125

Now the power of arrow function comes here and makes it very simple. Let us change the task function to arrow function. As we can see in the below example “they can use lexical environment this variable”, arrow function solved the issue in one line, that’s the reason they are called as shorthand functions.

function employee(name, dep) {
    this.name = name;
    this.dep = dep;
}
employee.prototype.task = function(task) {
    var listTask = task.map((item) => {
        console.log(this.name+' has the task '+item);
    });
}
let taskList = ['JIRA-123','JIRA-124','JIRA-125'];
new employee('Stark','IT').task(taskList);

// output
// Stark has the task JIRA-123
// Stark has the task JIRA-124
// Stark has the task JIRA-125

 

One thought on “Arrow function in Javascript

Comments are closed.