Higher Order Function Vs Call Back Function

Introduction

In this blog, we are going to see what is higher-order function and call-back function in JavaScript are and their use.

Higher-Order Function

A higher-order function is a function that takes another function as arguments or returns the function as output.

function HigherOrderFunction(callback) {}
function Test() {
    // logic
}
HigherOrderFunction(Test);
// Here 'HigherOrderFunction' is higher order function and 'Test' function is passed as argument

Below functions are examples for in-built higher-order functions in JavaScript,

  • Map
  • Filter
  • Reduce
var numbers = [1, 2, 3, 4];
var doubles = numbers.map(function(number) {
    return number * 2;
});
// doubles = [2, 3, 6, 8];

In the above code, the map function takes another function as an argument which iterates the values in the array and completes the task inside that function.

Call back Function

Call back function is a function that is passed to another function as an argument, which is invoked inside the outer function.

function OuterFunction(callback) {
    callback(); // 'Test' function will be invoke
}
function Test() {
    // logic
}
OuterFunction(Test); // Here 'Test' is call back function

Example

Simple Calculator function,

function add(num1, num2) {
    return num1 + num2;
}
function sub(num1, num2) {
    return num1 - num2;
}
function multiply(num1, num2) {
    return num1 * num2;
}
function calculator num1, num2, operator) {
    return operator(num1, num2);
}
calculator(10, 5, add);
calculator(10, 5, sub);
calculator(10, 5, multiply);

In the above code, 

  • The "calculator" is a higher-order function that takes another function as arguments(Third argument "operator")
  • The functions "add", "sub", "multiply" are passed as arguments to the "calculator" function and are invoked inside the "calculator" function. These are callback functions.

Use of higher function executes any function at runtime or dynamically based on function argument (Here add, sub, multiply). Also If need any common logic for all three functions then, we can add that logic in one place(In the "calculator" function). 

function calculator num1, num2, operator) {
    // Check inputs are number or not - Common logic
    if (isNaN(num1) || isNaN(num2) {
            console.log("input(s) are not a number");
            return;
        }
        return operator(num1, num2);
    }