Asynchronous Code Execution Order
You'll learn: How async callbacks execute after all synchronous code finishes, even when they appear earlier in your file.
The Surprising Execution Order
Even though you write asynchronous code (like setTimeout) at the top of your script, it doesn't run immediately. JavaScript follows a strict rule: finish all synchronous code first, then handle async callbacks.
Think of it like a restaurant kitchen. The chef (JavaScript) prepares orders one at a time in the order received (synchronous tasks). When someone orders something that needs to bake for 10 minutes, the chef sets a timer but doesn't stand there waiting. Instead, they continue preparing other orders. Only when all current orders are done and the timer beeps does the chef return to the baked item.
Observing the Pattern
console.log("First");
setTimeout(() => {
console.log("Async callback");
}, 0);
console.log("Second");
console.log("Third");
Output:
First
Second
Third
Async callback
Notice the callback runs last, even though setTimeout appears in the middle of the code and has a delay of 0 milliseconds! JavaScript executes "First," "Second," and "Third" without interruption because they're synchronous. Only after the synchronous script completes does the callback get its turn.
This happens because async operations don't execute immediately—they schedule callbacks to run later, after the current execution finishes.
Key Takeaway: Asynchronous callbacks always run after all synchronous code completes, regardless of where they appear in your code or their delay value. JavaScript never interrupts synchronous execution to handle async operations.