Hello coders ๐Ÿ‘‹, This is going to be our 9th question of the front-end interview questions series you can access all the questions by clicking here

Higher Order Function

A function that returns a function or takes other functions as arguments is called a higher-order function. —MDN

Let’s write two functions findEven and findOdd to filter even and odd numbers. We will refactor them latter.

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

function findEven(nums) {
  const results = [];

  for (let i = 0; i < nums.length; i++) {
    if (nums[i] % 2 === 0) {
      results.push(nums[i]);
    }
  }

  return results;
}

function findOdd(nums) {
  const results = [];

  for (let i = 0; i < nums.length; i++) {
    if (nums[i] % 2 !== 0) {
      results.push(nums[i]);
    }
  }

  return results;
}
console.log(findEven(numbers)); // Output: [2, 4, 6, 8, 10, 12]
console.log(findOdd(numbers)); // Output: [1, 3, 5, 7, 9, 11]

In the above example findEven accepts an array of numbers and returns array of even numbers, and the same goes for the findOdd and it returns an array of odd numbers.

If we see the above example closely, both functions’s logic is almost the same except the conditions, let’s try to abstact the common logic.

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

// myFilter is Higher Order Function because it accepting function as an argument
function myFilter(nums, callback) {
  const results = [];
  for (let i = 0; i < nums.length; i++) {
    const num = nums[i];
    if (callback(num)) {
      results.push(num);
    }
  }
  return results;
}

// Callback function
function isEven(num) {
  return num % 2 === 0;
}

// Callback function
function isOdd(num) {
  return num % 2 !== 0;
}

// Passing isEven and isOdd functions as an argument in myFilter function
console.log(myFilter(numbers, isEven)); // Output: [2, 4, 6, 8, 10, 12]
console.log(myFilter(numbers, isOdd)); // Output: [1, 3, 5, 7, 9, 11]

Note: A callback function in JavaScript is a function that is passed as an argument to another function.

In the above example the myFilter function is a Higher Order Function because it accepts a function as an argument.

I hope the above example has given you the clear understanding of Higher Order Functions and how to use them.

Built-in Higher Order functions in JavaScript

There are many built-in Higher Order functions in JavaScript, There are some of them being mentioned below.

Benefits of Higher Order functions

  • Reusability: Encapsulate common logic, avoid repetition.
  • Readability: Clear intent through function names and callbacks.
  • Functional Style: Mutability, pure functions for predictable code.
  • Composability: Chain HOFs for complex logic, no rewrites.
  • Efficiency: Optimized data processing, built-in HOFs often faster than loops.

If you find this helpful please share with your network โœ….

Happy Coding ๐Ÿ™Œ !