JavaScript Callback Functions Tutorial
#JavaScript Callback Functions Turial
Understand how callback functions work and how to use them in JavaScript.
Callback functions are a fundamental concept in JavaScript, especially when working with asynchronous operations or higher-order functions. This tutorial explains what they are, why they matter, and how to use them effectively.
A callback function is a function that is passed as an argument to another function and is executed after the parent function completes its task.
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
function sayGoodbye() {
console.log("Goodbye!");
}
greet("Alice", sayGoodbye);
To handle asynchronous operations (e.g., API calls, timers)
To reuse functions
For custom logic injection into a function
setTimeout(() => {
console.log("Executed after 2 seconds");
}, 2000);
const numbers = [1, 2, 3];
numbers.forEach(num => console.log(num * 2));
document.getElementById("btn").addEventListener("click", function() {
alert("Button clicked!");
});
Promote modular code
Enable custom logic
Support asynchronous programming
When callbacks are nested inside other callbacks, it can lead to unreadable code.
doSomething(function(result) {
doSomethingElse(result, function(newResult) {
doAnotherThing(newResult, function(finalResult) {
console.log(finalResult);
});
});
});
Solution: Use Promises or async/await for better readability.
Callback functions are essential for writing clean, flexible, and asynchronous code in JavaScript. Understanding how to use them properly will make you a more effective developer and prepare you for working with APIs, events, and modern JavaScript frameworks.