Understanding JavaScript Callbacks
Harshit Pandey
React Native | JavaScript | Typescript | Android | IOS | DSA | Node JS
JavaScript callbacks are an essential concept that allows functions to be passed as arguments and executed later. They play a significant role in asynchronous programming, ensuring that specific code runs after particular tasks are completed.
?? What is a Callback?
A callback is simply a function passed as an argument to another function. Once the first function completes its task, it calls (or executes) the callback function.
function fetchData(callback) {
console.log('Fetching data...');
setTimeout(() => {
console.log('Data fetched!');
callback('Fetched Data');
}, 2000);
}
function displayData(data) {
console.log(`Displaying: ${data}`);
}
fetchData(displayData);
???? Why Use Callbacks?
? Callback Hell (Pyramid of Doom)
When callbacks are nested within each other, it can lead to unreadable and unmanageable code, also known as Callback Hell.
? Solution: Using Promises or Async/Await
To avoid Callback Hell, you can use Promises or Async/Await for cleaner and more readable code.