Ads Top

Fat Arrow in JavaScript


One of the most popular ES6 features - Fat Arrow Functions!

Arrow function (or Fat Arrow function) expression is just a sugary syntax for defining a function expression in ES6. It uses => while defining a function expression by eliminating the use of function, {} brackets and return keywords and it does not bind its own this.

 ES5 way:

function sum(a,b) {
 return a + b;
}


ES6 way using fat arrow:

const sum = (a,b) => a + b;
const squareRoot = a => Math.sqrt(a); // no need of parentheses when there is only one parameter
const test = () => console.log(1);

As we noticed so far, fat arrow function is there to write the code in a more condensed way but it offers more than that.


this in Arrow Function

The most important keyword in JS - this. (What's this in JS?)

In ES6, the fat arrow function use lexical scoping for binding this to the enclosing function."Lexical scoping" simply means the value of this is determined by the surrounded code.

In global code, it will be set to the global context.

Consider the following example:

this.greeting = "Hello world!";

const foo = {
  greeting: "Hi"
};

foo.bar = () => {
 console.log(this.greeting); 
};

foo.bar(); // Hello world!

In this case, the result is not what we expected. It should be "Hi". The reason we are having the global "Hello world!" is because arrow function looked for the value of this in the surrounding code and it didn't exist there. That means the value of this is taken from the globally defined this.greeting. Even if we use bind method to bind the value of this to the object, arrow function will always take precedence and will always override any previously bound or dynamically determined value of this.

Basically, arrow function overrules call(), apply() and bind() methods to determine the value of this. The only solution is to go ES5 way and use function expression if you want this to be bound to a different value.


2 comments:

  1. Blogging is that the new poetry. I notice it terrific and wonderful in some ways.

    ReplyDelete
  2. Nice post, things explained in details. Thank You.

    ReplyDelete

Powered by Blogger.