ES6 version of TypeScript provides an arrow function which is the shorthand syntax for defining the anonymous function, i.e., for function expressions. It omits the function keyword. We can call it fat arrow (because -> is a thin arrow and => is a "fat" arrow). It is also called a Lambda function. The arrow function has lexical scoping of "this" keyword.
The motivation for arrow function is:
We can split the syntax of an Arrow function into three parts:
(parameter1, parameter2, ..., parameterN) => expression;
If we use the fat arrow (=>) notation, there is no need to use the function keyword. Parameters are passed in the brackets (), and the function expression is enclosed within the curly brackets {}.
There are two ways of writing a function in ES5 and ES6 style of coding.
// ES5: Without arrow function var getResult = function(username, points) { return username + ' scored ' + points + ' points!'; }; // ES6: With arrow function var getResult = (username: string, points: number): string => { return `${ username } scored ${ points } points!`; }
The following program is an example of arrow function with parameters.
let sum = (a: number, b: number): number => { return a + b; } console.log(sum(20, 30)); //returns 50
In the above example, the sum is an arrow function, "a: number, b: number" is a parameter type, ": number" is the return type, the arrow notation => separates the function parameter and the function body.
After compiling the above TypeScript program, the corresponding JavaScript code is:
let sum = (a, b) => { return a + b; }; console.log(sum(20, 30)); //returns 50
The following program is an example of arrow function without parameters.
let Print = () => console.log("Hello rookienerd!"); Print();
In the arrow function, if the function body consists of only one statement, then there is no need of the curly brackets and the return keyword. We can understand it from the below example.
let sum = (a: number, b: number) => a + b; console.log("SUM: " +sum(5, 15));
We can include the arrow function as a property in a class. The following example helps to understand it more clearly.
class Student { studCode: number; studName: string; constructor(code: number, name: string) { this.studName = name; this.studCode = code; } showDetail = () => console.log("Student Code: " + this.studCode + '\nStudent Name: ' + this.studName) } let stud = new Student(101, 'Abhishek Mishra'); stud.showDetail();