-
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
Callbacks are a core concept in JavaScript that allow functions to be passed as arguments to other functions and executed at a later time. They provide a way to handle asynchronous operations, event handling, and custom code execution sequences. Understanding callbacks is essential for writing efficient, non-blocking JavaScript code, especially when working with APIs, timers, or user interactions.
In this tutorial, you will learn about JavaScript callbacks, how to define and use them, practical examples, common mistakes, best practices, and real-world applications.
Callbacks are important because they allow you to:
Handle asynchronous operations such as API requests or timers
Execute functions after a specific event occurs
Implement flexible and reusable code patterns
Avoid blocking the main execution thread in JavaScript
Chain operations in a controlled and predictable manner
Without callbacks, managing asynchronous code would require complex workarounds or synchronous blocking operations, which can reduce performance and responsiveness.
A callback is simply a function passed as an argument to another function. The receiving function can call the callback at any time, either immediately or later based on certain conditions.
function greet(name, callback) {
console.log("Hello, " + name);
callback();
}
function sayGoodbye() {
console.log("Goodbye!");
}
greet("Aarushi", sayGoodbye);
// Output:
// Hello, Aarushi
// Goodbye!
In this example, sayGoodbye is passed as a callback to greet. After greeting, the callback is executed.
Callbacks can be executed synchronously, meaning they are called immediately within the function.
function doubleArray(arr, callback) {
const result = arr.map(callback);
return result;
}
const numbers = [1, 2, 3, 4];
const doubled = doubleArray(numbers, num => num * 2);
console.log(doubled); // [2, 4, 6, 8]
Here, the callback function num => num * 2 is executed immediately for each array element.
Callbacks are often used for asynchronous operations, such as handling timers, fetching data, or reading files.
console.log("Start");
setTimeout(() => {
console.log("This runs after 2 seconds");
}, 2000);
console.log("End");
Output:
Start
End
This runs after 2 seconds
The function passed to setTimeout is an asynchronous callback executed after a delay of 2 seconds.
Callbacks are widely used in event-driven programming. In JavaScript, events such as clicks, mouse movements, or key presses trigger callbacks.
const button = document.getElementById("myButton");
button.addEventListener("click", () => {
console.log("Button clicked!");
});
Whenever the button is clicked, the callback function is executed.
Sometimes, callbacks are nested inside other callbacks, leading to deeply nested structures known as callback hell.
setTimeout(() => {
console.log("Step 1");
setTimeout(() => {
console.log("Step 2");
setTimeout(() => {
console.log("Step 3");
}, 1000);
}, 1000);
}, 1000);
While functional, this structure can become difficult to read, maintain, and debug. Modern JavaScript often uses Promises or async/await to handle asynchronous flows more cleanly.
Forgetting to call the callback function
Overusing nested callbacks, creating "callback hell"
Passing the result of a function instead of the function itself
Not handling errors in asynchronous callbacks properly
Ignoring proper this context in callbacks
Keep callbacks simple and focused on a single task
Avoid deeply nested callbacks by modularizing code or using Promises
Handle errors inside callbacks to prevent silent failures
Use arrow functions for concise syntax and to preserve context
Clearly document which parameters a callback expects
Handling user interactions such as button clicks or form submissions
Making API calls and processing responses asynchronously
Scheduling tasks with setTimeout or setInterval
Reading or writing files in Node.js asynchronously
Implementing higher-order functions like map, filter, and reduce
function greet(name, callback) {
console.log("Hello, " + name);
callback();
}
function farewell() {
console.log("Goodbye!");
}
greet("Priya", farewell);
// Output:
// Hello, Priya
// Goodbye!
function processArray(arr, callback) {
const result = arr.map(callback);
return result;
}
const scores = [10, 20, 30];
const squaredScores = processArray(scores, num => num * num);
console.log(squaredScores); // [100, 400, 900]
setTimeoutconsole.log("Task start");
setTimeout(() => {
console.log("Task executed after delay");
}, 1500);
console.log("Task end");
const input = document.getElementById("username");
input.addEventListener("input", () => {
console.log("Input changed: " + input.value);
});
function fetchData(callback) {
const error = null;
const data = { name: "Aarushi", age: 20 };
callback(error, data);
}
fetchData((err, result) => {
if (err) {
console.log("Error occurred:", err);
} else {
console.log("Data received:", result);
}
});
This pattern is widely used in Node.js for handling asynchronous operations with potential errors.
JavaScript callbacks are functions passed as arguments to other functions and executed later, either synchronously or asynchronously. They are a powerful tool for handling events, processing data, and managing asynchronous operations. While nested callbacks can lead to complexity, proper use, modularization, and error handling ensure clean and maintainable code. Mastering callbacks is essential for writing responsive and scalable JavaScript applications.
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
