JavaScript: A Guide to Higher Order Methods, Functions, and Callbacks

Higher Order Functions in JavaScript

In JavaScript, a higher order function is a function that can accept other functions as arguments or return them as values. These functions provide a level of abstraction, allowing for more modular and reusable code.

Characteristics of Higher Order Functions

  1. Accepts Functions as Arguments: A higher order function can take other functions as parameters, allowing for customization of its behavior.

  2. Returns Functions: It can also return functions as results, enabling the creation of more dynamic and adaptable code structures.

Example: Function as an Argument

function operateOnNumbers(numbers, operation) {
  return numbers.map(operation);
}

const squareNumber = num => num ** 2;

const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = operateOnNumbers(numbers, squareNumber);

Here our operateOnNumbers is a Higher Order Function Which take another function as an argumernt like squareNumber is a function which will simply square the digit of numbers array

Example: Return Function

function multiplier(factor) {
  return function (number) {
    return number * factor;
  };
}

const double = multiplier(2);
console.log(double(5));

Now here our function multiplier is returning another function to double this is also possible in case of Higher order function. The function return an another function is a concept in javaScript call Closures. You can read More about closures from here : Closures

##Higher Order Method's In JavaScript In JavaScript, higher order methods are functions that take other functions as arguments or return functions as results. Here are some common higher order methods in JavaScript, particularly associated with arrays:

  • Map
  • Filter
  • Reduce
  • For Each
  • Sort
  • Find
  • Some
  • Every

Example: Map()

Applies a function to each element in an array and returns a new array with the results. Current Value (currentValue): The current element being processed in the array. Current Index (currentIndex): The index of the current element being processed. Source Array (array): The array reduce() was called upon.*

const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(num => num * num);

Example: Filter()

Creates a new array with elements that satisfy a given condition. Current Value (currentValue): The current element being processed in the array. Current Index (currentIndex): The index of the current element being processed. Source Array (array): The array reduce() was called upon.*

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);

Example: Reduce()

Reduces an array to a single value by applying a function cumulatively Accumulator (acc): The accumulated result of the previous iterations. Current Value (currentValue): The current element being processed in the array. Current Index (currentIndex): The index of the current element being processed. Source Array (array): The array reduce() was called upon.

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
//0 is the starting value of an accumulator

Example: forEach()

Executes a provided function once for each array element. Current Value (currentValue): The current element being processed in the array. Current Index (currentIndex): The index of the current element being processed. Source Array (array): The array reduce() was called upon.*

const numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => console.log(num));

Example: Sort()

  • Sorts the elements of an array in place.*
    const fruits = ['banana', 'apple', 'orange', 'grape'];
    const sortedFruits = fruits.sort();
    //sortedFruits-['apple','banana','grape','orange']
    

Example: Find()

Returns the first element in an array that satisfies a provided testing function.

const numbers = [1, 2, 3, 4, 5];
const foundNumber = numbers.find(num => num > 3);

Example: Some()

Checks if at least one element in an array satisfies a condition.

const numbers = [1, 2, 3, 4, 5];
const hasEvenNumber = numbers.some(num => num % 2 === 0);

Example: Every()

Checks if all elements in an array satisfy a condition.

const numbers = [1, 2, 3, 4, 5];
const allArePositive = numbers.every(num => num > 0);

CallBack Functions:

Callback Functions are functions passed as arguments to other functions, executed later to handle asynchronous operations or events.

setTimeout() with Callback:

function OrderPlaced(name, callback) {
  console.log(`Hello, ${name}! order has been placed sucessfully`);
  callback();
}

function OrderReady() {
  console.log("Order Is ready");
}

// Callback function (OrderReady) is executed after the OrderPlaced 
OrderPlaced("Manav Goyal", OrderReady);