LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
JavaScript

Synchronous vs Asynchronous JavaScript

Synchronous code runs one statement after another. Asynchronous code allows certain tasks, like timers and network requests, to finish later without blocking the remaining code.

Synchronous vs Asynchronous JavaScript: Understand How Code Executes

TL;DR: Synchronous JavaScript runs one task at a time. Each task waits for the previous task to finish. Asynchronous JavaScript lets longer operations complete without blocking the main flow. We use callbacks, promises and 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.

Example 1: Processing appointments synchronously

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");
Expected output
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?

  1. A slow task can delay the work that follows it.
  2. The browser may stop responding while long JavaScript runs.
  3. Users may experience delayed clicks, scrolling and updates.
  4. 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");
Expected output
Hospital dashboard opened
Checking doctor availability...
Dashboard is ready for other work
Doctor is available
Important: The two-second delay is only a demonstration. The browser schedules the callback. JavaScript continues executing the remaining statements first.

3. How Synchronous and Asynchronous Execution Differ

Synchronous

Wait and continue

One operation finishes before the next statement runs.

Example: Calculate a patient's age from a date.

Asynchronous

Continue while waiting

Other work can run while an operation is pending.

Example: Fetch doctor availability from a server.

Comparison of synchronous and asynchronous JavaScript
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.

A connected diagram showing JavaScript code entering the call stack, browser APIs handling asynchronous work, callbacks entering queues, and the event loop returning work to the call stack. JavaScript code Runs statements in order ● Call stack Runs current functions Browser APIs Timer or network work happens outside stack Callback queues Promise microtasks and timer tasks Event loop Checks stack and queues Callback runs When stack is available The event loop schedules queued work when the stack is clear. Simplified browser execution flow

The highlighted stages show code execution, browser work, queueing and callback execution.

Execution flow

  1. Call stack: JavaScript runs the current function.
  2. Browser API: The browser handles supported asynchronous operations.
  3. Queue: Completed callbacks wait for their turn.
  4. Event loop: It checks whether the call stack is empty.
  5. Callback: The queued function runs when the stack is available.
Remember: JavaScript does not run every asynchronous operation in parallel. The browser or runtime handles supported work. JavaScript callbacks still run on the relevant JavaScript thread.

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.

One operation blocks the next operation Start request Run JavaScript Long blocking task Main thread is busy Next task starts After blocking ends Waiting time blocks progress A long-running synchronous task delays later work.

The red stage represents a long task that keeps the JavaScript thread busy.

Other JavaScript work continues while the timer waits Start request Schedule timer Other work runs UI stays available Timer completes Callback becomes ready Callback executes When stack is clear

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

Example 3: Checking doctor availability with a Promise
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));
Expected output
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.

Example 4: Reading availability with async/await
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");
Expected output
Checking availability...
Dashboard remains available
Doctor is available
Appointment can continue
Key point: 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.

Example 5: Understanding execution order
console.log("1. Start");

setTimeout(() => {
  console.log("4. Timer callback");
}, 0);

Promise.resolve().then(() => {
  console.log("3. Promise callback");
});

console.log("2. End");
Expected output
1. Start
2. End
3. Promise callback
4. Timer callback

Why does the Promise callback run before the timer callback?

  1. The current synchronous code runs first.
  2. The Promise callback enters the microtask queue.
  3. The timer callback enters the task queue when ready.
  4. 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.

Example 6: Running independent requests together
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.

Production note: 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.

  1. Print three patient names using synchronous functions.
  2. Use setTimeout to show a delayed doctor availability response.
  3. Convert the timer example into a Promise.
  4. Rewrite the Promise example using async/await.
  5. Run two independent API requests using Promise.all.
  6. Print synchronous, Promise and timer messages in execution order.
Challenge: Predict the output before running your code. Explain why each message appears in that 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.

Upgradix by Shrash Studio
Learn Technology. Build Your Future.
Quality Technology Education. Completely Free.

Comments & Ratings (1)

Log in or create a student account to comment and rate this article.

A

Abhimanyu S

★★★★★ 11 Nov 2026

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!