The Event Loop and Callbacks
JavaScript runs on a single thread, yet it can handle timers, network requests, and user input without blocking — the event loop is what makes this possible.
console.log("1");
setTimeout(() => console.log("2"), 0);
console.log("3");
// logs: 1, 3, 2
Even with a 0ms delay, setTimeout's callback doesn't run immediately — it's placed in a queue, and the event loop only pulls from that queue once the current call stack is completely empty. This is why "3" logs before "2" above: the main script must finish first.
A callback is simply a function passed into another function to be run later — the pattern above, or handling a click event, are both callbacks. Deeply nested callbacks, historically needed for chains of dependent async operations, earned the nickname "callback hell" for how unreadable they became — the exact problem promises (next lesson) were designed to solve.