03 Higher Order Functions in Javascript
Tags: javascript, react, beginners
Published: 2024-05-19 08:44:34

---
title: 03 Higher Order Functions in Javascript
published: true
description: Functions that can take other functions as arguments or return them as results..
tags: #javascript #react #beginner
cover_image: https://i.imgur.com/fFNKI9W_d.webp?maxwidth=760&fidelity=grand
# Use a ratio of 100:42 for best results.
# published_at: 2024-05-19 06:33 +0000
---
### Higher Order Function

> A Higher order function is a function that either can accept another function as an argument or return a function as a result.

### Introduction:
Higher-order functions are a fundamental aspect of JavaScript, offering immense flexibility and code reusability by allowing functions to be treated as first-class citizens. In this blog, we'll explore what higher order functions are, why they are important, and how they can be used effectively in your code.
Javascripts [`Array.prototype.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) and [`Array.prototype.filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) they both are Higher order function. Lets explore why do we need Higher order function.

let's write a function that filter words that starts with word H.

```javascript
function startWithH (words){
  const containsCharWithH = [];
  
  for(let i=0, {length} = words; i< length; i++ ){
    const word = words[i];
    if(word.startsWith('H')){
    	containsCharWithH.push(word)
    }
  }
  return containsCharWithH;
}

console.log(startWithH(['Hack', 'Recursion', 'HOF', 'Currying', 'Handshake', 'Heap', 'Array'])) // ['Hack', 'HOF', 'Handshake', 'Heap']
```
and now lets filter all the words whose length is less than or equal to 4.

```javascript
function wordsWithLessThanChar4(words){
  const containsCharWithH = [];
  
  for(let i=0, {length} = words; i< length; i++ ){
    const word = words[i];
    if(word.length <=4){
    	containsCharWithH.push(word)
    }
  }
  return containsCharWithH;
}

console.log(wordsWithLessThanChar4(['Hack', 'Recursion', 'HOF', 'Currying', 'handshake', 'Heap', 'Array']))
```
As we can see both of these above functions are almost same, so we can refactor this with Higher order function.
Javascript has first class functions just like numbers, strings or objects, functions also can be 

1. Assigned as identifier.
2. Passed as arguments
3. Returned from functions.

due to these qualities abstractions are made easier with functions.

### Refactoring with Higher-Order Functions

let's write a reduce function which takes a function and return accumulated result for the given array.

```javascript
function reduce(reducerFn, acc, arr){
  let initial = acc;
  for(let i=0, {length} = arr; i< length; i++) {
    acc = reducerFn(acc, arr[i])
  }
  return acc;
}

``` 
now if we want to get product of 0-10 then we can get easily with this `reduce HOF`.

```javascript
reduce((acc, curr) => acc * curr, 0, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) // 3628800
```
now lets implement a `filter function` which is most useful function which will help us to abstract logic for both the above functions *startWithH* and *wordsWithLessThanChar4*

```javascript
const filter = (predicateFn , arr) => {
  // referring to the above reduce function
  return reduce((acc, curr) => {
    return predicateFn(curr) ? acc.concat([curr]) : acc
  }, [], arr)
}
```

filter function is a higher-order function because it takes another function, `predicateFn`, as one of its inputs. This `predicateFn` function is like a test that decides whether each item in the `array` should be included in the `final result`. The `filter function` then uses this `predicateFn` to check each item in the array. If the item passes the test (returns true), it's added to the `result`. If not, it's `skipped`.
In the above filter function everything is shared except the *predicateFn*, that's gets passed as an Argument.

now lets implement *startWithH* with these utility functions.
```javascript
const startWithH = words => filter(
  word => word.startsWith('H'), 
  words
)
startWithH(['Hack', 'Recursion', 'HOF', 'Currying', 'handshake', 'Heap', 'Array']) // ['Hack', 'HOF', 'Heap']
```
and lets rewrite this *wordsWithLessThanChar4* function.

```javascript
const wordsWithLessThanChar4 = words => filter(
  word => word.length <=4,
  words
)
wordsWithLessThanChar4(['Hack', 'Recursion', 'HOF', 'Currying', 'handshake', 'Heap', 'Array']) // ["Hack", "HOF", "Heap"]
```

`filter` can work on numbers as well, this utility function is smart enough to work on different data types.

### Conclusion

higher-order functions are a fundamental aspect of JavaScript that offer immense flexibility and code reusability by allowing functions to be treated as first-class citizens. By accepting or returning other functions, they enable powerful abstractions and functional programming paradigms.

Happy Learning!!!