A callback function is a function that is passed as an argument to another function and is executed after some operation has been completed. Callbacks are a core part of JavaScript and are commonly used for asynchronous operations like reading files, making API calls, or handling events.

Basic Example of a Callback


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

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

greet("Alice", sayGoodbye);

In the example above, sayGoodbye is passed as a callback to the greet function. It will run after the greeting is printed.

Why Use Callback Functions?

  • To run code **after** another piece of code finishes
  • To handle asynchronous tasks like HTTP requests
  • To allow functions to be more flexible and reusable

Asynchronous Callback Example


console.log("Start");

setTimeout(function () {
  console.log("This runs after 2 seconds");
}, 2000);

console.log("End");

Here, the callback function inside setTimeout runs **after** 2 seconds. JavaScript continues execution in the meantime.

Callback in Array Methods

Many array methods use callbacks:


const numbers = [1, 2, 3];

numbers.forEach(function (num) {
  console.log(num * 2);
});

Named vs Anonymous Callbacks


// Named
function logNumber(num) {
  console.log(num);
}
[1, 2, 3].forEach(logNumber);

// Anonymous
[1, 2, 3].forEach(function (num) {
  console.log(num);
});

Callback Hell

Too many nested callbacks can lead to messy code:


doSomething(function (result) {
  doNextThing(result, function (nextResult) {
    doAnotherThing(nextResult, function (finalResult) {
      console.log(finalResult);
    });
  });
});

This is known as callback hell. Modern solutions like Promises and async/await help avoid this.

Conclusion

Callback functions are essential in JavaScript for handling both synchronous and asynchronous code. They let you pass behavior into functions and are the foundation of more advanced patterns like Promises and async/await. Understanding callbacks is a must for every JavaScript developer.

Post a Comment

Your email address will not be published. Required fields are marked *