Introduction to Callbacks in JavaScript
A callback function is passed as an argument to another function and executed later. This is useful for handling asynchronous operations, event handling, and customizing behavior.
🔹 Why Use Callbacks?
✅ Delays execution until an event happens
✅ Handles asynchronous operations like file reading, API requests, and timers
✅ Prevents blocking the main thread
🔹 Basic Callback Example
A callback is simply a function passed as an argument.
✔ sayGoodbye
is executed after greet
completes.
🔹 Callbacks for Asynchronous Operations
JavaScript is non-blocking, so callbacks help handle asynchronous tasks like fetching data.
✅ Example: Using setTimeout
✅ Output:
✔ The callback waits until the data is ready.
🔹 Callbacks for Handling Events
Callbacks are commonly used for event listeners.
✔ The function inside addEventListener
executes only when the button is clicked.
🔹 Nested Callbacks (Callback Hell)
When multiple callbacks are nested, it becomes hard to read.
✅ Output (with 1-second delays)
✔ But nesting too many callbacks can make code hard to read.
🔹 Avoiding Callback Hell with Promises
Using Promises instead of callbacks makes code cleaner.
✔ Promises help write readable, maintainable async code.
🔹 Summary
✔ A callback is a function passed as an argument to another function
✔ Callbacks handle async tasks, such as timers, file reading, and API calls
✔ Too many nested callbacks lead to "callback hell"
✔ Promises and async/await
can make code cleaner
🚀 Want to learn more? Let me know! 😊