How to Use Lambda Expression in TypeScript?


Lambda expressions offer a succinct and expressive means of defining functions in TypeScript and are versatile enough to be utilized as class methods, object properties, and callbacks in higher-order functions. This tutorial aims to delve into the syntax of lambda expressions, highlight their advantages over conventional functions, and provide guidance on how to use lambda expressions in TypeScript effectively.

What are Lambda Expressions?

Lambda expressions, commonly referred to as arrow functions, were first introduced in ECMAScript 6 and have gained widespread usage in contemporary JavaScript and TypeScript code. These expressions provide a succinct syntax for defining functions in both languages. Although similar to conventional JavaScript functions, they have a few notable distinctions.

Syntax

This is the basic syntax for declaring a lambda expression/arrow function in typescript −

(parameter1: type, parameter2: type, ...) => expression

The parameters of the function are denoted by "parameter1", "parameter2", and so on, and their respective data types are specified by the "type" keyword. The function body can be of a single expression or a statement block enclosed in curly braces. In the former case, the expression is evaluated and returned when the function is invoked.

The parenthesis can be omitted in the lambda function definition when there is just one parameter. Here's an example −

parameter1: type => expression;

This lambda expression takes a single parameter, and returned value expression can be a single value or a statement block enclosed in curly braces.

Using Lambda Expressions in TypeScript

Utilizing lambda expressions in TypeScript is a straightforward process - we simply declare a variable using the "const" or "let" keyword, followed by the syntax for lambda expressions.

Example 1

Lambda expressions allow us to define traditional functions and invoke them by utilizing the variable name and passing in the relevant parameters. Here's an example of a "multiply" function that accepts three arguments of type "number"

// traditional function declaration
function multiplyTraditional(x: number, y: number, z: number): number {
   return x * y * z;
}
// lambda expression or arrow function declaration
const multiplyLambda = (x: number, y: number, z: number): number => x * y *z;
console.log(`The output of multiplyTraditional function is: ${multiplyTraditional(2, 2, 5)}`);
console.log(`The output of multiplyLambda function is: ${multiplyLambda(2, 2, 5)}`);

On compiling, it will generate the following JavaScript code −

// traditional function declaration
function multiplyTraditional(x, y, z) {
   return x * y * z;
}
// lambda expression or arrow function declaration
var multiplyLambda = function (x, y, z) { return x * y * z; };
console.log("The output of multiplyTraditional function is: ".concat(multiplyTraditional(2, 2, 5)));
console.log("The output of multiplyLambda function is: ".concat(multiplyLambda(2, 2, 5)));

Output

The above code will produce the following output −

The output of multiplyTraditional function is: 20
The output of multiplyLambda function is: 20

Example 2

Lambda expressions are also useful as callbacks in functions such as array methods (e.g., map, filter, reduce). Here's an example demonstrating their usage with the "map" method −

const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(x => x * x);
console.log(`Original array: ${numbers}`);
console.log(`Squared array: ${squaredNumbers}`);

The following lambda expression accepts a single parameter and returns its square. By applying this expression to each element of the array using the "map" method, a new array consisting of squared numbers is generated.

On compiling, it will generate the following JavaScript code −

var numbers = [1, 2, 3, 4, 5];
var squaredNumbers = numbers.map(function (x) { return x * x; });
console.log("Original array: ".concat(numbers));
console.log("Squared array: ".concat(squaredNumbers));

Output

The above code will produce the following output −

Original array: 1,2,3,4,5
Squared array: 1,4,9,16,25

Example 3

Lambda expressions can be employed as class methods or object properties in TypeScript. Below is an example of a class that includes a method composed as a lambda expression −

class Calculator {
   add = (x: number, y: number, z: number): number => x + y + z;
}
const objec = new Calculator();
console.log(`The result is: ${objec.add(4, 3, 2)}`);

In this example, the add method, which is a property of the Calculator class, is defined as a lambda expression.

On compiling, it will generate the following JavaScript code −

var Calculator = /** @class */ (function () {
   function Calculator() {
      this.add = function (x, y, z) { return x + y + z; };
   }
   return Calculator;
}());
var objec = new Calculator();
console.log("The result is: ".concat(objec.add(4, 3, 2)));

Output

The above code will produce the following output −

The result is: 9

Example 4

Higher-order functions which are functions that accept one or more functions as arguments and/or return a function as a result can be conveniently defined using lambda expressions in TypeScript.

const applyOp = (x: number, y: number, operation: (a: number, b: number) => number) => {
   return operation(x, y);
};
const result1 = applyOp(10, 20, (a, b) => a + b); // 30
console.log(result1);
const result2 = applyOp(10, 20, (a, b) => a * b); // 200
console.log(result2);

Consider the following example: we pass two numbers and a function to the "applyOp" function. This function returns the outcome of the passed function, which operates on the two number parameters.

On compiling, it will generate the following JavaScript code −

var applyOp = function (x, y, operation) {
   return operation(x, y);
};
var result1 = applyOp(10, 20, function (a, b) { return a + b; }); // 30
console.log(result1);
var result2 = applyOp(10, 20, function (a, b) { return a * b; }); // 200
console.log(result2);

Output

The above code will produce the following output &inus;

30
200

Example 5

Lambda expressions in TypeScript have lexical scoping and behave as closures, meaning they have access to variables defined in the same scope as the lambda expression. Upon being defined, a lambda expression captures the values of any variables in scope and applies them when executed at a later time.

Here is an example demonstrating the same.

function declareCounter() {
   let count = 0;
   return () => {
      count++;
      console.log(`Current count is ${count}`);
   };
}

const counter = declareCounter();
counter();  // Current count is 1
counter(); // Current count is 2

The "declareCounter" function in the following example returns a lambda expression that increments and logs the "count" variable each time it is invoked. The "count" variable is defined in the same scope as the lambda expression, enabling the lambda expression to access its value and update it.

By calling the "counter" function twice, the current count is logged twice, starting at 1 and increasing by 1 each time the lambda expression is executed.

On compiling, it will generate the same JavaScript code as above.

Output

The JavaScript code will produce the following output −

Current count is 1
Current count is 2

Benefits of Using Lambda Expressions in TypeScript

Lambda expressions offer several advantages over traditional functions −

  • Conciseness − By providing a more compact syntax, lambda expressions allow us to write functions that are easier to read and understand.

  • Clarity − When employed as a callback in a higher-order function like map or filter, lambda expressions can make the function's purpose more evident.

  • Performance − Due to their simplified syntax, lambda expressions can sometimes be quicker than traditional functions, as they can be optimized by the JavaScript engine.

  • Scope − Lambda expressions possess lexical scoping, enabling them to access variables within the surrounding scope, leading to potent and adaptable programming techniques like currying and memoization.

Conclusion

Lambda expression in TypeScript offers several benefits, such as clarity, conciseness, scope, and performance. They can be employed as class methods, object properties, and callbacks in higher-order functions. By utilizing concise syntax and lexical scoping, you can create more expressive and modular code. However, as lambda expressions become more complex, they may become harder to read, making traditional functions a better choice for such scenarios. Nevertheless, by and large, lambda expressions enhance code readability and maintainability.

Updated on: 04-Sep-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements