Open In App

What are Arrow/lambda functions in TypeScript ?

The Arrow/ lambda function is a concise form of a normal function in Typescript. Arrow functions are also known as lambda functions. We use “=>” (arrow symbol) in the arrow function and we do not use the ‘function’ keyword. We can use this method when we want our code to be short and not call the function each time. 

Syntax:



Example 1 (Arrow function with parameters): In the below code, we create an arrow function with two parameters name and roll_no. The function returns a string that contains two parameters. We use { } curly brackets and return keyword. 




let string1 = (name: string, roll_no: number) => {
  return "i am " + name + " and my roll no is "
  + `${roll_no.toString()}`;
};
  
console.log(string1("srinivas", 49));

Output: 

i am srinivas and my roll no is 49

Generally, when we have only one statement to execute we don’t need to use  { } curly brackets and return keywords. We can write the code as below:




let string1 = (name: string, roll_no: number) =>
  "i am " + name + " and my roll no is " 
  + `${roll_no.toString()}`;
  
console.log(string1("srinivas", 49));

Output:

i am srinivas and my roll no is 49

Example 2(Arrow function without parameters): This is an example where the arrow function takes no parameters and returns a string.




let str1 = () => "this is geeksforgeeks";
console.log(str1());

Output:

this is geeksforgeeks

Example 3 (Arrow function in a class): A class is created which has two properties, name of type string and CGPA of type number. There’s also a class method that returns and displays a string of the student details. This example shows arrow functions can also be used in classes.




class StudentDetail {
  name: string;
  cgpa: number;
  
  constructor(name: string, cgpa: number) {
    this.name = name;
    this.cgpa = cgpa;
  }
  
  displayString = () =>
    console.log("student_name : " + this.name + 
    " student_cgpa : " + this.cgpa);
}
  
let student1 = new StudentDetail("sarah", 9.45);
student1.displayString();

Output:

student_name : sarah student_cgpa : 9.45

Article Tags :