# 17. MEDIUM | Higher Order Function in JavaScript

* * *

## What is a higher order function?

A **higher-order function** in JavaScript is **<mark class="bg-yellow-200 dark:bg-yellow-500/30">a function that does at least one of the following:</mark>**

*   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:**
    

```javascript
// 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:**
    

```javascript
// 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!
