VOOZH about

URL: https://www.geeksforgeeks.org/typescript/what-are-arrow-lambda-functions-in-typescript/

⇱ What are Arrow/lambda functions in TypeScript ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

What are Arrow/lambda functions in TypeScript ?

Last Updated : 23 Jan, 2025

Arrow functions in TypeScript (also known as lambda functions) are concise and lightweight function expressions using the => syntax.

  • Provide a shorter syntax for defining functions.
  • Automatically bind the context of their surrounding scope.
  • It is commonly used for callbacks, array methods, and simple one-liner functions.

Syntax:

(param1, param2, ..., paramN) => expression; //Arrow function having multiple parameters
() => expressions; //Arrow function with no parameters

Output:

Hello, Alice!

More Example of Arrow function in TypeScript

Arrow Function in a Class

  • The Calculator class includes an add method defined as an arrow function, which takes two numbers and returns their sum.
  • Using an arrow function ensures that the method inherits the this context from its enclosing class.

Output:

8

Arrow Function with Array Methods

  • An arrow function is used within the map method to square each number in the numbers array.
  • This concise syntax enhances readability when performing operations on array elements.

Output: 

[1, 4, 9, 16, 25]

Arrow Function as a Callback

  • An arrow function is passed as a callback to setTimeout, which logs a message after a 1-second delay.
  • Arrow functions are ideal for inline callbacks due to their concise syntax and lexical this binding.

Output:

This message is displayed after 1 second.

Best Practices for Using Arrow Functions in TypeScript

  • Use Arrow Functions for Short Callbacks: Arrow functions are ideal for short and concise callback functions in methods like map, filter, and reduce.
  • Avoid Arrow Functions for Methods in Classes: Use regular functions for class methods that require dynamic this binding, as arrow functions inherit the this context.
  • Return Object Literals Correctly: Wrap object literals in parentheses when returning them in single-line arrow functions to avoid syntax errors.
  • Use Arrow Functions to Maintain this Context: Arrow functions are useful in scenarios where you want to preserve the this context in event handlers or asynchronous code.
Comment
Article Tags:

Explore