- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array length
- Arrays
- Between braces
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Destructuring
- Else
- Else if
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- Function
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Overriding methods
- Parameters
- Promises
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- Substring
- Template literals
- Tile
- Type conversion
- While loop
JAVASCRIPT
JavaScript Callback Function: Syntax, Usage, and Examples
A JavaScript callback function is a function that you pass as an argument to another function. The receiving function then calls (or "executes") the callback at a specific time. Callbacks allow for better code organization and enable asynchronous programming.
How to Use a JavaScript Callback Function
You define a function and pass another function as an argument. The receiving function then calls the callback when needed.
Basic Syntax
function mainFunction(callback) {
console.log("Main function is running...");
callback(); // Call the callback function
}
function callbackFunction() {
console.log("Callback function executed.");
}
mainFunction(callbackFunction);
Here, callbackFunction
is passed to mainFunction
, which then executes it.
Callback Function with Parameters
You can also pass arguments to the callback function.
function greet(name, callback) {
console.log(`Hello, ${name}!`);
callback();
}
function done() {
console.log("Greeting completed.");
}
greet("Alice", done);
The callback done
runs after greet
prints a message.
When to Use a JavaScript Callback Function
- Asynchronous Operations – Callbacks help execute code only when an asynchronous task (like a network request) completes.
- Event Handling – JavaScript uses callbacks for handling user interactions, such as button clicks.
- Reusability and Modularity – Callbacks allow you to create more flexible and reusable functions.
Examples of JavaScript Callback Functions
Handling Asynchronous Code
You often use callbacks with setTimeout
for delaying code execution.
function delayedMessage(callback) {
setTimeout(() => {
console.log("This message appears after 2 seconds.");
callback();
}, 2000);
}
function done() {
console.log("Callback executed after delay.");
}
delayedMessage(done);
Callbacks in Event Listeners
Event listeners rely on callbacks to execute functions when an event occurs.
document.getElementById("btn").addEventListener("click", function () {
console.log("Button clicked!");
});
The anonymous function acts as a callback and runs when you click the button.
Callback Hell
When multiple callbacks are nested, it leads to callback hell, making the code harder to read and maintain.
getUser(function (user) {
getOrders(user, function (orders) {
getPaymentDetails(orders, function (details) {
processPayment(details, function () {
console.log("Payment completed.");
});
});
});
});
You can replace this with Promises or async/await for cleaner code.
Learn More About JavaScript Callback Functions
Using Anonymous Callback Functions
Instead of defining a separate function, you can use an anonymous function as a callback.
setTimeout(function () {
console.log("Anonymous function executed.");
}, 1000);
Async Callback Function
When working with asynchronous operations, passing a callback function ensures the task completes before executing the next step.
function fetchData(url, callback) {
setTimeout(() => {
console.log(`Fetched data from ${url}`);
callback();
}, 1500);
}
fetchData("https://api.example.com", () => {
console.log("Processing fetched data...");
});
Passing Arguments to a Callback
You can pass arguments when calling a callback function.
function processData(data, callback) {
console.log(`Processing: ${data}`);
callback(data);
}
function logData(info) {
console.log(`Logged: ${info}`);
}
processData("User Info", logData);
Avoiding Callback Hell with Promises
To avoid deeply nested callbacks, use Promises.
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data received");
}, 2000);
});
}
fetchData().then((data) => console.log(data));
This structure improves readability and maintainability.
How to Add a Callback Function in JavaScript
To add a callback function, define the function and pass it as an argument when calling another function.
function executeTask(task, callback) {
console.log(`Executing: ${task}`);
callback();
}
executeTask("Download File", function () {
console.log("Download completed.");
});
Callback Function vs. Regular Function
A regular function executes immediately when called. A callback function, on the other hand, runs when another function invokes it.
function regularFunction() {
console.log("Runs immediately.");
}
function callbackExample(callback) {
console.log("Preparing to execute callback...");
callback();
}
callbackExample(regularFunction);
Using Callbacks in Loops
Callbacks also help process arrays using methods like map
, filter
, and forEach
.
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function (num) {
console.log(`Number: ${num}`);
});
Handling Errors in Callback Functions
You should always handle errors inside callbacks to prevent unexpected behavior.
function fetchData(url, callback) {
setTimeout(() => {
const error = false; // Simulating no error
if (error) {
callback("Error occurred", null);
} else {
callback(null, `Data from ${url}`);
}
}, 1000);
}
fetchData("https://api.example.com", function (err, data) {
if (err) {
console.error(err);
} else {
console.log(data);
}
});
JavaScript Callback Function Use Cases
- Managing Asynchronous Code – Callbacks handle API requests, file reading, and database queries.
- Event-Driven Programming – Many JavaScript features, like event listeners, depend on callbacks.
- Code Reusability – Passing different callback functions makes your code more flexible.
Callbacks form the foundation of JavaScript's asynchronous programming. Understanding how to use them effectively will help you write better, more efficient code.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.