DEV Community

Cover image for JS interview in 2 minutes / Higher Order Functions
Nick K
Nick K

Posted on

JS interview in 2 minutes / Higher Order Functions

Question:
Explain Higher Order Functions in Javascript.

Quick answer:
These are functions that return other functions.

UPD: as @mazentouati noted in the comments, Higher Order Functions are also functions that accept a function as its parameter. Wikipedia

image

Longer answer:
In JavaScript, you can return objects of any type as a result of the function or receive an object of any type as a parameter. This means you can create a function that will return a function.



function higherFunction() {
  return function regularFunction() {
    console.log('Hello world!')
  }
}

const a = higherFunction() // won't print anything
a() // Hello world!


Enter fullscreen mode Exit fullscreen mode

You can also try to create even more nested functions.



const a = () => () => () => () => console.log('Hello world')
const b = a()
const c = b()
const d = c()

d() // Hello world!


Enter fullscreen mode Exit fullscreen mode

You can pass functions to a function that will execute functions in some specific order.



const pipe = (...args) => 
  (init) => 
    args.reduce((acc, cur) => cur(acc), init)

const a = pipe(
 (val) => val + 1,
 (val) => val * 2,
 (val) => console.log("Got", val),
)

a(10) // Got 22


Enter fullscreen mode Exit fullscreen mode

And more other fun ways to use functions πŸ€ͺ

Real-life example:
Some frameworks (angular) and libraries (MobX) heavily rely on decorators, but decorators are no more than Higher Order Functions themselves.



const logDecorator = (wrapped) => {
  return (...args) => {
    console.log(`Invoked ${wrapped.name} with args ${args}`)
    wrapped(...args)
  }
}

const tmp = (param) => {
  console.log('Do nothing, but just show param:', param) 
}

const wrappedTmp = logDecorator(tmp)
wrappedTmp('Hello world!')
// Invoked tmp with args Hello world!
// Do nothing, but just show param: Hello world!


Enter fullscreen mode Exit fullscreen mode

Some other libraries (RxJs) may use it as configurable helpers.



// These functions can by provided by a library itself
const uppercase = (a) => a.toUpperCase();
const removePunctuation = (a) => a.replace(/[^0-9a-zA-Z ]/g, '')

// pipe is a Higher Order Function that returns a function, which will apply all functions one by one
const process = pipe(
  uppercase,
  removePunctuation,
)

console.log(process('qwe-qwe'), process('Hello world!'))
// QWEQWE HELLO WORLD


Enter fullscreen mode Exit fullscreen mode

Older posts:

Btw, I will post more fun stuff here and on Twitter. Let's be friends πŸ‘‹

Top comments (7)

Collapse
 
mazentouati profile image
Mazen Touati

Nice read Nikita!

It would be more insightful to clearly state that Higher Order Function should meet one of these conditions or both of them:

  • It returns a function
  • It accepts at least one function as a parameter (Like reduce that's being used in the example).
Collapse
 
kettanaito profile image
Artem Zakharchenko

Yeap, that's completely true. The original short definition:

These are functions that return other functions.

Should be changed to something like:

These are functions that accept a function as an argument or return other functions

Collapse
 
hexnickk profile image
Nick K

Hey, thanks for the comment!

That's totally right, needed to double-check the definition, my bad. I've added an update note with a mention to the second section πŸ™

Thanks again!

Collapse
 
johnny_ness profile image
pheeno

awesome! the most easy way to learn about high order function !

Collapse
 
hexnickk profile image
Nick K

Glad you like it ✨

Collapse
 
midasxiv profile image
Midas/XIV

Good read! :D

Collapse
 
hexnickk profile image
Nick K

Thanks! ⭐️