Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Callbacks
Next article icon

JavaScript Callbacks

Last Updated : 05 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

What is a Callback Function?

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); 

Output
Hello, Ajay Goodbye! 

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

How Do Callbacks Work 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"); 

Output

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

Where Are Callbacks Used?

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)); 

Output
8 15 
  • 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.

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.

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);  

Output
Result: 5 Error: Cannot divide by zero 

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).

Next Article
JavaScript Callbacks
author
2hin_roy_
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Asynchronous

Similar Reads

    What is Callback Hell in JavaScript ?
    One of the primary ways to manage asynchronous operations in JavaScript is through callback functions that execute after a certain operation completes. However, excessive use of callbacks can lead to an issue known as Callback Hell, making code difficult to read, maintain, and debug.What is Callback
    4 min read
    JavaScript Function Call
    The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). This allows borrowing methods from other objects, executing them within a different context, overriding the default value, and passing arguments. Syntax: cal
    2 min read
    Promise vs Callback in JavaScript
    In JavaScript, managing asynchronous operations is a key aspect of modern web development. Two popular approaches for handling these operations are Promises and Callbacks. While both techniques are designed to deal with tasks that take time to complete (like fetching data from a server), they work d
    5 min read
    Asynchronous JavaScript
    Asynchronous JavaScript is a programming approach that enables the non-blocking execution of tasks, allowing concurrent operations, improved responsiveness, and efficient handling of time-consuming operations in web applications, JavaScript is a single-threaded and synchronous language. The code is
    2 min read
    How to Create a Custom Callback in JavaScript?
    A callback is a function that executes after another function has been completed in JavaScript. As an event-driven language, JavaScript does not pause for a function to finish before moving on to the next task. Callbacks enable the execution of a function only after the completion of another, making
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences