![]() |
JavaScript, a single-threaded language, relies on callbacks for handling asynchronous tasks. Callbacks execute code once an operation finishes. But as the code complexity increases, the risk of callback hell emerges. Callback:A callback is a function that is passed as an argument to another function that executes the callback based on the result. They are basically functions that are executed only after a result is produced. Callbacks are an important part of asynchronous JavaScript. Example: In this example, we have used setTimeout in the mainFunction to mimic some I/O Operations or a request call. The callback function passed is used to sum up the elements of the array. After 2 seconds have passed, the sum of the array is printed which is 9. Javascript
Output: 9 Callback Hell:Callback Hell is essentially nested callbacks stacked below one another forming a pyramid structure. Every callback depends/waits for the previous callback, thereby making a pyramid structure that affects the readability and maintainability of the code. Example: In the below example we have split the word GeeksForGeeks into three separate words and are trying to animate each word after one after another. HTML
Output: We can notice that the animateAll function takes a pyramid structure, thereby making it difficult to read. ![]() Geeks For Geeks animated callback output Reference: https://developer.mozilla.org/en-US/docs/Glossary/Callback_function |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 10 |