-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
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.
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.
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.
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);
});
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 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);
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
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.
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' }
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.
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);
}
});
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.
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.
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts