Advance JavaScript (DOM, BOM, Web API) / Asynchronous JavaScript

Callback Functions

In JavaScript, callbacks play an essential role in handling asynchronous tasks like reading files, making API requests, and executing code after certain events.

If you’ve ever heard the phrase "I will call back later!", that’s exactly how callbacks work.

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

  • A function can accept another function as a parameter.

  • Callbacks allow one function to call another at a later time.

  • A callback function can execute after another function has finished.

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

function sayBye() {
    console.log("Goodbye!");
}

greet("Ajay", sayBye);
Hello, Ajay
Goodbye!

Here, sayBye( ) is passed as a callback to greet( ), which executes after the greeting.

In simple words: A callback is a “function that will be called back later.”


💮 Types of Callback

There are two types of callbacks: synchronous and asynchronous callbacks.

🔸 Synchronous callbacks

  • A synchronous callback is executed during the execution of the high-order function that uses the callback. The isOdd and isEven are examples of synchronous callbacks because they execute during the execution of the filter() function.

Example :

function isOdd(num) {
  return num % 2 !== 0;
}

function isEven(num) {
	return num % 2 === 0
}

const numbers = [1, 2, 3, 4, 5];

const oddNumbers = numbers.filter(isOdd);
const evenNumbers = numbers.filter(isEven);

console.log("Odd Numbers:", oddNumbers);
console.log("Even Numbers:", evenNumbers);
  • filter() is a synchronous higher-order function.

  • It accepts isOdd and isEven as callbacks.

  • Both callbacks run immediately for each element in the array.

  • No waiting or async behavior — everything completes before the next line runs.

  • oddNumbers and evenNumbers are ready right after filter() finishes.

Odd Numbers: [1,4,5]
Even Numbers: [2,4]

🔹Asynchronous callbacks

  • An asynchronous callback is executed after the execution of the high-order function that uses the callback.

  • Asynchronicity means that if JavaScript has to wait for an operation to complete, it will execute the rest of the code while waiting.

  • Note that JavaScript is a single-threaded programming language. It carries asynchronous operations via the callback queue and event loop.

Example :

console.log("Start");

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

console.log("End");
  • "Start" prints immediately.

  • setTimeout() schedules the callback to run after 2 seconds, but it does not block the code.

  • JavaScript moves on and prints "End" immediately.

  • After 2 seconds, the callback is taken from the task queue and executed →

    "Callback Executed (Async)" appears.

✔️ Why does this happen?

  • setTimeout() uses the Web APIs (browser environment).

  • The callback is placed in the callback queue and waits.

  • JavaScript continues executing the rest of the code (because it's non-blocking).

  • Once the main call stack is empty, the event loop pushes the callback to run.

Start
End
Cllaback Executed (Async)

✅ Key Difference Recap:

Feature

Synchronous Callback

Asynchronous Callback

Execution Time

Immediately during function execution

After the current execution is finished

Blocking

Yes

No

Use Cases

filter(), map(), forEach()

setTimeout(), setInterval(), fetch()+


🔷Where Are Callbacks Used?

Callbacks are widely used in

  • API requests (fetching data)

  • Reading files (Node.js file system)

  • Event listeners (clicks, keyboard inputs)

  • Database queries (retrieving data)


1. Callbacks in Functions Handling Operations

When a function needs to execute different behaviors based on input, callbacks make the function flexible.

function calc(a, b, callback) {
    return callback(a, b);
}

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

function mul(x, y) {
    return x * y;
}

console.log(calc(5, 3, add));
console.log(calc(5, 3, mul));
8
15
  • calculate( ) receives two numbers and a function (add or multiply).

  • The passed function is executed inside calculate( ).


2. Callbacks in Event Listeners

JavaScript is event-driven, and callbacks handle user interactions like clicks and key presses.

document.getElementById("myButton").addEventListener("click", **function** () {
    console.log("Button clicked!");
});

Here, the anonymous function is a callback that runs when the button is clicked.


3. Callbacks in API Calls (Fetching Data)

Callbacks are useful when retrieving data from APIs.

function getData(callback) {
  fetch("<https://jsonplaceholder.typicode.com/todos/1>")
    .then(res => res.json())
    .then(data => callback(data));
}

function showData(data) {
  console.log("Fetched Data:", data);
}

getData(showData);

fetchData( ) gets data from an API and passes it to showData( ) for processing.


🔸 Features of JavaScript Callbacks

  • Asynchronous Execution: Handle async tasks like API calls, timers, and events without blocking execution.

  • Code Reusability: Write modular code by passing different callbacks for different behaviors.

  • Event-Driven Programming: Enable event-based execution (e.g., handling clicks, keypresses).

  • Error Handling: Pass errors to callbacks for better control in async operations.

  • Non-Blocking Execution: Keep the main thread free by running long tasks asynchronously.


🟥 When to Avoid Callbacks?

  • Code becomes nested and unreadable (use Promises or async/await).

  • You need error handling in asynchronous operations (Promises are better).