Sobes.tech
Junior

What is a first-class function?

sobes.tech AI

Answer from AI

The first-order function (Higher-Order Function) in Node.js, as in other languages supporting functional programming, is a function that:

  • Takes one or more functions as arguments.
  • Returns another function as a result.

This allows creating abstractions, combining functions, and managing the flow of execution more flexibly.

Examples of usage:

  • Callback functions: Passing a function that will be called after an asynchronous operation completes.
  • Array manipulation functions: map, filter, reduce accept a function that is applied to each element of the array.
  • Decorators or wrapper functions: Functions that add additional logic to another function.
// Example of a higher-order function that takes another function as an argument
function createMultiplier(multiplier) {
  return function(number) { // Returns a new function
    return number * multiplier;
  };
}

const double = createMultiplier(2);
const triple = createMultiplier(3);

console.log(double(5)); // 10
console.log(triple(5)); // 15

// Example of using callback in an asynchronous operation (simplified)
function fetchData(url, callback) {
  // Simulating an API request
  setTimeout(() => {
    const data = `Data from ${url}`;
    callback(data); // Calling the passed callback function
  }, 1000);
}

fetchData('https://example.com', (data) => {
  console.log('Received:', data);
});

// Example of using Array.prototype.map
const numbers = [1, 2, 3];
const doubledNumbers = numbers.map((num) => { // map takes a function
  return num * 2;
});
console.log(doubledNumbers); // [2, 4, 6]

Main advantages of using first-order functions:

  • Increased abstraction: They allow hiding implementation details and working at a higher level.
  • Code reuse: Functions can be easily reused in different contexts.
  • Improved readability: The code becomes more declarative and understandable.
  • Support for composition: They make it easy to combine functions to create more complex operations.
What is a first-class function? — Node.js - sobes.tech