JavaScript Callback Function

Subject: JavaScript

A callback function is a function passed as an argument to another function, which is executed after the parent function completes. Callbacks can be synchronous or asynchronous.


What is a Callback Function?

  • A function passed to another function as an argument.
  • Called after the parent function finishes execution.
  • Can be synchronous or asynchronous.

Example 1: Basic Callback Function


Example 2: Callback with setTimeout (Asynchronous)


Example 3: Custom Asynchronous Callback


Why Use Callbacks?

  • Execute code after async tasks finish.
  • Write non-blocking code.
  • Common in event handling, file reading, HTTP requests.

Callback Hell (Downside)

Callbacks can be nested deeply, making code hard to read and maintain.

Solution: Use Promises or async/await for cleaner code.


Named vs Anonymous Callbacks

  • Named Callback:
  • Anonymous Callback:

Key Takeaways

  • Callbacks are functions passed and called later.
  • Useful in async programming with events, timers, API calls.
  • Help modularize and reuse code.
  • Avoid callback hell by using Promises or async/await.
  • Callbacks can be synchronous or asynchronous.
Next : Generator Functions