JavaScript ES6 Arrow Functions

The arrow function is taken from CoffeeScript (a trans-compiled language). The arrow function is also called the “fat arrow” function. This is represented by => (Flat Arrow). It is anonymous and can change the way this binds into function. When we are using the arrow function we will avoid –

  • Function keyword
  • Return keyword
  • Curly brackets

How to use arrow function


//ES5 Example
var add = function(a, b) {

	return a + b;
};

//ES6 Example
var add = (a, b) => { return a + b; }

// or you can use this way
var add = (a, b) => a + b;

Function without arguments


//ES5 Example
var msg = function() {

	return "Welcome! User";
};

//ES6 Example
var msg = () => "Welcome! User";

For object literal


//ES5 Example
var obj = function(age, name) {

	return {
		age: age,
		name: name
	}
};

//ES6 Example
var obj = (age, name) => ({age: age, name: name});
obj(12, "bob");

Now some useful use cases



//ES6 Example
var arr = [1, 2, 3, 4]; 
var doubleVal = arr.map(v => v*2); //[1, 4, 9, 16]
var even = arr.filter(v => v%2==0) // [2, 4]

So now we can see arrow function is a very useful tool for us. But we know about some more things about arrow function like –

  • The value of this can’t change by bind, call, apply method.
  • We can’t use it as a constructor function

About the Author: Pankaj Bisht