What is a callback function?
Answer
A callback function is a function passed as an argument to another function, to be executed at a later time — typically when an asynchronous operation completes or at a specific point in the calling function's execution. setTimeout(() => console.log("done"), 1000) — the arrow function is a callback. arr.forEach(item => console.log(item)) — forEach calls the callback for each element. Callbacks enabled asynchronous JavaScript before Promises. Callback hell (pyramid of doom) occurs when multiple async operations are nested: getData(function(a) { getMoreData(a, function(b) { getEvenMore(b, function(c) { ... }) }) }) — deeply nested, hard to read and error-handle. Promises and async/await solve this. Higher-order functions (map, filter, reduce, forEach, sort) use callbacks as a functional programming pattern — these synchronous callbacks are perfectly clean and preferred.
Previous
What is the difference between call(), apply(), and bind()?
Next
What is the use of the Array.from() method?