← 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

LanguageAsync MechanismDescription
JavaScriptWeb APIs + Event LoopSingle-threaded but offloads work via the browser or Node.js
Pythonasyncio / threadingUses coroutines or OS threads
JavaThread pools / CompletableFutureUses real multithreading
C#async/await + Task SchedulerManaged by the .NET runtime
GoGoroutines + SchedulerLightweight 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.