Callback Functions in JavaScript 🚀
Callback Functions in JavaScript 🚀
Ever wondered why End prints before Data Loaded?
JavaScript is single-threaded, but it can handle asynchronous tasks like timers, API requests, and file operations. Instead of waiting for these tasks to finish, JavaScript keeps executing the next lines of code.
That's where callback functions come in.
Definition
A callback function is a function passed as an argument to another function. It is executed later, after a specific task is completed.
Example
console.log("Start");
setTimeout(() => {
console.log("Data Loaded");
}, 2000);
console.log("End");
Output
Start
End
Data Loaded
Why?
setTimeout starts a timer and immediately returns. JavaScript doesn't wait for the timer. Once it completes, the callback function is executed.
Common use cases
• setTimeout()
• setInterval()
• Event Listeners
• API Requests (before Promises)
• File System Operations in Node.js
Advantages
✅ Makes asynchronous programming possible
✅ Executes code only after a task completes
✅ Keeps applications responsive
Disadvantages
❌ Too many nested callbacks create Callback Hell
❌ Code becomes difficult to read and maintain
In the next reel, we'll understand Callback Hell and why Promises were introduced.
Follow @dev.techtricks for more JavaScript content.
#javascript #js #nodejs #webdevelopment #programming coding developer frontend backend softwareengineer learnjavascript javascriptdeveloper devtechtricks
Comments
Comments from the original post on Instagram
No comments yet
