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
// Main function const mainFunction = (callback) => { setTimeout(() => { callback([2, 3, 4]); }, 2000) } // Add function const add = (array) => { let sum = 0; for (let i of array) { sum += i; } console.log(sum); } // Calling main function mainFunction(add); |
Output:
9
What to understand Callback and Callback hell in JavaScript ?
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.