Skip to main content

Command Palette

Search for a command to run...

Synchronous vs Asynchronous JavaScript

Published
3 min read
Synchronous vs Asynchronous JavaScript

When we write JavaScript most of the time code runs line by line.

One step after another.

Simple.

But in real apps things do not always happen instantly.

Sometimes you have to wait:

  • fetching data from API

  • loading files

  • timers

So what happens then?

Does JavaScript just stop and wait?

No.

That is where synchronous and asynchronous behavior comes in.

In this blog I will share how I understand sync vs async in JavaScript.


What synchronous code means

Synchronous means:

one thing at a time

Code runs step by step.

Example:

console.log("Start")
console.log("Middle")
console.log("End")

Output:

Start
Middle
End

each line waits for previous one


How it feels

Straight line execution


What asynchronous code means

Asynchronous means:

do not wait move ahead

Example:

console.log("Start")

setTimeout(() => {
  console.log("Inside timeout")
}, 2000)

console.log("End")

Output:

Start
End
Inside timeout

Even though timeout is in middle it runs later


Why JavaScript needs async

Imagine this:

You call an API that takes 5 seconds.

If JavaScript waits:

everything freezes

  • UI stuck

  • buttons not working

  • bad experience

So instead JavaScript says:

I will start this task and continue other work


Real life example

Think like ordering food:

Synchronous:

order → wait → get food → then do next thing

Asynchronous:

order → do other work → get food later


Blocking vs non blocking

Synchronous:

blocking

It waits.

Asynchronous:

non blocking

It continues.


Problem with blocking code

Let us look at this:

console.log("Start")

setTimeout(() => {
  console.log("Waited 3 seconds")
}, 3000)

console.log("End")

Output:

Start
End
Waited 3 seconds

Now imagine if JavaScript waited for this like synchronous code:

Start
(wait 3 seconds)
Waited 3 seconds
End

everything would pause

nothing else would run

app would feel stuck


Async flow

When async task happens:

JavaScript sends it to background

continues execution

later runs the function


Async mental model

Diagram idea:


Simple async example

setTimeout(() => {
  console.log("Done")
}, 1000)

runs after delay


Where you see async

  • API calls

  • database queries

  • timers

  • file operations


Why this matters

Without async:

apps would freeze

With async:

smooth experience


Quick comparison

Synchronous:

  • step by step

  • blocking

Asynchronous:

  • runs in background

  • non blocking


JavaScript is single threaded.

So it cannot do everything at once.

Async is how it handles waiting tasks without stopping everything.