Lambda Expressions in JavaScript

A lambda expression is a concise way to define a short function in programming. It’s commonly found in modern languages like Ruby, JavaScript, and Java. Essentially, it’s just a small piece of code that creates a function.

Support for first-class functions is crucial in programming languages. This means functions can be passed as arguments to other functions or assigned to variables. Lambda expressions, also known as arrow function expressions in JavaScript, are recognized by compilers through specific syntax in the source code. At runtime, these expressions are evaluated and stored as lambda functions in memory.

A lambda function, also known as an anonymous function, is a short function in JavaScript that takes one or more parameters and consists of a single expression. In essence, you can pass a function as a parameter to another function. Thanks to functions being treated as objects in JavaScript, they can be passed to and returned from other functions, allowing the creation of lambda functions.

Advantages of Javascript Lambda Functions:

  1. Lambda functions are pure functions in Javascript.
  2. Lambda functions are easy to read.
  3. Lambda functions are easy to cache.

Syntax:

function(arg1, arg2...argn) expression

Example 1: In this example, the arrow function is used for showing lambda expression.

Javascript
let multiply = (a, b) => a * b;
console.log(multiply(5, 9));

Output:

45

In this example, the arrow function is used and we have taken two parameters and have a single expression.

Example 2: In this example, an anonymous function is used which shows the lambda expression.

Javascript
const Names = [
  'Mansi',
  'Gaurav',
  'Akansha',
  'Sanya'
];

console.log(Names.map(Names => Names.length));

Output:

[ 5, 6, 7, 5 ]

In this example, an anonymous function is created which makes the code small and returns the length of Names in the array.


Contact Us