Introduction
ES6 provides various features to make the developer's life easier. Arrow function is one of the extensively used features provided in ES6 or ECMAScript 2015.
Arrow function is the new ES6 syntax for defining a JavaScript function. It saves few keystrokes and also makes code look cleaner compared to ES5 syntax. It is often referred as ‘Fat Arrow Function’, and syntax is similar to C# anonymous function.
It uses => token referred as ‘maps to or goes to’ symbol to define the function.
The keywords function and return keywords are avoided when using arrow function. When the definition contains multi-line, then { } curly braces are mandatory.
Let's see some of the examples to understand better.
Function Usage
Parameterless Function
ES5
function print()
{
return 'Hello World';
}
ES6
var print = () => 'Hello World';
Function with Parameter with one Parameter
ES5
function print(name)
{
return name;
}
print('Hello World!');
ES6
var print = (name) => name;
Function with Parameter with Multiple Parameters
ES5
function getProduct(a, b)
{
return a * b;
}
getProduct(5,6);
ES6
var print = (name) => name;
Object Literals
Arrow function can be used to return object literals containing variables and functions. But there are some differences in which this keyboard is processed. Arrow function uses lexical scoping(inner functions contain the scope of parent functions even if the parent function has returned) to determine the value of ‘this’ keyword.
When using ES5, syntax, this keyword returns the current context but in case of arrow function, it returns the global context.
Let’s take an example,
var calculate = {
var multiplier: 10;
getProduct: function(){
console.log(this);
}
calculate.getProduct();
}
Using Arrow function
var calculate = {
var multiplier: 10;
getProduct: () => console.log(this);
}
calculate.getProduct();
}
Function returning function
Var calculate = {
Var multiplier: 10;
getProduct: function(){
return () => console.log(this.multiplier);
}
}
calculate.getProduct()();
It returns 10 because getProduct is the function here and that’s the context we are working with.
Bind, Call and Apply methods don’t operate with arrow function, it ignores updating the object without claiming any error.
var calculate = {
var multiplier: 10;
getProduct: function(){
return () => console.log(this.multiplier);
}
}
var newObject = {
multiplier: 20
}
calculate.getProduct().bind(newObject);
Dealing with Event Handler
In ES5, when dealing with an event handler, the calling object passes the current element’s context to the callee, which makes it difficult to access the global this.
document.addEventListerner('click', function(){
console.log(this);
}
)
document.addEventListener('click', () => console.log(this));