Higher Order Methods, Higher Order Function, Callback function in JavaScript

What is a Higher Order Function?

A higher order function is a function that takes one or more functions as arguments, or returns a function as its result.

// Callback function, passed as a parameter in the outerloop function
function callbackFunction(){
    console.log("callback function called")
}
function outerloop(callback){
    console.log("outer loop")
    callbackFunction()
}
outerloop(callbackFunction)
  • Higher-order functions offer flexibility and enable more dynamic and reusable code by allowing functions to be passed around as values.

What are Higher Order Methods?

Higher order methods make code reusable, abstracting away repetitive tasks, and offering flexibility by letting functions team up creatively.

Higher Order Methods in Action:

1. Map

  • The map method creates a new array by calling a provided function on every element in the calling array and after the element undergoes the operation and it returns make changes in the original Array.

    Parameters :

  • callback (Function): Function that produces an element of the new array, taking three arguments:

    • currentValue (required): The current element being processed in the array.

    • index (optional): The index of the current element being processed.

    • array (optional): The array map was called upon.

const numbers = [1, 2, 3];
const squared = numbers.map((num, index, array) => {
  console.log(`Index: ${index}, Array: ${array}`);
  return num * num;
});
// squared will be [1, 4, 9]

2. Filter

The filter method creates a new array with all elements that pass the test implemented by the provided function.

Parameters :

  • callback (Function): Function that produces an element of the new array, taking three arguments:

    • currentValue (required): The current element being processed in the array.

    • index (optional): The index of the current element being processed.

    • array (optional): The array filter was called upon.

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
// Output :- evenNumbers will be [2, 4]

3. Reduce

The reduce method executes a reducer function on each element of the array, resulting in a single output value.

Parameters:

  • callback (Function): Function that executes on each element of the array, taking four arguments:

    • accumulator (required): The accumulated value previously returned in the last invocation of the callback, or initialValue if supplied.

    • currentValue (required): The current element being processed in the array.

    • index (optional): The index of the current element being processed.

    • array (optional): The array reduce was called upon.

    • initialValue (optional): Value to use as the first argument to the first call of the callback.

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, curr, index) => {
  console.log(`Index: ${index}`);
  return acc + curr;
}, 0);
// sum will be 15

4. forEach

  1. The forEach method executes a provided function once for each array element.

    Parameters:

    • callback (Function): Function to execute on each element, taking three arguments:

      • currentValue (required): The current element being processed in the array.

      • index (optional): The index of the current element being processed.

      • array (optional): The array forEach was called upon.

const numbers = [1, 2, 3];
numbers.forEach((num, index) => {
  console.log(`Index: ${index}`);
  console.log(num);
});
// Output: 1, 2, 3 (prints each number)

What is Callback function?

Callback function is essentially a function that gets passed as an argument to another function. The function receiving the callback can then execute or call this function at a certain point within its own code.

function bakeCookies(callback) {
  callback();
}
function eatCookies() {
  console.log("Yum! These cookies are delicious!");
}
bakeCookies(eatCookies);

when bakeCookies finishes baking the cookies, it calls the eatCookies function (the callback) to do something extra (in this case, just logging a message). This way, the bakeCookies function doesn't need to know exactly what to do after baking; it just knows to call whatever function you give it as a callback.

Conclusion :-

  • Higher-order functions and their associated methods like map, filter, reduce, and forEach in JavaScript are powerful tools that enable cleaner, reusable code by working with functions as values. They allow you to perform actions on arrays, like transforming elements (map), filtering them (filter), combining them into a single value (reduce), or executing a function for each element (forEach).

  • Callback functions are simply functions passed as arguments to other functions. They help separate concerns, making code more modular. For instance, a callback passed to a function can be executed at a specific point, allowing flexibility in behavior without the function needing specific knowledge about what that behavior might be. This flexibility and modularity make your code more maintainable and easier to extend.