Horje
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

1. Arrow function having multiple parameters:

(param1, param2, ..., paramN) => expression;

2. Arrow function with no parameters:

() => expressions;

Example: 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. 

TypeScript
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:

TypeScript
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.

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

Output:

this is horje

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.

TypeScript
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



Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
Spring with Xstream Spring with Xstream
How to Install Multiple JDK’s in Windows? How to Install Multiple JDK’s in Windows?
Git - Environment Setup Git - Environment Setup
Spring MVC - Exception Handling Spring MVC - Exception Handling
Spring Boot - Starter Test Spring Boot - Starter Test

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
10