Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a callback also known as a higher-order function?

I'm trying to understand callback and higher-order functions but there's a description from a blog post, Understand JavaScript Callback Functions and Use Them, that confuses me, the implication being that they are one and the same:

A callback function, also known as a higher-order function,...

It was repeated verbatim on a Quora answer to the question asking about What is a simple explanation of higher order functions and callbacks in JavaScript?.

It doesn't make sense to me. From what I understand, a higher-order function takes in or returns other functions and a callback function is the function being passed/taken in, so how can it be both at the same time? Is there something that I'm not understanding about that description?

like image 857
thuynt13 Avatar asked Feb 12 '26 06:02

thuynt13


1 Answers

Callback function

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

Return a function

A function that returns a function called Higher-Order Function

A callback function is not a Higher-Order Function, unless it is a function that returns a function.

Simple callback:

function toto(callback){
  /** some routine or action before */
  callback();
}

function foo(){
  console.log("I'm a simple callback");
}

toto(foo);

Simple Higher-Order Function

function toto(){
  console.log("I'm a simple Higher-Order Function")
  return function(){
     console.log("I'm the return function");
  }
}

//first log
const func = toto();
//second log
func();

Callback that is also a Higher-Order Function:

function toto(callback){
  /** some routine or action before */
  const func = callback();
  func();
}

function foo(){
  console.log("I'm a callback and Higher-Order function");
  
  return function(){
    console.log("Do something...");
  };
}

toto(foo);
like image 107
kemicofa ghost Avatar answered Feb 18 '26 13:02

kemicofa ghost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!