Arrow Function : A concise and fat form of javascript function

Arrow Function : A concise and fat form of javascript function DasJs

Arrow Function both make your code more concise while also making the “this” keyword more manageable. It allows having implicit return without having return keyword.

Benefits of Arrow Function:

  1. It has a shorter syntax than a function expression.
  2. It does not have its own this, super, arguments, new.target.

Read also: How to use Conditional/Ternary Operator in Javascript

Let's see the first benefit:

Let's take a look at the traditional function with one parameter:

 function functionName(arg) {
   return arg + 3;
 }
funcName(2); 

OR


var func = function functionName(arg) {
  return arg + 3;
};
func(2);

Now the same example using arrow function


var func = (arg) => { arg + 2 }
funcName(2);

If { } contains single statement. You can omit the parentheses and write


var func = (arg) => arg + 2 
funcName(2);

Let's take a look at the traditional function with multiple parameters:

 function functionName(x,y) {
   return x + y;
 }
funcName(2,3); 

OR


var funcName = function (x,y) {
  return x + y;
}
funcName(2,3);

Let's check out the same example using arrow functions:


var funcName = (x,y) =>  x + y  
funcName(2,3);

Now I am taking another example of a function with no parameter:

 function functionName() {
   return "Arrow function by DasJs";
 }
funcName(); 

OR


var funcName = function () {
  return "Arrow function by DasJs";
}
funcName();

The same example using Arrow functions:


var funcName = () =>  "Arrow function by DasJs"  
funcName();

 

If you have a single parameter, you can remove parenthesis of the parameter. You can also write as below:


var funcName = arg => arg + 2  
funcName();