Fat Arrow Function Expression in ES6
Posted By : Rudhishthir Prakash | 26-Dec-2017
Fat Arrow function expressions are basically a shorter function syntax. It is extremely succint than the normal function expressions and just a bare minimum code is required to express the logic of the code. But a key thing to note that "this" keyword behaves differently which is explained below.
We normally write function like this:
var getValue = function(x){ return x*2; }
But when we use fat arrows, we will write like:
let getValue = x => x*2;
where, x is the argument and x*2 is the function body and the return statement here is implicit. This is in case where the function is of only one line.
So, if we add the following line to the above fat arrow function:
let getValue = x => x*2; console.log(getValue(4));
The output will be 8.
Parentheses around the arguments and braces around the function body is optional in case of one argument and single line in body but is necessary if they are more than one or we are not passing any argument at all.
For example,
let getSum = (x, y) => { return x + y}; console.log(getSum(4,5));
Output will be 9.
var x = 2; let getValue = () => {return x*2 }; console.log(getValue());
Output will be 4.
We can also use "_" instead of "()" in case we are not passing any argument.
var x = 2; let getValue = _ => {return x*2 }; console.log(getValue());
Output will be 4.
As mentioned previously, we have some tricky situations when we use "this" keyword with setTimeout function(say). For example,
var f = function(){ this.val = 1; setTimeout(function(){ this.val++; console.log(this.val); }, 1) } var ff = new f();
And when we run this code, we get the output as NaN.
This is because, setTimeout has its own "this" which refer to its object.
We can work around this situation as follows:
var f = function(){ var that = this; that.val = 1; setTimeout(function(){ that.val++; console.log(that.val); }, 1) } var ff = new f();
We can work around this problem using fat arrows insead of anonymous function as well.
var f = function(){ this.val = 1; setTimeout(() => { this.val++; console.log(this.val); }, 1) } var ff = new f();
This gives output as 2.
Request for Proposal
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Rudhishthir Prakash
Rudhishthir is a technical enthusiast having experience in C#.NET, NodeJS & various front-end technologies. He has great experience in building quality applications with innovative ideas. He also has proven expertise in handling clients.