Skip to main content

Command Palette

Search for a command to run...

Callbacks in JavaScript: Why They Exist

Updated
β€’4 min readβ€’View as Markdown
Callbacks in JavaScript: Why They Exist
M
I am currently pursuing a Bachelor of Technology in Computer Science and Engineering at Maharishi Markandeshwar (Deemed to be University), India. I have completed my Diploma in Computer Science & Engineering from Government Polytechnic, Purnea.

JavaScript Callback Functions Explained (Beginner to Advanced)

Introduction

JavaScript is a powerful language used to build interactive websites and applications. One important concept you will see everywhere is callback functions.

If you have ever worked with events, APIs, or timers, you have already used callbacksβ€”maybe without even realizing it.

In this blog, you will learn callback functions from basics to advanced concepts in a clear and simple way.


What is a Callback Function?

Functions as Values in JavaScript

In JavaScript, functions are first-class citizens. This means:

  • You can store them in variables

  • Pass them as arguments

  • Return them from other functions

Example

function greet(name) {
  return "Hello " + name;
}

function processUser(callback) {
  const result = callback("Madhu");
  console.log(result);
}

processUser(greet);

Explanation

  • greet is passed as an argument

  • processUser calls it

  • This passed function is called a callback function

πŸ‘‰ Definition:

A callback function is a function passed into another function to be executed later.

Passing Functions as Arguments

This is the foundation of callbacks.

Simple Example

function sayHello() {
  console.log("Hello!");
}

function executeFunction(fn) {
  fn();
}

executeFunction(sayHello);

Key Idea

  • fn is a callback

The main function controls when to execute it

Why Callbacks are Used in Asynchronous Programming

  • JavaScript is single-threaded, but it handles tasks like:

    • API calls

    • File loading

    • Timers

    These tasks take time, so JavaScript uses asynchronous programming.

    Example with setTimeout

    console.log("Start");
    
    setTimeout(function () {
      console.log("This runs later");
    }, 2000);
    
    console.log("End");
    

    Output

    Start
    End
    This runs later
    

    Explanation

    • The callback runs after 2 seconds

    • JavaScript continues execution without waiting

    πŸ‘‰ This makes apps fast and responsive

    Callback Usage in Common Scenarios

    1. Event Handling

    button.addEventListener("click", function () {
      console.log("Button clicked!");
    });
    

    πŸ‘‰ The function runs only when the event happens

2. API Calls (Simulation)

function fetchData(callback) {
  setTimeout(() => {
    callback("Data received");
  }, 1000);
}

fetchData(function (data) {
  console.log(data);
});

3. Array Methods

const numbers = [1, 2, 3];

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

πŸ‘‰ Here, the callback runs for each element


Function Calling Flow (Conceptual Diagram)

Main Function β†’ Receives Callback β†’ Executes Callback β†’ Output

Problem: Callback Nesting (Callback Hell)

When callbacks are nested too deeply, code becomes hard to read.

Example

setTimeout(() => {
  console.log("Step 1");

  setTimeout(() => {
    console.log("Step 2");

    setTimeout(() => {
      console.log("Step 3");
    }, 1000);

  }, 1000);

}, 1000);

Issues

  • Hard to read

  • Difficult to debug

  • Poor maintainability

Nested Callback Flow (Conceptual Diagram)

Step 1
  └── Step 2
        └── Step 3

πŸ‘‰ This structure is called Callback Hell


How to Handle Callback Problems

Even though callbacks are important, modern JavaScript provides better solutions:

  • Promises

  • Async/Await

But understanding callbacks is still essential for fundamentals.

Real-World Example

Imagine ordering food online:

  1. Place order

  2. Wait for confirmation

  3. Delivery arrives

function placeOrder(callback) {
  console.log("Order placed");

  setTimeout(() => {
    callback();
  }, 2000);
}

placeOrder(function () {
  console.log("Order delivered");
});

πŸ‘‰ Delivery happens only after processing

Practical Project Idea

Mini Project: User Login Simulation

Build a small program that:

  • Takes a username

  • Simulates server verification

  • Calls a callback after login

Example

function loginUser(username, callback) {
  console.log("Checking user...");

  setTimeout(() => {
    callback("Welcome " + username);
  }, 2000);
}

loginUser("Madhu", function (message) {
  console.log(message);
});

πŸ‘‰ This mimics real-world backend behavior

Key Takeaways

  • A callback function is passed into another function

  • JavaScript treats functions as values

  • Callbacks are essential for asynchronous programming

  • Used in events, APIs, and array methods

  • Too many nested callbacks lead to callback hell

  • Modern alternatives exist, but callbacks remain fundamental


Conclusion

Callback functions are one of the most important concepts in JavaScript. They allow you to write flexible, reusable, and asynchronous code.

Start with simple examples, understand how functions are passed and executed, and then move toward real-world use cases.

Once you master callbacks, learning advanced concepts like Promises and Async/Await becomes much easier.

πŸ‘‰ Keep practicing, and try building small projects to strengthen your understanding.