Arrow Functions Typescript

Introduction

In Javascript, we describe an anonymous function using the function keyword. A function is called anonymous function when it doesn't have a name specified. 

let func = function(message){
 console.log(message);
}

But in Typescript which is ECMAScript 6 defines a shorter way of writing anonymous function. The new syntax is called fat-arrow syntax or lambda expression. 

let func = (message) => { 
    console.log(message);
}

Now we can see that we have used (=>) fat-arrow syntax instead of function keyword. 
We can see that we have removed curly braces as well if there is only one expression. It is defined as below. It is the shorthand syntax to write an anonymous function using arrow functions. 

let func = () => console.log(message);

Arguments to Arrow Function

If we are using arrow function we can write as follows. We need not write a return keyword in the function description if we have only one line in it. It automatically returns the one statement without defining the return keyword explicitly.

let subFn = (message,x) => message.substring(x);

Stabilizing this with Arrow Function

In Javascript, the use of this for calling context inside a function is confusing for long. But arrow function solves this problem defining the calling context of arrow function properly. 

let employee = {
	name: "Aanchal",
	getName: function() {
	  console.log(this.name); // Will print Aanchal on the console.
	}
};
employee.getName();

In the above function, Aanchal will get printed on the console. Here this points to an employee object. But if we have something like below:

let employee = {
	name: "Aanchal",
	getName: function() {
            setTimeout(function(){
               console.log(this.name); // Will print undefined or show error
            },500)
	  }
};
employee.getName();

In the above example, the calling context for function passed to getName function is an employee as we have written employee.getName(). But the anonymous function passed to setTimeout() doesn't have its calling context as an employee. So we are getting undefined or error. This problem can be solved using the arrow function in ES6. With the arrow function, the calling context is defined by the surrounding code. If this points to something suppose x outside arrow function, it will point to the same x inside arrow function as well. The value is defined by its surrounding code context. If we run the above code using the arrow function, then we will get the same object using this keyword. The value inside the arrow function will be same outside it as well.

let employee = {
	name: "Aanchal",
	getName: function() {
               console.log(this.name); // Will print Aanchal
            setTimeout(() =>{
               console.log(this.name); // Will print Aanchal
            },500)
	  }
};
employee.getName();


Comments