Mind~G
Javascript

Callback

Introduction

In JavaScript a callback is just a function that is passed into another function so that it runs after something finishes.

Basic Example

function firstTask(callback) {
  console.log("First task done")
  callback()
}
 
function secondTask() {
  console.log("Second task done")
}
 
firstTask(secondTask)
  • Here secondTask is a callback because it runs after firstTask finishes

Callback Hell

Callback hell happens when you have many callbacks inside callbacks where each callback depends on the one before it.

Example of Callback Hell

doSomething(function(result1) {
  doSomethingElse(result1, function(result2) {
    doThirdThing(result2, function(result3) {
      doFourthThing(result3, function(result4) {
        console.log("All done")
      })
    })
  })
})

Problems with Callback Hell

  • The code looks ugly and hard to read
  • It is hard to handle errors
  • It is difficult to maintain or add new features
  • Creates a "pyramid of doom" structure

How to Fix Callback Hell

  1. Promises - Promises make code look cleaner and more manageable
  2. Async/Await - Modern syntax that makes asynchronous code look synchronous

Important Notes

  • Callbacks are fundamental to JavaScript's asynchronous nature
  • They allow code to continue running while waiting for operations to complete
  • Modern JavaScript prefers Promises and async/await over nested callbacks
  • Callbacks are still widely used in event handlers and array methods like map(), filter(), forEach()

On this page