ES6 arrow functions

es6 arrow function

Arrow function taken from CoffeeScript (a transcompiled language). Arrow function, also called “fat arrow” functions. This is represented by => (Flat Arrow). It is anonymous and can change the way this bind into function. When we are using 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 like 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 very useful tool for us. But we know about somemore thing about arrow function like –

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

You May Also Like

About the Author: admin