Arrow functions – Popular feature in ES6

Arrow Functions

Arrow functions are very popular features of javascript which is introduced in ECMASCRIPT 6 (commonly known as ES6 and ES2015).Arrow functions are very concise in syntax to write expressions of functions

What are Arrow functions?

Arrow functions are known as FAT Arrow functions Which are more concise in syntax to write function Expression.

Arrow functions use icon of  equal to & greater than (=>) which looks like Fat arrow.

Arrow functions are most popular, anonymous and it changes the way of binding of keyword this.

Advantages of Arrow functions

Mainly there are two benefits of Arrow functions

  • Very sort syntax than typical lengthy javascript functions
  • No binding of this .(Lexical scoping for this keyword)

Syntax of Arrow functions

There are variety of syntax available for Arrow functions in ES6.

Basic syntax for Arrow function is as below

(param1, param2, paramN) => {Statements of Expression}

Lets have look on different type of syntax for Arrow functions

Without parameter

  • If there isn’t any parameter in functions then we can write Arrow functions as below

ES5

Syntax:
function abc(){
 //Statements for function Expressions
}

Example:
Function printName(){
  return “My name is Mitesh Gadhiya”;
}

Call function:
printName();

Output:
// My name is Mitesh Gadhiya

ES6 – Above function of ES5 is equivalent to below function is ES6

() => { //Statements for function Expressions}

Example:
const printName = () => “My name is Mitesh Gadhiya”; 

Call function:
printName();

Output:
// My name is Mitesh Gadhiya
  • If the expression is being return you can remove the curly braces around your statements.

With single parameter

  • If there is only one parameter in the function then functions are expressed as below

ES5:

Syntax:
function abc(param){
  //Statements for function Expressions
}

Example:
Function splitName(name){
  return name.split(“ “);
}

Call function:
splitName(“Mitesh Gadhiya”);

Output:
// [“Mitesh”,”Gadhiya”]

ES6

  • Above function of ES5 is equivalent to below function is ES6
name => { //Statements for function Expressions }

Example:
const splitName = name => name.split(“ ”)

Call function:
splitName(“Mitesh Gadhiya”);

Output:
// [“Mitesh”,”Gadhiya”]
  • If there is only one parameter in function then round braces for the parameters can be removed.

With multiple parameters

    • When there are multiple parameters in the functions then functions are expressed as below.

ES5:

Syntax:
function abc(param1, param2, paramN){
 //Statements for function Expressions
}

Example:
Function concateName(firstName, lastName){
  return firstName + “ “ + lastName;
}

Call function:
concateName(“Mitesh”, “Gadhiya”);

Output:
// Mitesh Gadhiya

ES6

  • Above function of ES5 is equivalent to below function is ES6
(param1,param2,paramN) => { //Statements for function Expressions }

Example:
const concateName = (firstName, lastName) => firstName + “ “ + lastName

Call function:
concateName(“Mitesh”, “Gadhiya”);

Output:
// Mitesh Gadhiya

Return object Literal

    • Arrow function can be used to return object literal expression. The only thing we need to make sure that when we need to return Object literal then We need to wrap body into Parentheses(Curly Bracket).

ES5:

Syntax:
function abc(param1, param2, paramN){
//Statements for function Expressions
return {
 //Set object values here
}
}

Example:
var objEmployee = function setEmployee(empId, empName) {
  return {
    EmployeeId: empId,
    EmployeeName: empName
  };
};

Call function:
setEmployee(“565”, “Mitesh Gadhiya”);

Output:
// Object {EmployeeId: 4, EmployeeName: "Kyle"}

ES6

  • Above function of ES5 is equivalent to below function is ES6
Syntax
var abc= (param1, param2) => ({ //Set values of object });

Example:
var setEmployee= (empId, empName) => ({ EmployeeId: empId, EmployeeName: empName});

Call function:
setEmployee(“565”, “Mitesh Gadhiya”);

Output:
//Object {EmployeeId: 4, EmployeeName: "Kyle"} 

How to use Arrow functions?

Uptill now we have seen syntax for arrow functions.now we will see the ways where we can use the arrow functions.

Array Manipulation:

It’s common that we all need to use map, reduce and filter methods of Array. So lets understand these methods using Arrow functions.

For e.g.

const Employees = [
  { name:'Mitesh', salary:150000 },
  { name:'Niket', salary:100000 },
  { name:'Siddharth Makwana', salary:50000 }
];

Using above array object we can easily find out salaries of Employee.

//ES5

Var salaries = Employees.map(function(emp){
return emp.salary;
});

console.log(salaries);

// Output
[150000,100000,50000] 

Now lets see how easy it can be done using Arrow functions in ES6

// ES6

const salaries = Employees.map(emp => emp.salary);

console.log(salaries);

// Output
[150000,100000,50000] 

Now lets understand Array manipulation with filter method.

With above array object If we want to get employee whose salary is 50,000 then we can do it by filter method in Javascript.

Lets understand this by doing with ES5 and ES6(using Arrow function)


// ES5
var emp = Employees.filter(function(emp){ 
return emp.salary === 50000;
});

//Output
[[object Object] {
  name: "Siddharth Makwana",
  salary: 50000
}]
 

Lets do it with ES6

// ES6

const emp = Employees.filter(emp => emp.salary === 50000);
console.log(emp);

//Output
[[object Object] {
  name: "Siddharth Makwana",
  salary: 50000
}]
 

Promises and Callbacks

Basically Promises are used for managing asynchronous operations. Lets understand how it will be done using Arrow function.

Normally when we use Promises to manage asynchronous call then functions expression will be written like chaining.

Here is the example of chaining.

// ES5


function_a_Async().then(function() {
  return function_b_Async();
}).then(function() {
  return function_c_Async();
}).done(function() {
  finish();
});

The same can be implemented easily in ES6

// ES6

function_a_Async()().then(() => function_b_Async()).then(() => function_c_Async()).done(() => finish);

this with Arrow functions

The main advantage for using arrow function is, It minimize the confusion for value of this keyword.

When we do coding using javascript and use nested function call then it will be difficult to keep tracking and remember to bind the value of this context. To overcome this situation in ES5 we can use .bind() method as work around but this method makes performance down. The other way is to create clouser like var self = this;

When we use promise with Arrow function we don’t need to create clouser or any workaround to maintain the value of this context because it retains the value of this inside the block(lexical scope for this).

When we are using Arrow function then .bind(), .call(), .apply() method can’t change the value of this. If we want to change the value for this we need to use function expression(ES5).

Cons for Arrow functions:

  • Arrow functions are useful and helpful with function syntax but with new features of Arrow functions it also brings too many confusions in syntax.
    It reduces the content and saves typing but It makes the code more difficult to understand.
  • Constructors for Arrow functions can’t be created. When we use new keyword with Arrow function it throws an Error.

Conclusion:

  • Arrow functions have been called a quickest win for the ES6.
  • Arrow functions will likely become the default functions until and unless function expressions are necessary to define.


Cheers 🙂

Written by Mitesh Gadhiya