Synchronous vs Asynchronous JavaScript: Understand How Code Executes
async/await to handle these operations.1. Why Do We Need Asynchronous JavaScript?
Imagine a hospital dashboard handling 1,000 appointment requests.
Each request needs patient details, doctor availability and appointment confirmation.
What happens if one slow request blocks every other task?
The problem: synchronous execution
JavaScript normally executes statements in order. Each statement waits for the previous one.
Consider this simple appointment desk example.
This example uses three patient records. Each task runs before the next starts.
function processAppointment(patient) {
console.log("Checking " + patient);
}
console.log("Hospital desk opened");
processAppointment("Anita");
processAppointment("Rahul");
processAppointment("Meena");
console.log("All appointments checked");
Hospital desk opened
Checking Anita
Checking Rahul
Checking Meena
All appointments checked
This works, but every operation must finish before the next begins.
What goes wrong with slow operations?
- A slow task can delay the work that follows it.
- The browser may stop responding while long JavaScript runs.
- Users may experience delayed clicks, scrolling and updates.
- Independent tasks cannot make progress during a blocking operation.
Now think about 1,000 appointment requests arriving together.
We need a way to handle waiting without blocking other work.
2. What Is Asynchronous JavaScript?
Asynchronous JavaScript lets an operation finish later. Other JavaScript work can continue while it waits.
For example, a hospital dashboard can request doctor availability. It can keep responding while the server processes that request.
Asynchronous = an operation can complete later without blocking the current JavaScript flow.
Example 2: Handling an appointment asynchronously
We use setTimeout() to simulate a delayed server response.
It schedules a callback after the given delay. It does not block the current code.
function checkDoctorAvailability() {
console.log("Checking doctor availability...");
setTimeout(() => {
console.log("Doctor is available");
}, 2000);
}
console.log("Hospital dashboard opened");
checkDoctorAvailability();
console.log("Dashboard is ready for other work");
Hospital dashboard opened
Checking doctor availability...
Dashboard is ready for other work
Doctor is available
3. How Synchronous and Asynchronous Execution Differ
Wait and continue
One operation finishes before the next statement runs.
Example: Calculate a patient's age from a date.
Continue while waiting
Other work can run while an operation is pending.
Example: Fetch doctor availability from a server.
| Area | Synchronous | Asynchronous |
|---|---|---|
| Execution | Runs in sequence | Can continue while waiting |
| Waiting | Current flow waits | Waiting operation completes later |
| UI response | Long tasks can block the UI | Suitable for non-blocking operations |
| Common examples | Calculations and simple assignments | Network requests and timers |
| Error handling | try/catch |
Promises and try/catch with async/await |
Terms to remember
- Call stack = the place where JavaScript tracks running functions.
- Callback = a function passed to run later.
- Promise = an object representing a future result.
- Event loop = the mechanism that coordinates queued JavaScript work.
- Microtask = a queued task with priority after the current stack.
- Task queue = a queue that holds scheduled callback tasks.
4. How JavaScript Handles Asynchronous Work
JavaScript runs your code on a call stack. The browser provides APIs for timers and network operations.
When an asynchronous operation finishes, its callback is queued. The event loop schedules queued work when the call stack is clear.
The highlighted stages show code execution, browser work, queueing and callback execution.
Execution flow
- Call stack: JavaScript runs the current function.
- Browser API: The browser handles supported asynchronous operations.
- Queue: Completed callbacks wait for their turn.
- Event loop: It checks whether the call stack is empty.
- Callback: The queued function runs when the stack is available.
5. Synchronous Blocking vs Non-Blocking Execution
Let's compare two appointment dashboard workflows.
The first diagram shows a blocking task. The second shows a timer completing later.
The red stage represents a long task that keeps the JavaScript thread busy.
The animation follows the scheduled timer while other work continues.
6. Promises and Async/Await
Timers are useful for learning. Real applications often call APIs.
A Promise represents a result that may become available later.
Promise states:
- Pending: The operation has not finished.
- Fulfilled: The operation completed successfully.
- Rejected: The operation failed.
Using a Promise with then and catch
function getDoctorAvailability() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const doctorAvailable = true;
if (doctorAvailable) {
resolve("Doctor is available");
} else {
reject("No available doctor");
}
}, 1000);
});
}
getDoctorAvailability()
.then((message) => console.log(message))
.catch((error) => console.error(error));
Doctor is available
Using async and await
async makes a function return a Promise. await waits for a Promise inside that function.
It makes asynchronous code easier to read. It does not block the browser's main thread while the Promise is pending.
function getDoctorAvailability() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Doctor is available");
}, 1000);
});
}
async function bookAppointment() {
console.log("Checking availability...");
try {
const result = await getDoctorAvailability();
console.log(result);
console.log("Appointment can continue");
} catch (error) {
console.error(error);
}
}
bookAppointment();
console.log("Dashboard remains available");
Checking availability...
Dashboard remains available
Doctor is available
Appointment can continue
await pauses that async function. It does not pause all JavaScript execution. Other work can continue while the Promise is pending.7. Microtasks and the Task Queue
JavaScript uses different queues for scheduled work.
Promise callbacks use the microtask queue. Timer callbacks use the task queue.
After the current call stack finishes, microtasks are processed before the next task.
console.log("1. Start");
setTimeout(() => {
console.log("4. Timer callback");
}, 0);
Promise.resolve().then(() => {
console.log("3. Promise callback");
});
console.log("2. End");
1. Start
2. End
3. Promise callback
4. Timer callback
Why does the Promise callback run before the timer callback?
- The current synchronous code runs first.
- The Promise callback enters the microtask queue.
- The timer callback enters the task queue when ready.
- The event loop processes microtasks before the next task.
8. Common Mistakes and Best Practices
Mistake 1: Assuming setTimeout runs immediately
Wrong: A zero delay does not mean immediate execution.
setTimeout(() => {
console.log("Timer finished");
}, 0);
console.log("Current code finished");
Better: Expect the callback to run after the current stack clears.
Mistake 2: Forgetting to await a Promise
Wrong: This logs a Promise instead of its resolved value.
const result = getDoctorAvailability();
console.log(result);
Better: Use await inside an async function.
const result = await getDoctorAvailability();
console.log(result);
Mistake 3: Ignoring rejected Promises
Wrong: An unhandled rejection can hide important failures.
Better: Handle failures using catch or try/catch.
Mistake 4: Running long calculations on the main thread
Asynchronous timers do not make CPU-heavy JavaScript calculations faster.
Use Web Workers for suitable heavy calculations. Workers run JavaScript separately from the page's main thread.
Best practices
- Use synchronous code for short, immediate calculations.
- Use asynchronous operations for network requests and timers.
- Use async/await when it improves readability.
- Handle errors from every important asynchronous operation.
- Use Promise.all when independent operations can run together.
- Use cancellation, such as AbortController, when requests may become unnecessary.
- Keep long-running CPU work away from the main thread when possible.
9. Real-World Example: Loading Multiple Hospital Details
A dashboard may need doctor, patient and appointment details.
These requests can run together when they do not depend on each other.
async function loadDashboard() {
try {
const [doctors, patients, appointments] =
await Promise.all([
fetch("/api/doctors").then(response => response.json()),
fetch("/api/patients").then(response => response.json()),
fetch("/api/appointments").then(response => response.json())
]);
console.log(doctors);
console.log(patients);
console.log(appointments);
} catch (error) {
console.error("Dashboard loading failed:", error);
}
}
loadDashboard();
This example assumes the three API endpoints exist. Each response must be successful JSON data.
fetch() does not reject for HTTP error statuses such as 404 or 500. Check response.ok before reading the response body.Promise.all() rejects when any input Promise rejects. Use Promise.allSettled() when you need every result, including failures.
10. Interview Questions
1. What is the difference between synchronous and asynchronous JavaScript?
Answer: Synchronous code runs in sequence. Each operation finishes before the next statement runs. Asynchronous code allows other work to continue while an operation waits. Promises and async/await help us manage asynchronous results.
2. Is JavaScript synchronous or asynchronous?
Answer: JavaScript executes synchronous code on its call stack. It also supports asynchronous operations through the runtime environment. The event loop coordinates queued callbacks with the call stack.
3. Does async/await make JavaScript multithreaded?
Answer: No. Async/await does not create another JavaScript thread. It makes Promise-based code easier to write. The runtime handles supported asynchronous operations.
4. What is the event loop?
Answer: The event loop checks whether the call stack is clear. It then schedules queued callbacks for execution. Promise microtasks are processed before the next task.
5. What is the difference between Promise.all and Promise.allSettled?
Answer: Promise.all rejects when any input Promise rejects. Promise.allSettled waits until every input Promise settles. It returns each operation's result or failure.
11. Hands-On Practice
Try these exercises using the hospital appointment example.
- Print three patient names using synchronous functions.
- Use setTimeout to show a delayed doctor availability response.
- Convert the timer example into a Promise.
- Rewrite the Promise example using async/await.
- Run two independent API requests using Promise.all.
- Print synchronous, Promise and timer messages in execution order.
12. Final Takeaway
Synchronous JavaScript is useful for short operations that finish quickly. Asynchronous JavaScript helps applications handle waiting without blocking the main flow.
Understand the call stack, queues and event loop first. Then practise callbacks, Promises and async/await with real examples.
Learn Technology. Build Your Future.
Quality Technology Education. Completely Free.
This is a fantastic explanation of synchronous vs. asynchronous JavaScript! The UPI analogy makes a notoriously tricky concept very easy to grasp.
To make the article technically complete and truly stand out for interview prep, I highly recommend adding these technical details and code examples:
Explain the Call Stack & Task Queue: Briefly mention that synchronous code runs on the Call Stack, while async tasks wait in the Callback Queue. Define the Event Loop's actual job: checking if the Call Stack is empty before pushing the next callback.
Add the "Zero-Delay" Trick: Show a code example with setTimeout(..., 0). It perfectly proves to beginners that even with zero delay, the async task still waits for the synchronous code to finish completely.
Include a Modern Promise Example: Since modern JavaScript relies on Promises and async/await, provide a quick fetch() API example to show how developers actually handle network requests today, rather than just using setTimeout.
Mention Microtasks vs. Macrotasks: This is a classic interview question! Explain that there are two queues: the Microtask Queue (for Promises, which gets higher priority) and the Macrotask Queue (for setTimeout).
Adding these technical deep-dives will turn this from a great beginner introduction into a top-tier, production-ready guide!