JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Callbacks


What is a Callback in JavaScript?

In JavaScript, a callback is a function passed as an argument to another function. The purpose of a callback is to allow a function to “call back” another function once it has finished its execution.

Callbacks are one of the most important concepts in JavaScript because they are used heavily in asynchronous operations like fetching data, reading files, or handling user events.

Why Do We Need Callbacks?

Normally, JavaScript executes code line by line (synchronously). But sometimes we need to wait for an operation to complete before continuing.

For example:

  • Wait until a file is read from disk.

  • Wait until data is fetched from a server.

  • Wait until a button is clicked.

Callbacks allow us to handle these situations without blocking the rest of the program.

Basic Example of a Callback

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

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

// Passing sayGoodbye as a callback
greetUser("Vicky", sayGoodbye);

Output:

Hello, Vicky
Goodbye!

Here, sayGoodbye is passed as a callback and executed after the greeting.

Anonymous Callback Functions

Instead of defining a separate function, we can also use anonymous functions as callbacks:

function processNumber(num, callback) {
  console.log("Processing number:", num);
  callback(num);
}

processNumber(5, function(result) {
  console.log("Square:", result * result);
});

Callback with Built-in Methods

Many JavaScript built-in methods use callbacks.
Example with setTimeout():

setTimeout(function() {
  console.log("This runs after 2 seconds");
}, 2000);

Example with Array methods:

let numbers = [1, 2, 3, 4];
numbers.forEach(function(num) {
  console.log(num * 2);
});

Synchronous vs Asynchronous Callbacks

  1. Synchronous Callback – runs immediately inside the function.

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

let sum = calculate(5, 3, function(x, y) {
  return x + y;
});

console.log("Sum:", sum);
  1. Asynchronous Callback – runs later after an operation completes.

console.log("Start");

setTimeout(function() {
  console.log("Callback executed after 2 seconds");
}, 2000);

console.log("End");

Output order:

Start  
End  
Callback executed after 2 seconds  

Nested Callbacks and "Callback Hell"

When many callbacks are nested, code becomes hard to read and maintain.

setTimeout(function() {
  console.log("Step 1");
  setTimeout(function() {
    console.log("Step 2");
    setTimeout(function() {
      console.log("Step 3");
    }, 1000);
  }, 1000);
}, 1000);

This is known as callback hell, which later led to the introduction of Promises and async/await.

Real-world Example: Fetching Data (Simulation)

function fetchData(callback) {
  console.log("Fetching data...");

  setTimeout(function() {
    let data = { id: 1, name: "Vicky" };
    callback(data);
  }, 2000);
}

fetchData(function(result) {
  console.log("Data received:", result);
});

Output:

Fetching data...
Data received: { id: 1, name: 'Vicky' }

Best Practices for Using Callbacks

  • Use named functions instead of anonymous ones for readability.

  • Handle errors inside callbacks (error-first callbacks are common).

  • Avoid deeply nested callbacks – use Promises or async/await for complex logic.

Error Handling in Callbacks (Error-First Style)

In Node.js and many APIs, the first argument of a callback is often reserved for errors.

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

divide(10, 2, function(err, result) {
  if (err) {
    console.log(err);
  } else {
    console.log("Result:", result);
  }
});

Summary of the Tutorial

  • A callback is a function passed to another function to be executed later.

  • Callbacks can be synchronous or asynchronous.

  • They are widely used in JavaScript (e.g., setTimeout, event listeners, array methods).

  • Too many nested callbacks cause callback hell, which can be solved with Promises or async/await.


Practice Questions

1. Write a function performOperation(a, b, callback) that takes two numbers and a callback function. Use the callback to return the sum of the two numbers.

2. Create a function greetUser(name, callback) that prints a greeting message and then executes the callback to print a farewell message.

3. Use setTimeout() with a callback to display "Task completed!" after 3 seconds.

4. Write a function processArray(arr, callback) that applies the callback function to each element of the array and prints the results.

5. Simulate fetching user data with a fetchUser(callback) function. After 2 seconds, return a user object {id: 1, name: "Alex"} to the callback.

6. Implement a function calculate(num1, num2, callback) that performs multiplication, but if num2 is 0, the callback should return an error message.

7. Write nested callbacks using setTimeout() to display the steps: "Step 1", "Step 2", "Step 3" each after 1 second, one after the other.

8. Use a callback function inside an event listener. For example, when a button is clicked, run a callback that logs "Button clicked!".

9. Create a function downloadFile(url, callback) that simulates downloading a file with a delay, then calls the callback with "Download complete".

10. Write a function filterEvenNumbers(arr, callback) that filters even numbers from an array using a callback to return the result.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top