GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.geeksforgeeks.org — JavaScript Callbacks - GeeksforGeeks JavaScript CallbacksLast Updated : 17 Jan, 2026 A callback function is a function that is passed as an argument to another function and executed later.
Here, sayBye() is passed as a callback to greet(), which executes after the greeting. Working of Callbacks in JavaScriptJavaScript executes code line by line (synchronously), but sometimes we need to delay execution or wait for a task to complete before running the next function. Callbacks help achieve this by passing a function that is executed later. Callbacks for Asynchronous Execution
Uses of Callbacks in JavaScript1. Handling Asynchronous OperationsCallbacks are widely used in
2. Callbacks in Functions Handling OperationsWhen a function needs to execute different behaviors based on input, callbacks make the function flexible.
3. Callbacks in Event ListenersJavaScript is event-driven, and callbacks handle user interactions like clicks and key presses.
Here, the anonymous function is a callback that runs when the button is clicked. 4. Callbacks in API Calls (Fetching Data)Callbacks are useful when retrieving data from APIs.
fetchData() gets data from an API and passes it to handleData() for processing. Problems with CallbacksAlthough callbacks are useful, they have some drawbacks. 1. Callback Hell (Nested Callbacks)When callbacks are nested deeply, the code becomes unreadable and hard to maintain.
As the number of steps increases, the nesting grows deeper, making the code difficult to manage. 2. Error Handling Issues in CallbacksError handling can get messy when dealing with nested callbacks.
Handling errors inside callbacks can complicate code readability. Alternatives to Callbacks1. Promises (Fixing Callback Hell)Promises provide a better way to handle asynchronous tasks without deep nesting.
Promises make code more readable by chaining .then() instead of nesting callbacks. 2. Async/Await (Cleaner Alternative)async/await provides an even cleaner way to handle asynchronous code.
async/await makes code look synchronous, improving readability. When to Use and Avoid CallbacksUse callbacks when
Avoid callbacks when:
Comment Explore |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |