Callback Functions

Callback functions are a fundamental concept in JavaScript, enabling asynchronous programming and allowing functions to be passed as arguments to other functions for execution at a later time.

What is a 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.

Basic Syntax

function outerFunction(callback) {
  // Code before executing callback
  callback();
  // Code after executing callback
}

Synchronous Callbacks

Synchronous callbacks are executed immediately, such as with array methods like forEach, map, and filter.

Example with forEach

const numbers = [1, 2, 3, 4, 5];
numbers.forEach(number => {
  console.log(number);
});

Explanation

In this example, the callback function is executed synchronously for each element in the numbers array.

Output

1
2
3
4
5

FAQ

Q: What is the difference between synchronous and asynchronous callbacks?

A: Synchronous callbacks are executed immediately within the function they are passed to, whereas asynchronous callbacks are executed at a later time, typically after an asynchronous operation completes.

Q: How do I handle errors in asynchronous callbacks?

A: Always check for error arguments in your callback function and handle them appropriately, often by logging the error or taking corrective action. For example, when using `fs.readFile`, the first argument in the callback is an error object.

Q: Can I pass multiple callback functions to a single function?

A: Yes, you can pass multiple callback functions to a single function by including them as additional arguments and invoking them as needed within the function body.

Q: Why are arrow functions commonly used as callbacks?

A: Arrow functions provide a concise syntax and automatically bind `this` lexically, making them a popular choice for callbacks, especially in methods like `map`, `forEach`, and `filter`.