The famous lambda functions (aka arrow functions)

   



Lambda functions (or anonymous functions) are a fundamental concept in functional programming and are commonly used in languages ​​such as JavaScript.

In JavaScript, a lambda function is simply a function that does not have a specific name and is defined inline, often as an argument to another function or as a return from a function. These functions are compact, concise, and are used in situations where it is not necessary to define a complete function with a name.

🔗 Do you like Techelopment? Check out the website for all the details!

Lambda Functions in action

Lambda functions are also known as anonymous functions or arrow functions, in the case of JavaScript with the => syntax introduced in ECMAScript 6 (ES2015). Their compact and powerful syntax allows you to write functional code in a more expressive and readable way.

1. Anonymoys function with function

In JavaScript, an anonymous function can be defined using the function keyword, without an associated name. Here's an example:


const numbers = [1, 2, 3, 4, 5];

// Anonymous fuction passed to a map()
const results = numbers.map(function(num) {
  return num * 2;  // Multiply each number by 2
});

console.log(results);  // [2, 4, 6, 8, 10]

In this example, the anonymous function function(num) { return num * 2; } is passed as an argument to the map() method to multiply each element of the array by 2.

2. Arrow Functions (Lambda-compatible syntax)

Starting with ECMAScript 6 (ES6), the arrow functions syntax (=>) was introduced, which is a more concise way of writing anonymous functions. The syntax is as follows:


const numbers = [1, 2, 3, 4, 5];

// Arrow function
const results = numbers.map(num => num * 2);

console.log(results);  // [2, 4, 6, 8, 10]

In this case, num => num * 2 is an arrow function that performs the same task as the anonymous function above, but in a more compact way.

It's important to note that arrow functions don't have their own this, which makes them particularly useful in some scenarios (usually when you want to avoid scoping issues with the this).


Lambda Functions syntax

Let's start with a practical example of lambda functions to filter the elements of an array. Imagine having an array of numbers and wanting to get only the even ones:


const numbers = [1, 2, 3, 4, 5, 6];

// Using filter with a lambda function
const evenNumbers = numbers.filter(num => num % 2 === 0);

console.log(evenNumbers);  // [2, 4, 6]

In this case, the lambda function num => num % 2 === 0 is used to filter out even numbers from the array, but how exactly does this syntax work? Let's try to understand it better by comparing it with traditional (imperative) programming.

Basic syntax

The syntax of an arrow function is as follows:


const functionName = (param1, param2, ...) => {
  // function body
}


1. Funzione con due o più parametri

With Arrow Function:


const sum = (a, b) => {
    return a + b;
};

console.log(sum(3, 5)); // 8

Without Arrow Function:


function sum(a, b) {
    return a + b;
}

console.log(sum(3, 5)); // 8
 

In this case, the behavior is the same, but the arrow function is more concise.

2. Function with only one parameter and that returns a value directly

With Arrow Function:


const square = x => x * x;

console.log(square(4)); // 16

Without Arrow Function:


function square(x) {
  return x * x;
}

console.log(square(4)); // 16

If there is only one input parameter to the function (x) and only one operation that the function must perform (x * x), the parentheses (both round and curly) are not needed and it is possible to eliminate the return.

3. Function without parameters

With Arrow Function:


const greet = () => console.log('Hello!');

greet(); // "Hello!"

Without Arrow Function:


function greet() {
  console.log('Hello!');
}

greet(); // "Hello!"

If there are no input parameters, you need to use parentheses ().

4. Function with multiple lines of code

With Arrow Function:


const operation = (a, b) => {
  const sum = a + b;
  const product = a * b;
  return sum + product;
};

console.log(operation(2, 3)); // 11 (5 + 6)

Without Arrow Function:


function operation(a, b) {
  const sum = a + b;
  const product = a * b;
  return sum + product;
}

console.log(operation(2, 3)); // 11 (5 + 6)

Again, the arrow function doesn't change the logic, but it's a little more compact in writing.

5. Function that returns an object

With Arrow Function:


const createObject = (name, age) => ({
  name: name,
  age: age
});

console.log(createObject("Francesco", 30)); // { name: "Francesco", age: 30 }

Without Arrow Function:


function createObject(name, age) {
  return {
    name: name,
    age: age
  };
}

console.log(createObject("Francesco", 30)); // { name: "Francesco", age: 30 }

In this case, the arrow function allows you to omit the return keyword and the curly braces, making the code more compact.

6. Context of this

One of the main differences between arrow functions and traditional functions is how they handle the context of this.

Without Arrow Function:


const person = {
  name: "Francesco",
  greet: function() {
    setTimeout(function() {
      console.log("Hello, I am " + this.name);  // `this` does not refer to the `person` object
    }, 1000);
  }
};

person.greet(); // "Hello, I am undefined"

In the case of the traditional function, when the function is passed to setTimeout, the context of this changes and no longer refers to the person object.

With Arrow Function:


const person = {
  name: "Francesco",
  greet: function() {
    setTimeout(() => {
      console.log("Hello, I am " + this.name);  // `this` correctly refers to the `person` object
    }, 1000);
  }
};

person.greet(); // "Hello, I am Francesco"

With the arrow function, this maintains the context of the person object, avoiding the context loss problem.

8. Unable to use new with arrow functions

Arrow functions cannot be used as object constructors, so you cannot call them with new.

Without Arrow Function:


function Person(name) {
  this.name = name;
}

const p = new Person('Francesco');
console.log(p.name); // Francesco

With Arrow Function:


const Person = (name) => {
  this.name = name; // it doesn't work as expected
};

const p = new Person('Francesco'); // TypeError: Person is not a constructor

Arrow functions do not have their own this, so they cannot be used as constructors, causing an error if you try to use them with new.


Key concepts

Lambda functions (or arrow functions) are one of the main tools of functional programming in JavaScript:

  • More concise syntax: Arrow functions are generally shorter and more readable, especially when dealing with callback functions or when returning values ​​directly.
  • Context of this: Arrow functions do not change the context of this, so they are very useful when you want to preserve the value of this from the context in which the function is defined.
  • Cannot be used as constructors: Arrow functions cannot be used with new, while traditional functions can.

In JavaScript, adopting lambda functions allows you to write more elegant code, reduce the number of lines of code, and improve understanding of the execution flow. As a key concept in modern programming, lambda functions are an essential skill for any developer working with functional languages ​​or JavaScript.


Follow me #techelopment

Official site: www.techelopment.it
facebook: Techelopment
instagram: @techelopment
X: techelopment
Bluesky: @techelopment
telegram: @techelopment_channel
whatsapp: Techelopment
youtube: @techelopment