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

Introduction

JavaScript is a powerful language where functions are treated as values.

This means:

  • You can assign functions to variables

  • Pass functions as arguments

  • Return functions from other functions

πŸ‘‰ This concept is the foundation of callbacks


Functions as Values (Core Idea)

Before understanding callbacks, let’s see how functions behave like values:

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

const fn = sayHello;

fn(); // Hello!

βœ” Here, the function is stored in a variable and executed later


❓ What is a Callback Function?

A callback function is a function that is passed as an argument to another function and is executed later.


Simple Example

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

function processUser(callback) {
  const name = "Babita";
  callback(name);
}

processUser(greet);

πŸ‘‰ Output:

Hello Babita

βœ” greet is passed as a callback βœ” It is executed inside another function


Passing Functions as Arguments

function calculate(a, b, operation) {
  return operation(a, b);
}

function add(x, y) {
  return x + y;
}

console.log(calculate(2, 3, add));

πŸ‘‰ Output:

5

βœ” Function passed as argument β†’ callback


Why Do Callbacks Exist? πŸ€”

Callbacks exist to:

  • βœ” Make functions flexible

  • βœ” Enable code reuse

  • βœ” Handle asynchronous operations


Callbacks in Asynchronous JavaScript

JavaScript is single-threaded, but it can handle async tasks like:

  • API calls

  • Timers

  • Events

πŸ‘‰ Callbacks allow code to run after a task is completed


Example: setTimeout

console.log("Start");

setTimeout(() => {
  console.log("Callback executed");
}, 2000);

console.log("End");

πŸ‘‰ Output:

Start
End
Callback executed

βœ” The callback runs after 2 seconds βœ” Execution does not stop


Visual Understanding (from Cover Image)

Think of callbacks like this:

Function A β†’ passes function β†’ Function B β†’ executes callback

And in async flow:

Task β†’ Done β†’ Callback()

πŸ‘‰ First task finishes β†’ then callback runs


Real-World Examples

1. Array Methods

const nums = [1, 2, 3];

nums.forEach(function(num) {
  console.log(num);
});

βœ” forEach uses callback


2. Event Handling

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

βœ” Callback runs when event happens


3. API / Async Simulation

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

fetchData((data) => {
  console.log(data);
});

πŸ‘‰ Output:

Data received

Problem: Callback Nesting (Callback Hell)

When callbacks are deeply nested, code becomes messy:

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

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

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

  }, 1000);

}, 1000);

😡 Hard to read, hard to debug


Why Callback Hell is a Problem

  • ❌ Poor readability

  • ❌ Difficult debugging

  • ❌ Hard to maintain


Modern Solution

To solve callback problems, JavaScript introduced:

  • Promises

  • Async/Await

πŸ‘‰ These make async code cleaner


Key Takeaways

  • A callback is a function passed into another function

  • Functions are treated as values in JavaScript

  • Callbacks are essential for async programming

  • Too many callbacks lead to callback hell


Conclusion

Callbacks are a fundamental concept in JavaScript.

They help you:

  • Execute code later

  • Handle async tasks

  • Write flexible functions

πŸ‘‰ Master callbacks first β€” they are the foundation of modern async JavaScript .


Final Tip

Whenever you see a function passed inside another:

πŸ‘‰ That’s a callback


If you found this helpful, share it and keep learning!