Open In App

What are Arrow/lambda functions in TypeScript ?

Last Updated : 07 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Arrow function having multiple parameters:

    (param1, param2, ..., paramN) => expression;
  • Arrow function with no parameters:

    () => expressions;

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. 

Javascript




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:

Javascript




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.

Javascript




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.

Javascript




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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads