DEV Community

Cover image for 03 Higher Order Functions in Javascript
Karma7
Karma7

Posted on • Updated on

03 Higher Order Functions in Javascript

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 and Array.prototype.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.

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']
Enter fullscreen mode Exit fullscreen mode

and now lets filter all the words whose length is less than or equal to 4.

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']))
Enter fullscreen mode Exit fullscreen mode

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.

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

Enter fullscreen mode Exit fullscreen mode

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

reduce((acc, curr) => acc * curr, 0, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) // 3628800
Enter fullscreen mode Exit fullscreen mode

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

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

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.

const startWithH = words => filter(
  word => word.startsWith('H'), 
  words
)
startWithH(['Hack', 'Recursion', 'HOF', 'Currying', 'handshake', 'Heap', 'Array']) // ['Hack', 'HOF', 'Heap']
Enter fullscreen mode Exit fullscreen mode

and lets rewrite this wordsWithLessThanChar4 function.

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

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!!!

Top comments (0)