Callbacks

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

Illustration of callbacks
Illustration of callbacks

💡 Why use Callbacks?

Callbacks allow you to control the order of execution, handle asynchronous operations, and create reusable, modular code.

How Callbacks Work

Instead of running immediately, a callback function is invoked after a task completes, often used for asynchronous tasks like fetching data or event handling.

📌 Deep Dive: Simple Callback Example

JAVASCRIPT
function greet(name, callback) {
  console.log('Hello, ' + name + '!');
  callback();
}

function sayGoodbye() {
  console.log('Goodbye!');
}

greet('Alice', sayGoodbye);
Output
Hello, Alice! Goodbye!

Callbacks with Asynchronous Functions

Callbacks are essential for asynchronous operations, such as timers or network requests, to handle actions that happen later.

📌 Deep Dive: Using Callback with setTimeout

JAVASCRIPT
function fetchData(callback) {
  setTimeout(() => {
    callback('Data loaded');
  }, 1000);
}

fetchData(function(message) {
  console.log(message);
});
Output (after 1 second)
Data loaded

💡 Callback Naming

By convention, callback parameters are often named callback, cb, or more descriptive names like onComplete.

Callback vs Regular Function Call
CallbackRegular Function Call
Passed as an argumentCalled directly
Executed inside another functionExecuted immediately
Often used for async tasksUsed for synchronous tasks

⚠️ Avoid Callback Hell

Excessive nested callbacks can make code hard to read and maintain. Modern JavaScript often uses Promises or async/await to handle this.

Summary

  • A callback is a function passed to another function to be executed later.
  • They are fundamental for asynchronous programming in JavaScript.
  • Proper naming and structure improve readability and maintainability.