Skip to main content

Command Palette

Search for a command to run...

17. MEDIUM | Higher Order Function in JavaScript

This article will talk about higher order function in javascript.

Updated
•2 min read•View as Markdown
S
Full-Stack Developer with 4 years' experience, specializing in backend development. Skilled in JavaScript, React, Python, Databases, and AWS. Known for building scalable web apps, leading teams, and maintaining strong client communication. Upskilling in Generative AI.

What is a higher order function?

A higher-order function in JavaScript is a function that does at least one of the following:

  • Takes one or more functions as arguments (often called callback functions).

  • Returns a function as its result.

This is possible because JavaScript treats functions as first-class citizens, meaning they can be:

  • stored in variables (function expressions)

  • passed as arguments

  • returned from other functions


Common Built-in Higher-Order Functions

  1. map()

  2. filter()

  3. reduce()

  4. setTimeout()

  5. setInterval()

  6. ... and many more


Creating Custom Higher-Order Functions

You can also write your own higher-order functions to make your code more modular and reusable.

  • Function that takes another function as an argument:
// Example 1
function processUserInput(param) {
  const name = "Shubham";
  param(name);
}

// callback function as function declaration
function greet(name) {
  console.log(`Hello ${name}`);
}

processUserInput(greet);

/**
Explanation:-
* processUserInput is the Higher-Order Function.
* greet is passed as the callback.
*/

// ===============================================================
// Example 2
function processUserInput(param) {
  const name = "Shubham";
  param(name);
}

// callback function as function expression
const greet = function(name) {
  console.log(`Hello ${name}`);
}

processUserInput(greet);

// ===============================================================
// Example 3
function processUserInput(param) {
  const name = "Shubham";
  param(name);
}

// callback function as anonymous function
processUserInput(function(name) {
  console.log(`Hello ${name}`);
});
  • Function that returns another function:
// Example 1
const num1 = 4;
const num1 = 6;

function parent() {
    console.log("Inside parent...")

    function add() {
        console.log(num1 + num2);
    }

    return add // returning named function
}

const caller = parent();
caller();

// ===============================================================
// Example 2
function parent() {
    console.log("Inside parent...")
    
    // returning anonymous function
    return function(num1, num2) {
        console.log(num1 + num2);
    }

}

const caller = parent();
caller(4, 6);

Benefits of Higher-Order Functions

  • Code Reusability

  • Modularity

  • Abstraction


Happy reading!