Skip to main content

Command Palette

Search for a command to run...

Synchronous vs Asynchronous JavaScript

Updated
2 min read
Synchronous vs Asynchronous JavaScript
S
Software Developer | Full Stack Developer |

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

  1. API Calls
fetch("https://api.example.com/data")
  .then(res => res.json())
  .then(data => console.log(data));
  1. Timers
setTimeout(() => {
  console.log("Runs later");
}, 2000);
  1. 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:

  1. It sends async tasks (like setTimeout, fetch) to the Web APIs

  2. When done, they go to the Callback Queue

  3. 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

Debunking Fundamentals of JavaScript

Part 23 of 24

This series contains various blogs which explain the basics of javascript from scratch and give an inside working structure of the scripting language.

Up next

Async/Await in JavaScript

Writing Cleaner Asynchronous Code