Synchronous vs Asynchronous JavaScript

What is Synchronous Code?
Synchronous code runs line by line, in a strict sequence.
Each task must finish before the next one starts.
Example
console.log("Start");
console.log("Processing...");
console.log("End");
// Output:
// Start
// Processing...
// End
Problem With Synchronous Code
Now imagine a slow operation — like fetching data from a server.
console.log("Start");
function fetchData() {
// Simulating delay
const start = Date.now();
while (Date.now() - start < 3000) {} // blocks for 3 sec
console.log("Data fetched");
}
fetchData();
console.log("End");
// Output:
// Start
// (wait 3 seconds...)
// Data fetched
// End
Problem:
The entire program freezes
Nothing else can run
UI becomes unresponsive
This is called blocking code
What is Asynchronous Code?
Asynchronous code allows JavaScript to:
Start a task
Move on without waiting
Handle the result later
Example
console.log("Start");
setTimeout(() => {
console.log("Data fetched");
}, 3000);
console.log("End");
// Output:
// Start
// End
// Data fetched
JavaScript doesn’t wait for setTimeout. It schedules it and moves on.
Why JavaScript Needs Asynchronous Behavior?
JavaScript runs on a single thread.
That means:
One task at a time
No parallel execution like multi-threaded languages
So to avoid freezing, it uses:
Async behavior
Event loop
Task queue
Without async:
Websites would hang while loading data
Buttons wouldn’t respond
Apps would feel broken
Real-World Examples
- API Calls
fetch("https://api.example.com/data")
.then(res => res.json())
.then(data => console.log(data));
- Timers
setTimeout(() => {
console.log("Runs later");
}, 2000);
- User Actions
Clicking a button
Typing in input
Scrolling
Blocking vs Non-Blocking
| Feature | Synchronous | Asynchronous |
|---|---|---|
| Execution | Line-by-line | Doesn’t wait |
| Behavior | Blocking | Non-blocking |
| Performance | Slower UI | Smooth UI |
| Example | Loops, calculations | API calls, timers |
How JavaScript Handles Async (Simple View)?
Even though JavaScript is single-threaded:
It sends async tasks (like
setTimeout,fetch) to the Web APIsWhen done, they go to the Callback Queue
The Event Loop pushes them back to the main thread when it's free
Conclusion
Synchronous = Simple but blocking
Asynchronous = Efficient and scalable
Modern JavaScript heavily relies on async patterns like:
Promises
async/await





