Callback Functions, Higher-Order Functions, and Higher-Order Methods

First of all,

Greetings! Today, let's explore the fascinating world of programming sophistication by shedding light on callback functions, higher-order functions (HOFs), and higher-order methods (HOMs). These concepts serve as the building blocks for crafting code that is not only efficient but also elegantly modular.

Higher-Order Methods:

Functions that operate on other functions by returning them or accepting them as arguments are referred to as higher-order methods, or HOMs for short. Functional programming, where functions are seen as first-class citizens, is the foundation of this idea. HOMs are frequently used with arrays and collections in programming languages such as Python and JavaScript.

Some of the higher-order methods we generally use are:

  • map()

Consider the following block of code, which uses the "map" method.

The map() method in JavaScript is used to create a new array by applying a provided function to each element of an existing array. It's a convenient way to transform each element of an array without modifying the original array. Here's an example code:

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

// Using map to create a new array with squared numbers
const squareNumbers = number.map((num) => num * 2);
console.log(squareNumbers);
//output
[2,4,6,8,10]
  • filter()

Consider the following block of code, which uses the "filter" method.

The filter() method in JavaScript is used to create a new array by filtering out elements from an existing array based on a provided condition. It's a concise and powerful way to selectively include or exclude elements from an array. Here's an example code:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Using filter to get even numbers
const evenNumbers = numbers.filter(function (number) {
  return number % 2 === 0;
});

console.log(evenNumbers);
//output
[2, 4, 6, 8, 10]
  • reduce()

Consider the following block of code, which uses the "reduce" method.

The reduce() method in JavaScript is used to reduce the elements of an array to a single value. It iterates over the array, applying a provided function to each element, and accumulates the result. The result can be of any type; it could be a number, a string, an object, or even another array. Here's an example code:

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

// Using reduce to calculate the sum of all numbers
const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);

console.log(sum);
//output
15
  • forEach()

Consider the following block of code, which uses the "forEach" method.

The forEach() method in JavaScript is used to iterate over elements in an array and execute a provided callback function for each element. It's a simple and effective way to act on each item in an array without creating a new array. Here's an example code:

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

// Using forEach to log each number to the console
numbers.forEach((num) => {
  console.log(num);
});
//output
1
2
3
4
5

Higher-Order Functions:

A function that receives another function as an argument or that returns a new function or both is called a higher-order function. Higher-order functions are only possible because of the first-class function.

Example 1: Functions returning another function.

// Define a function called greet that takes a 'name' parameter
const greet = function(name) {
  // Return an inner function
  return function(m) {
    // Log a message to the console using the 'name' parameter and the provided 'm' parameter
    console.log(`Hi!! ${name}, ${m}`);
  };
};

// Call the greet function with the argument 'ABC' and assign the returned inner function to 'greet_message'
const greet_message = greet('ABC');

// Invoke the inner function with the argument "Welcome To GeeksForGeeks"
greet_message("Welcome To GeeksForGeeks");
//output
Hi!! ABC, Welcome To GeeksForGeeks

Example 2: Passing a function as an argument.

// Define a function called greet that takes a 'name' parameter
function greet(name) {
  // Return a greeting string using the provided 'name'
  return `Hi!! ${name} `;
}

// Define a function called greet_name that takes three parameters: a greeting function, a 'message', and a 'name'
function greet_name(greeting, message, name) {
  // Log a message to the console by combining the result of the 'greeting' function with the 'message'
  console.log(`${greeting(name)} ${message}`);
}

// Call the greet_name function with the 'greet' function as the greeting, the message 'Welcome To GeeksForGeeks', and the name 'JavaScript'
greet_name(greet, 'Welcome To GeeksForGeeks', 'JavaScript');
//output
Hi!! JavaScript  Welcome To GeeksForGeeks

Key points regarding higher-order functions:

  • The function receives another function as an argument or returns First-order a new function or both.

  • The “higher-order” concept can be applied to functions in general, like functions in the mathematical sense.

  • The presence of a higher-order function does not imply the presence of a first-order function.

Callback function:

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

A callback's primary purpose is to execute code in response to an event. These events might be user-initiated, such as mouse clicks or typing. With a callback, you may instruct your application to "execute this code every time the user clicks a key on the keyboard."
Here's an example code:

// Get the HTML element with the id 'button' and assign it to the variable 'button'
const button = document.getElementById('button');

// Define a callback function named 'callback'
function callback() {
  // Log the message "Hello world" to the console when this function is called
  console.log("Hello world");
}

// Add an event listener to the 'button' element for the 'click' event, triggering the 'callback' function when clicked
button.addEventListener('click', callback);

In the above code, we add addEventListener as a function, and we are passing another function callback as an argument. And when a click event is triggered, the addEventListener registers the callback function.

Benefits of Callback Function

Callback functions are needed because many JavaScript actions are asynchronous. Instead, it executes in the background while the rest of the code runs. A callback's purpose is to execute code in response to an event. These events can be like mouse clicks; with callback, we can add text at the end of each statement, like execute this code every time the user clicks a key on the keyboard."