GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • JS Tutorial
  • Web Tutorial
  • A to Z Guide
  • Projects
  • OOP
  • DOM
  • Set
  • Map
  • Math
  • Number
  • Boolean
  • Exercise
  • Introduction3 min read
  • Variables5 min read

This view

  • Original page
  • New address

GeezerVison is showing www.geeksforgeeks.org — JavaScript Callbacks - GeeksforGeeks

geeksforgeeks
search icon
  • Courses
  • Tutorials
  • Interview Prep
  • JS Tutorial
  • Web Tutorial
  • A to Z Guide
  • Projects
  • OOP
  • DOM
  • Set
  • Map
  • Math
  • Number
  • Boolean
  • Exercise

JavaScript Callbacks

Last Updated : 17 Jan, 2026

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.
JavaScript
function greet(name, callback) {
    console.log("Hello, " + name);
    callback();
}

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

greet("Ajay", sayBye);

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

Working of Callbacks in JavaScript

JavaScript executes code line by line (synchronously), but sometimes we need to delay execution or wait for a task to complete before running the next function. Callbacks help achieve this by passing a function that is executed later.

Callbacks for Asynchronous Execution

JavaScript
console.log("Start");

setTimeout(function () {
    console.log("Inside setTimeout");
}, 2000);

console.log("End");
  • setTimeout() is an asynchronous function that takes a callback to execute after 2 seconds.
  • The rest of the code continues executing without waiting.

Uses of Callbacks in JavaScript

1. Handling Asynchronous Operations

Callbacks are widely used in

  • API requests (fetching data)
  • Reading files (Node.js file system)
  • Event listeners (clicks, keyboard inputs)
  • Database queries (retrieving data)

2. Callbacks in Functions Handling Operations

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

JavaScript
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));
  • calculate() receives two numbers and a function (add or multiply).
  • The passed function is executed inside calculate().

3. Callbacks in Event Listeners

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

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

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

4. Callbacks in API Calls (Fetching Data)

Callbacks are useful when retrieving data from APIs.

JavaScript
function fetch(callback) {
    fetch("https://jsonplaceholder.typicode.com/todos/1")
        .then(response => response.json())
        .then(data => callback(data))
        .catch(error => console.error("Error:", error));
}

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

fetch(handle);

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

Problems with Callbacks

Although callbacks are useful, they have some drawbacks.

1. Callback Hell (Nested Callbacks)

When callbacks are nested deeply, the code becomes unreadable and hard to maintain.

JavaScript
function step1(callback) {
    setTimeout(() => {
        console.log("Step 1 completed");
        callback();
    }, 1000);
}

function step2(callback) {
    setTimeout(() => {
        console.log("Step 2 completed");
        callback();
    }, 1000);
}

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

step1(() => {
    step2(() => {
        step3(() => {
            console.log("All steps completed");
        });
    });
});

As the number of steps increases, the nesting grows deeper, making the code difficult to manage.

2. Error Handling Issues in Callbacks

Error handling can get messy when dealing with nested callbacks.

JavaScript
function divide(a, b, callback) {
    if (b === 0) {
        callback(new Error("Cannot divide by zero"), null);
    } else {
        callback(null, a / b);
    }
}

function result(error, result) {
    if (error) {
        console.log("Error:", error.message);
    } else {
        console.log("Result:", result);
    }
}

divide(10, 2, result);
divide(10, 0, result); 

Handling errors inside callbacks can complicate code readability.

Alternatives to Callbacks

1. Promises (Fixing Callback Hell)

Promises provide a better way to handle asynchronous tasks without deep nesting.

JavaScript
function step1() {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log("Step 1 completed");
            resolve();
        }, 1000);
    });
}

function step2() {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log("Step 2 completed");
            resolve();
        }, 1000);
    });
}

function step3() {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log("Step 3 completed");
            resolve();
        }, 1000);
    });
}

step1()
    .then(step2)
    .then(step3)
    .then(() => console.log("All steps completed"));

Promises make code more readable by chaining .then() instead of nesting callbacks.

2. Async/Await (Cleaner Alternative)

async/await provides an even cleaner way to handle asynchronous code.

JavaScript
async function processSteps() {
    await step1();
    await step2();
    await step3();
    console.log("All steps completed");
}

processSteps();

async/await makes code look synchronous, improving readability.

When to Use and Avoid Callbacks

Use callbacks when

  • Handling asynchronous tasks (API calls, file reading).
  • Implementing event-driven programming.
  • Creating higher-order functions.

Avoid callbacks when:

  • Code becomes nested and unreadable (use Promises or async/await).
  • You need error handling in asynchronous operations (Promises are better).
Comment

Explore

    JavaScript Basics
    • Introduction3 min read
    • Variables5 min read
    • Operators4 min read
    • Control Statements4 min read
    Array & String
    • Arrays6 min read
    • Array Methods4 min read
    • String5 min read
    • String Methods8 min read
    Function & Object
    • Functions4 min read
    • Function Expression3 min read
    • Function Overloading4 min read
    • Objects4 min read
    • Constructors4 min read
    OOP
    • OOP5 min read
    • Classes & Objects4 min read
    • Access Modifiers5 min read
    • Constructor4 min read
    Asynchronous JavaScript
    • Asynchronous2 min read
    • Callbacks4 min read
    • Promises4 min read
    • Event Loop3 min read
    • Async Await Fuction3 min read
    Exception Handling
    • Error and Exceptional Handling5 min read
    • Errors Throw & Try to Catch2 min read
    • Custom Errors2 min read
    • TypeError Invalid Array.prototype.sort argument1 min read
    DOM
    • DOM8 min read
    • DOM Elements3 min read
    • Custom Events4 min read
    • Addeventlistener5 min read
    Advanced Topics
    • Closure3 min read
    • Hoisting5 min read
    • Scope4 min read
    • Higher Order Functions7 min read
    • Debugging3 min read
    Courses
    • Placement 360 Course2 min read
    • MERN Full Stack Course2 min read
    • DSA and System Design Course2 min read
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.