β Back to all posts
π§ Understand Synchronous and Asynchronous JavaScript Once and For All
πΉ What Is Synchronous JavaScript?
Synchronous JavaScript runs line by line β each operation waits for the previous one to finish before starting the next. Example:
console.log("A");
console.log("B");
console.log("C");
Output:
A
B
C
Each statement runs in order β nothing happens at the same time.
πΉ What Is Asynchronous JavaScript?
Asynchronous JavaScript means tasks donβt wait for each other β JavaScript can continue running other code while waiting for something time-consuming to finish. But since JavaScript is single-threaded, how does it do that? π€ Through the Web APIs.
βοΈ How JavaScript Handles Asynchronous Code
The Web API is a set of built-in browser features (written in C++) that allow JavaScript to run tasks outside its main thread, like:
- Network requests (
fetch,XMLHttpRequest) - Timers (
setTimeout,setInterval) - DOM manipulation
- Geolocation
- WebSockets
π§© Example: Asynchronous Code in Action
console.log("A");
setTimeout(() => {
console.log("B");
}, 1000);
console.log("C");
Output:
A
C
B
π― Quick Interview Question
console.log("A");
setTimeout(() => {
console.log("B");
}, 0);
console.log("C");
Answer:
A
C
B
Even with a delay of 0ms, the callback still goes through the Web API β Task Queue β Event Loop before it runs.
π How Other Languages Handle Async
| Language | Async Mechanism | Description |
|---|---|---|
| JavaScript | Web APIs + Event Loop | Single-threaded but offloads work via the browser or Node.js |
| Python | asyncio / threading | Uses coroutines or OS threads |
| Java | Thread pools / CompletableFuture | Uses real multithreading |
| C# | async/await + Task Scheduler | Managed by the .NET runtime |
| Go | Goroutines + Scheduler | Lightweight threads managed by Go runtime |
β Final Summary
- Synchronous: runs in order, blocking other code.
- Asynchronous: runs independently without blocking.
- JavaScript uses Web APIs, Task Queues, and the Event Loop.
- Other languages use true multithreading.