📘 Lesson · Lesson 42
Callbacks
Callbacks
What a Callback Is
function greet(name, callback) {
console.log("Hi " + name);
callback(); // run the function we were handed
}
greet("Aman", function() {
console.log("Greeting finished");
});
// Hi Aman
// Greeting finished
A callback is simply a function passed as an argument to another function, to be called later. That's the whole idea — you hand over a function, and the receiving code decides WHEN to run it. Remember that in JavaScript, functions are values, so passing one around is no stranger than passing a number. Callbacks matter because they let you say "when you're done, run this." That "when you're done" is what makes them essential for asynchronous work.
Synchronous vs Asynchronous
// SYNCHRONOUS — runs top to bottom, each line waits for the last
console.log("First");
console.log("Second");
// Output: First, Second
// ASYNCHRONOUS — doesn't block; the rest keeps running
console.log("First");
setTimeout(() => console.log("Second"), 2000); // scheduled for later
console.log("Third");
// Output: First, Third, Second ← Second arrives 2 seconds later
JavaScript runs one line at a time (synchronously) — but some operations, like waiting 2 seconds or fetching data from a server, would freeze the page if they blocked everything. So those operations are ASYNCHRONOUS: JavaScript starts them, moves on immediately, and runs your callback later when the result is ready. That's why "Third" prints before "Second" above. This is the single most important concept in the rest of this group — the code does NOT run in the order it's written.
setTimeout and setInterval
// Run a function ONCE after a delay (in milliseconds)
setTimeout(() => console.log("2 seconds passed"), 2000);
// Run a function REPEATEDLY every N milliseconds
const id = setInterval(() => console.log("tick"), 1000);
clearInterval(id); // stop it
// Note: the delay is a MINIMUM, not a guarantee
setTimeout(() => console.log("Later"), 0); // still runs AFTER sync code
console.log("Now");
// Output: Now, Later
setTimeout(callback, delay) schedules a function to run once after a delay; setInterval repeats it forever until you call clearInterval. Both take a callback as their first argument — your first hands-on taste of asynchronous JavaScript. A surprising detail: even setTimeout(fn, 0) doesn't run immediately. All synchronous code finishes first, and only then does the scheduled callback get its turn. Delays are a minimum wait, not a precise promise.Callbacks You Already Use
// Array methods take callbacks:
[1, 2, 3].forEach(n => console.log(n));
[1, 2, 3].map(n => n * 2);
[1, 2, 3].filter(n => n > 1);
// Event listeners take callbacks:
button.addEventListener("click", () => console.log("Clicked"));
// setTimeout takes a callback:
setTimeout(() => console.log("Hi"), 1000);
You've been using callbacks for chapters without the name. Every array method that takes a function —
forEach, map, filter, reduce, sort — receives a callback and calls it for each item. Every addEventListener hands over a callback to run when the event fires (which could be never, or a hundred times). Seeing them all as one pattern — "give a function, let something else call it" — is a genuine step up in understanding JavaScript.Callback Hell — why we needed something better
// Nested callbacks: each step waits for the previous one
getUser(1, function(user) {
getOrders(user.id, function(orders) {
getOrderDetails(orders[0].id, function(details) {
getShipping(details.id, function(shipping) {
console.log(shipping); // finally!
});
});
});
});
// ↑ The "pyramid of doom" — hard to read, harder to handle errors
When one asynchronous task depends on another, callbacks nest inside callbacks — quickly producing a sideways pyramid that's painful to read, debug, and handle errors in. Developers named this "callback hell." It's not that callbacks are bad; it's that CHAINING them scales badly. This exact frustration led to the invention of Promises, and later async/await — both designed to write asynchronous steps in a flat, readable sequence. That's precisely what the next two chapters cover.
Exam Corner
Q: What is a callback function? A function passed as an argument to another function, to be called later.
Q: What is asynchronous code? Code that starts an operation and continues without waiting, running a callback when it finishes.
Q: What does
Q: Name three places you already use callbacks. Array methods (map/filter/forEach), addEventListener, setTimeout.
Q: What is callback hell? Deeply nested callbacks from chained async tasks, which are hard to read and debug.
Q: What is asynchronous code? Code that starts an operation and continues without waiting, running a callback when it finishes.
Q: What does
setTimeout(fn, 0) do? Runs fn after all synchronous code finishes — not immediately.Q: Name three places you already use callbacks. Array methods (map/filter/forEach), addEventListener, setTimeout.
Q: What is callback hell? Deeply nested callbacks from chained async tasks, which are hard to read and debug.
Callback क्या है
function greet(name, callback) {
console.log("Hi " + name);
callback(); // jo function mila usse chalao
}
greet("Aman", function() {
console.log("Greeting finished");
});
// Hi Aman
// Greeting finished
Callback बस वह function है जो दूसरे function को argument के रूप में भेजा जाता है, बाद में call होने को. यही पूरा विचार है — आप एक function सौंपते हैं, और पाने वाला code तय करता है उसे KAB चलाना. याद रखिए JavaScript में functions values हैं, तो एक को इधर-उधर भेजना number भेजने से अजीब नहीं. Callbacks इसलिए मायने रखते हैं क्योंकि वे आपको कहने देते हैं "जब आप पूरा कर लें, यह चलाइए." वह "जब आप पूरा कर लें" ही उन्हें asynchronous काम के लिए ज़रूरी बनाता है.
Synchronous vs Asynchronous
// SYNCHRONOUS — ooper se neeche, har line pichhli ka intezaar karti
console.log("First");
console.log("Second");
// Output: First, Second
// ASYNCHRONOUS — block nahi karta; baaki chalta rehta hai
console.log("First");
setTimeout(() => console.log("Second"), 2000); // baad ke liye scheduled
console.log("Third");
// Output: First, Third, Second ← Second 2 second baad aata hai
JavaScript एक बार में एक line चलाता है (synchronously) — पर कुछ operations, जैसे 2 सेकंड इंतज़ार या server से data लाना, सब कुछ block करें तो page जम जाए. तो वे operations ASYNCHRONOUS हैं: JavaScript उन्हें शुरू करता है, तुरंत आगे बढ़ता है, और नतीजा तैयार होने पर बाद में आपका callback चलाता है. इसीलिए ऊपर "Third" "Second" से पहले print होता है. यह इस group के बाकी हिस्से का सबसे ज़रूरी concept है — code उस order में NAHI चलता जिसमें लिखा है.
setTimeout और setInterval
// Delay ke baad function EK BAAR chalao (milliseconds me)
setTimeout(() => console.log("2 seconds passed"), 2000);
// Har N milliseconds par BAAR-BAAR chalao
const id = setInterval(() => console.log("tick"), 1000);
clearInterval(id); // roko
// Note: delay NYUNTAM hai, guarantee nahi
setTimeout(() => console.log("Later"), 0); // phir bhi sync code ke BAAD
console.log("Now");
// Output: Now, Later
setTimeout(callback, delay) function को delay के बाद एक बार चलाने को schedule करता है; setInterval उसे हमेशा दोहराता है जब तक आप clearInterval call न करें. दोनों पहले argument के रूप में callback लेते हैं — asynchronous JavaScript का आपका पहला व्यावहारिक स्वाद. आश्चर्यजनक विवरण: setTimeout(fn, 0) भी तुरंत नहीं चलता. सारा synchronous code पहले खत्म होता है, और तभी scheduled callback को बारी मिलती है. Delays न्यूनतम इंतज़ार हैं, सटीक वादा नहीं.Callbacks जो आप पहले से use करते हैं
// Array methods callbacks lete hain:
[1, 2, 3].forEach(n => console.log(n));
[1, 2, 3].map(n => n * 2);
[1, 2, 3].filter(n => n > 1);
// Event listeners callbacks lete hain:
button.addEventListener("click", () => console.log("Clicked"));
// setTimeout callback leta hai:
setTimeout(() => console.log("Hi"), 1000);
आप कई chapters से callbacks use कर रहे हैं बिना नाम जाने. हर array method जो function लेता है —
forEach, map, filter, reduce, sort — callback पाता है और हर item के लिए उसे call करता है. हर addEventListener callback सौंपता है event fire होने पर चलने को (जो कभी नहीं, या सौ बार हो सकता है). इन सबको एक pattern के रूप में देखना — "function दो, कुछ और उसे call करने दो" — JavaScript समझने में असली छलांग है.Callback Hell — बेहतर कुछ क्यों चाहिए था
// Nested callbacks: har kadam pichhle ka intezaar karta
getUser(1, function(user) {
getOrders(user.id, function(orders) {
getOrderDetails(orders[0].id, function(details) {
getShipping(details.id, function(shipping) {
console.log(shipping); // aakhirkar!
});
});
});
});
// ↑ "Pyramid of doom" — padhna mushkil, errors sambhalna aur mushkil
जब एक asynchronous काम दूसरे पर निर्भर हो, callbacks callbacks के अंदर nest होते हैं — जल्दी ही तिरछा pyramid बनाते जो पढ़ने, debug करने, और errors संभालने में तकलीफदेह है. Developers ने इसे "callback hell" नाम दिया. बात यह नहीं कि callbacks बुरे हैं; बात यह है कि उन्हें CHAIN करना बुरी तरह scale होता है. ठीक यही निराशा Promises, और बाद में async/await के आविष्कार तक ले गई — दोनों asynchronous कदमों को समतल, पढ़ने योग्य क्रम में लिखने को बने. अगले दो chapters ठीक यही cover करते हैं.
Exam Corner
Q: Callback function क्या है? दूसरे function को argument के रूप में भेजा function, बाद में call होने को.
Q: Asynchronous code क्या है? ऐसा code जो operation शुरू करके बिना इंतज़ार किए चलता रहता है, पूरा होने पर callback चलाते.
Q:
Q: तीन जगहें बताइए जहां आप पहले से callbacks use करते हैं. Array methods (map/filter/forEach), addEventListener, setTimeout.
Q: Callback hell क्या है? Chained async tasks से गहरे nested callbacks, जिन्हें पढ़ना और debug करना मुश्किल है.
Q: Asynchronous code क्या है? ऐसा code जो operation शुरू करके बिना इंतज़ार किए चलता रहता है, पूरा होने पर callback चलाते.
Q:
setTimeout(fn, 0) क्या करता है? सारा synchronous code खत्म होने के बाद fn चलाता है — तुरंत नहीं.Q: तीन जगहें बताइए जहां आप पहले से callbacks use करते हैं. Array methods (map/filter/forEach), addEventListener, setTimeout.
Q: Callback hell क्या है? Chained async tasks से गहरे nested callbacks, जिन्हें पढ़ना और debug करना मुश्किल है.
💻 Live Code Editor
इस पेज का code यहाँ तैयार है — बदलिए और तुरंत नतीजा देखिए. कुछ install किए बिना.
सब कुछ आपके browser में ही चलता है — कोई server, कोई signup नहीं. JavaScript का
console.log देखने के लिए F12 दबाइए.