HomeJAVASCRIPTDifference between synchronous and asynchronous code.

Difference between synchronous and asynchronous code.

Here’s a clear breakdown of synchronous vs asynchronous code in programming, especially in JavaScript:


1. Synchronous Code

  • Definition: Code that executes line by line, one after the other. Each operation must finish before the next one starts.
  • Behavior: Blocks further execution until the current task completes.
  • Analogy: Waiting in a queue at a bank—one person is served at a time.

Example in JS:

console.log("Start");

function waitThreeSeconds() {
  const start = Date.now();
  while (Date.now() - start < 3000) {
    // Blocking loop for 3 seconds
  }
  console.log("Finished waiting");
}

waitThreeSeconds();
console.log("End");

Output:

Start
Finished waiting
End

Notice how “End” waits until the 3-second function finishes.


2. Asynchronous Code

  • Definition: Code that can start a task and move on without waiting for it to finish. Completion is handled later (via callbacks, promises, or async/await).
  • Behavior: Non-blocking; other code continues to run.
  • Analogy: Ordering food at a restaurant and reading a book while waiting—when the food is ready, you’re notified.

Example in JS (setTimeout):

console.log("Start");

setTimeout(() => {
  console.log("Finished waiting");
}, 3000);

console.log("End");

Output:

Start
End
Finished waiting

Notice “End” prints before the waiting task completes.


Key Differences

AspectSynchronousAsynchronous
ExecutionOne after anotherCan run concurrently
BlockingYesNo
Example tasksCalculations, loopsAPI calls, timers, file reads
JavaScript handlingNormal function callsCallbacks, Promises, async/await
Flow controlEasy to reason aboutRequires event-driven thinking

💡 Tip:
Use synchronous code for tasks that must happen in order, and asynchronous code for tasks that take time (like network requests) to avoid freezing the program.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *