Skip to main content

High Order Functions

A higher-order function is a function that accepts functions as parameters and/or returns a function.

In JavaScript, functions are first-class citizens, which means they can be passed around as arguments to other functions, returned from other functions, and assigned to variables. This allows for the creation of higher-order functions, which are functions that operate on other functions, either by taking them as arguments or by returning them.

Example

const higherOrderFunction = () => {
return () => {
console.log("Returned function is invoked");
};
}

// Assigning the returned function to a variable
const returnedFunction = higherOrderFunction();

// Invoking the returned function
returnedFunction();

Example 2

cont highOrderFunction = (cb) => {   
// Perform some operations
// Call the callback function
cb();
}

const callbackFn = () => {
console.log("Callback function is executed.");
}

// Passing the callback function to the higher-order function
highOrderFunction(cbFn);

Functions as first class objects

In JavaScript, functions are first-class objects, because they can be passed to other functions, returned from functions, and assigned to variables and properties. They can also have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called.

Example 1: Assigning a function to a variable

const foo = () => {
console.log("foobar");
};
foo(); // Invoke it using the variable
// foobar

Example 2: Passing function as an argument

function sayHello() {
return "Hello, ";
}
function greeting(helloMessage, name) {
console.log(helloMessage() + name);
}
// Pass `sayHello` as an argument to `greeting` function
greeting(sayHello, "JavaScript!"); // Hello, JavaScript!

Example 3: Returning a function

function sayHello() {
return () => {
console.log("Hello!");
};
}

Built in High Order Functions

JavaScript provides several built-in higher-order functions that work with arrays, strings, and other data structures. Here are some common examples:

  • map(): Creates a new array by applying a function to each element of the original array.
  • filter(): Creates a new array containing only elements that pass a test implemented by the provided function.
  • reduce(): Applies a function against an accumulator and each element in the array to reduce it to a single value.
  • forEach(): Executes a provided function once for each array element.

Summary

  • A higher-order function is a function that accepts functions as parameters and/or returns a function.
  • There are built in high order functions like .map(), .filter(), .reduce() and .forEach(). Also you can create custom high order functions.
  • In Javascript functions are first-class objects, which means they can be passed to other functions, returned from functions, and assigned to variables and properties.

References