Higher order functions in javascript

Higher order functions in javascript

What is a higher order function in Javascript?

A higher order function is a function that can accept another function as argument or it returns another function as a result.

Examples:

  1. pass a function as a parameter to another function
function fn1() {
  console.log('fn1');
}
function fn(otherFn) {
  otherFn();
}

fn(fn1); //will log 'fn1'

As you can see in the example above we send as arguments to function fn, another function called fn1 and then we’ve run our function and got the result ‘fn1’.

  1. return a function from another function
function fn1() { 
  console.log('fn1'); 
}
function fn (otherFn) { 
  return () => otherFn();
}
fn(fn1)(); //will lo 'fn1'

Above example is going to return a function from our function fn and the invoke it and we are going to get the result ‘fn1’.

Related Posts