JavaScript Notes
Learn the difference between synchronous and asynchronous JavaScript with real-world analogies, code examples, text diagrams, and interview questions. Understand how JS handles blocking and non-blocking operations despite being single-threaded.
Introduction — JavaScript is Single-Threaded
JavaScript is a single-threaded language — it has one call stack and executes one operation at a time. Think of it as a single worker who picks up one task, finishes it, then moves to the next.
But how does JavaScript handle network requests, timers, and user interactions without freezing the page? The answer: asynchronous execution. JavaScript uses Web APIs, a callback queue, and an event loop to handle time-consuming operations without blocking the main thread.
In this lesson you'll learn:
- What synchronous (blocking) execution means
- What asynchronous (non-blocking) execution means
- Why JavaScript needs async despite being single-threaded
- Real-world analogies and 6+ code examples with outputs
Synchronous Code — Line by Line, Blocking
In synchronous code, JavaScript executes each statement one after another. The next line will NOT run until the current line finishes. If any line takes a long time, everything below it waits.
Key traits: predictable order, blocking, simple to read, dangerous for long operations.
console.log("First");
console.log("Second");
console.log("Third");First Second Third
If you add a heavy computation between lines, everything freezes:
Before heavy task After heavy task: 1999999999000000000 ← after 3 second freeze This had to wait!
During those 3 seconds, clicks, scrolling, and animations all freeze.
Asynchronous Code — Non-Blocking
In async code, JavaScript starts an operation and immediately moves to the next line without waiting. When the operation finishes later, a callback handles the result.
Key traits: non-blocking, execution order ≠ code order, results come via callbacks/promises.
console.log("Before async operation");
setTimeout(function() {
console.log("Inside setTimeout (runs later)");
}, 2000);
console.log("After async (runs immediately!)");Before async operation After async (runs immediately!) Inside setTimeout (runs later) ← 2 seconds later
JavaScript doesn't wait for setTimeout — it hands the timer to the Web API and moves on. When the timer completes, the callback enters the queue, and the event loop pushes it to the call stack when it's empty.
Code Examples
Example 1: Synchronous Execution Order
function greet(name) {
console.log("Hello, " + name);
}
console.log("Start");
greet("Alice");
greet("Bob");
console.log("End");Start Hello, Alice Hello, Bob End
No surprises — output matches code order exactly.
Example 2: setTimeout Demo — 0ms Is Still Async
console.log("1 - Start");
setTimeout(function() {
console.log("2 - Timeout 0ms");
}, 0);
console.log("3 - End");1 - Start 3 - End 2 - Timeout 0ms
Even with 0ms delay, setTimeout goes through Web API → queue → event loop. Synchronous code always finishes first.
Example 3: Async Order Surprise — Multiple Timers
console.log("A");
setTimeout(function() { console.log("B"); }, 3000);
setTimeout(function() { console.log("C"); }, 1000);
setTimeout(function() { console.log("D"); }, 0);
console.log("E");A E D ← 0ms (fastest async) C ← 1 second later B ← 3 seconds later
Sync code first (A, E), then callbacks in completion order (D, C, B).
Example 4: Real-World Analogy in Code — Restaurant Kitchen
function asyncRestaurant() {
console.log("Waiter takes order 1: Pasta");
setTimeout(function() {
console.log("🍝 Pasta ready! (took longest)");
}, 3000);
console.log("Waiter takes order 2: Salad");
setTimeout(function() {
console.log("🥗 Salad ready! (quick dish)");
}, 1000);
console.log("Waiter takes order 3: Soup");
setTimeout(function() {
console.log("🍲 Soup ready! (medium time)");
}, 2000);
console.log("All orders placed! Waiter is free.");
}
asyncRestaurant();Waiter takes order 1: Pasta Waiter takes order 2: Salad Waiter takes order 3: Soup All orders placed! Waiter is free. 🥗 Salad ready! (quick dish) 🍲 Soup ready! (medium time) 🍝 Pasta ready! (took longest)
The waiter (main thread) takes all orders without waiting. Kitchen (Web API) cooks in parallel. Food arrives when ready (callbacks).
Example 5: Sync vs Async Data Reading Pattern
=== Sync === Sync: reading... Sync: done → chunk0 chunk1 chunk2 Got: chunk0 chunk1 chunk2 === Async === Async: reading started... Async: function returned (data not ready yet) Code continues... Async: done → chunk0 chunk1 chunk2 ← 1.5s later Callback got: chunk0 chunk1 chunk2
Example 6: Mixing Sync + Async (Microtasks vs Macrotasks)
console.log("1 - Sync");
setTimeout(function() {
console.log("2 - Macrotask (setTimeout)");
}, 0);
Promise.resolve().then(function() {
console.log("3 - Microtask (Promise)");
});
console.log("4 - Sync");
setTimeout(function() {
console.log("5 - Macrotask (setTimeout 2)");
}, 0);
Promise.resolve().then(function() {
console.log("6 - Microtask (Promise 2)");
});
console.log("7 - Sync");1 - Sync 4 - Sync 7 - Sync 3 - Microtask (Promise) 6 - Microtask (Promise 2) 2 - Macrotask (setTimeout) 5 - Macrotask (setTimeout 2)
Priority order: All synchronous → all microtasks (Promises) → macrotasks (setTimeout) one by one.
Real-World Analogies
🍽️ Restaurant Waiter
| Synchronous Waiter | Asynchronous Waiter |
|---|---|
| Takes order 1, stands in kitchen waiting | Takes order 1, gives to kitchen |
| Food ready → delivers to customer 1 | Immediately takes order 2, 3, 4... |
| Only THEN takes order 2 | When food is ready → delivers to right customer |
| Customers wait 30+ minutes | Everyone served efficiently |
Mapping: Waiter = main thread. Kitchen = Web API. "Food ready" bell = callback queue. Waiter checking the bell = event loop.
🏦 Bank Queue
Sync Bank: You wait in line. Person ahead fills a 50-page form. You wait 30 minutes for your 10-second task.
Async Bank: Take a token, sit down, browse your phone. When your number is called (callback!), go to counter. You're FREE while waiting.
Why JavaScript Needs Async
The main thread handles: rendering, user input, animations, AND your JavaScript. If JS blocks this thread:
Operations that MUST be async: network requests, timers, file I/O, database queries, GPS/geolocation, user events.
Common Mistakes
1. Treating async results as synchronous
2. Assuming setTimeout(fn, 0) runs immediately
It still goes through the async pipeline — runs AFTER all sync code.
3. Using busy-wait loops for delay
4. Trying to return values from callbacks
5. Not handling async errors
Key Takeaways
- JavaScript is single-threaded — one call stack, one operation at a time.
- Synchronous = blocking — each line waits for the previous. Output order = code order.
- Asynchronous = non-blocking — long tasks delegated to Web APIs. Main thread stays free.
- setTimeout(fn, 0) is NOT instant — still async, runs after all sync code.
- Event loop bridges sync and async — moves callbacks to stack when stack is empty.
- Microtasks (Promises) run before Macrotasks (setTimeout) in the same event loop cycle.
- Never block the main thread — use async for network, timers, I/O.
- You can't return values from callbacks directly — use Promises or async/await.
- Always handle errors in async code with
.catch()ortry/catch. - async/await makes async code look synchronous but it's still non-blocking underneath.
Interview Questions
Q1: What is the difference between synchronous and asynchronous JavaScript?
Synchronous code runs line by line — each statement blocks until complete. Asynchronous code starts an operation and continues without waiting. Results arrive later via callbacks, promises, or async/await. Async keeps the application responsive.
Q2: Why does code after setTimeout(fn, 0) run first?
Because setTimeout is a Web API — even with 0ms delay, the callback enters the macrotask queue. It can only execute after all synchronous code finishes and the call stack is empty. The event loop enforces this order.
Q3: How does single-threaded JavaScript handle async operations?
JavaScript delegates async work to browser Web APIs (separate threads). When complete, callbacks enter the queue. The event loop moves them to the call stack when it's empty. JS itself stays single-threaded; concurrency comes from the environment.
Q4: Output of: log("A"); setTimeout(()=>log("B"),0); Promise.resolve().then(()=>log("C")); log("D");?
Output: A, D, C, B. Sync first (A, D). Microtask next (C — Promise). Macrotask last (B — setTimeout).
Q5: Why is async important for web applications?
Without async, any network request or heavy operation freezes the entire page — no scrolling, clicking, or animations. Async lets the UI stay responsive while operations complete in the background, providing a smooth user experience.
FAQ
Is JavaScript synchronous or asynchronous?
JavaScript is synchronous by nature (single-threaded, sequential execution). But the runtime environment (browser/Node.js) provides async capabilities via Web APIs, the event loop, and task queues.
Can I convert synchronous code to asynchronous?
You can't make a blocking loop async by itself. Use Web Workers for CPU-heavy work on a separate thread, or setTimeout to break work into chunks. For I/O operations, use async APIs like fetch instead of sync alternatives.
What happens if async code throws an error?
Without .catch() or try/catch, it becomes an unhandled promise rejection — a silent failure in older browsers, a warning/crash in modern environments. Always handle async errors explicitly.
Is async/await truly synchronous?
No — it's syntactic sugar over Promises. await pauses only inside the async function. Code outside continues running immediately. Under the hood, it's still non-blocking.
When should I use sync vs async?
Use sync for quick operations: math, variable assignment, DOM reads. Use async for anything slow or unpredictable: network requests, timers, file reads, database calls. Rule: if it might take >few ms, make it async.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Synchronous vs Asynchronous JavaScript — Complete Explanation 2026.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, asynchronous, synchronous, synchronous vs asynchronous javascript — complete explanation 2026
Related JavaScript Master Course Topics