Skip to main content

Command Palette

Search for a command to run...

Callbacks in JavaScript: Why They Exist

The Art of the Callback: A Beginner’s Guide to Higher-Order Functions, Event Handling, and Escaping Callback Hell

Updated
4 min readView as Markdown
Callbacks in JavaScript: Why They Exist

What a callback function is

A callback function is a function passed as an argument to another function and executed later is called as a callback function in JavaScript. Callback functions are one the most important concepts in modern JavaScript and it is widely used to write async code. Let's take an example :

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

function process(callback) {
  callback("Rahul");
}

process(greet);

I think you have guessed the output. The mechanism of working of this callback function flow is first the compiler go through Main function , then it receives another function and Executes it later when required.

Callbacks are very useful and helpful in modern day writing code. Callback allows functions to become flexible, reusable and dynamic. Instead of hardcoding behavior, we can pass different functions when needed.


Why callbacks are used in asynchronous programming

Callbacks are used in asynchronous programming because JavaScript is Asynchronous , this means it will take time to complete some tasks. For example, API requests, database operations, file reading, timers, fetching data from servers. These operations do not finish instantly.

If we imagine ordering food in a restaurant , you place the order and continue talking with friends. When food gets ready , the waiter servers you . Similar to this that 'call later' idea is similar to callbacks.

Callbacks are commonly used in asynchronous programming because callbacks provide flexibility, delayed execution, asynchronous handling, reusable logic and event driven programming.


Passing function as arguments

Since functions are treated as values, we can pass them into another function. Let's understand by example ;

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

function executeFunction(fn) {
  fn();
}

executeFunction(sayHello);

Let's try to understand the flow of code, firstly we created a function , then we passed it into another function and inside that function the passed function gets executed. This is the core idea behind callbacks.


Callback usage in common scenarios

Nowadays Callback are used everywhere in JavaScript. Let's take some example :

1. Event Handling

Event Handling is very common is JavaScript. When a button is clicked, the button configured wants to thing what type the button got trigger and what to do when button pressed. Inside button we passed a callback , the function executes only when the event happens.

button.addEventListener("click", ()=> {
  console.log("Button clicked");
});

2. Timers

setTimeout(() => {
  console.log("Executed later");
}, 1000);

The examples is classical example of timers in JavaScript. Callbacks runs after delay.

3. Array Methods

Array Methods or to play with array methods callbacks are heavily used in array methods. Let's take a forEach() example of array methods. ForEach takes a callback in parameters.

const numbers = [1, 2, 3];

numbers.forEach((num) =>{
  console.log(num);
});

//OUTPUT : 
// 1 
// 2
// 3
// 4

Basic problem of callback nesting

The callbacks are extremely useful, but too many nested callbacks create problems. When too many callbacks the code becomes difficult to read, difficult to debug and difficult to maintain. This problem is called CALLBACK HELL.

loginUser(function () {

  getProfile(function () {

    getPosts(function () {

      getComments(function () {

        console.log("Finished");

      });

    });

  });

});

When too many callbacks takes place the code shrink to right side continuously and this pyramid - like structure becomes messy in large applications. To solve callback problems , modern JavaScript introduced Promises and async/await . This makes asynchronous code cleaner but understanding callbacks first is extremely important because promises are built on the same asynchronous foundation.


Wrapping Up 📍

Thanks for reading till the end 🙌
I hope this article helped you understand the topic in a simple, practical, and beginner-friendly way.

My goal is to break down complex tech concepts into clear, real-world explanations, especially for learners who are just starting out or feeling overwhelmed.

If you found this useful, feel free to bookmark, share, or leave a comment - it really helps and keeps me motivated to write more.

You can connect with me here:

Let’s learn together and grow step by step 🚀