What is the difference between callback, high-order functions, and callback queue
A higher-order function is a function that takes another function(s) as an argument(s) and/or returns a function to its callers.
A callback function is a function that is passed to another function with the expectation that the other function will call it.
So a callback is not necessarily itself a higher-order function, but a function which receives a callback as an argument is. Consider a very common case, the DOM event listener:
elem.addEventListener('click', console.log);
Here, .addEventListener
is a higher-order function that takes another function (console.log
) which it then calls. Although console.log
is a callback here, it is not in this case acting as a higher-order function itself.
The event loop is a mechanism exposed to you by the underlying runtime. Here we are going to imagine that we have to do this manually, using an array as a queue:
const queue = [];
const setTimeout = (f, ...args) => {
queue.push([f, args]);
};
const runQueuedCallbacks = () => {
let queued;
while (queued = queue.shift()) {
let [f, args] = queue;
f(...args);
}
};
setTimeout(console.log, 'first'); // queues a call to log
setTimeout(console.log, 'second'); // queues a call to log
console.log('zero-th'); // directly calls log, prints first
// at this point there's no more code to execute, so runQueuedCallbacks runs
// and sequentially steps through the enqueued callbacks.
In real life it's a little more complicated than this because of things like microtask resolution (also what happens when a queued callback queues another callback) but that should hopefully give you a decent picture.