Javascript: Difference between Callback function and Higher Order Function

Sanjana Human In Tech
2 min readNov 20, 2023

--

Callback functions and higher-order functions are concepts in JavaScript that are often used together but serve distinct purposes.

Javscript- Higher Order and Callback function

Higher-Order Function:

A Higher-order function takes one or more functions as arguments and returns as a result. A Higher-order function enables the creation of more abstract and reusable code.

A sample code as below :

//A Higher-Order Function
function multiplyBy(factor) {
return function (number) {
return number * factor;
}
}

//creating a new function as Higher Order Function
const result = multiplyBy(5);

//Using the new function
console.log(result(10));

//output: 50

In this example, multiplyBy is a Higher Order function that takes the function as an argument and returns the result as 5 * 5 = 25.

Callback Function:

A Callback function is a function that is passed as an argument to another function and is executed after the completion of some operation. Callbacks are commonly used to execute asynchronous functions such as data fetching, event handling, and other time-consuming operations.

Let’s take an example for the same:

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

//callback passed as an argument
function greetToGather() {
console.log("Hello callback function');
}

//using the callback function
greet("Javascript", greetToGather);

//output:
Javascript Hello callback function

In this example, the greetToGather is a function that is a callback that is passed to the greet function.

In summary, a callback function is a function passed as an argument to another function and executed at a later time, often used in asynchronous scenarios. On the other hand, a higher-order function is a function that takes one or more functions as arguments or returns a function, allowing for the creation of more abstract and reusable code. so this concept is often used together with a higher-order function which takes the callback function as an argument.

--

--

Sanjana Human In Tech
Sanjana Human In Tech

Written by Sanjana Human In Tech

A React Native front-end enthusiast and dedicated development engineer, eager to expand knowledge on development techniques and collaborate with others.

Responses (1)