Why does JavaScript need async code if it runs on a single thread?

# webdev# programming# javascript# beginners
Why does JavaScript need async code if it runs on a single thread?Shashi Bhushan Kumar

Why does JavaScript need async code if it runs on a single thread? JavaScript runs on a...

Why does JavaScript need async code if it runs on a single thread?

JavaScript runs on a single thread.

This means it can do only one task at a time.

So a common question is:

If JavaScript can do only one thing at a time, why do we need async code?

The simple answer is:
To avoid waiting and freezing.

## Real-life example (Very easy)

Imagine you are alone at home.
You put rice on the gas stove.
Cooking rice takes 20 minutes.

Now think:
Do you stand in the kitchen and stare at the stove for 20 minutes?

No.
Instead, you:

  • Put the rice on the stove
  • Let it cook
  • Do other things (use phone, clean room, drink water)

When the rice is ready, you come back.

πŸ‘‰ This is exactly how async code works.

What would happen without async code?

If JavaScript was NOT async:

  • It would start a long task (like loading data from the internet)
  • It would wait there doing nothing
  • During that time:
    • Buttons would not work
    • Page would feel frozen
    • User would get frustrated

Just like:
Standing in the kitchen and doing nothing while food cooks.

What async code actually does

Async code tells JavaScript:

"Start this long task,

don’t wait here,

I will handle the result later."

So JavaScript can:

  • Start a task
  • Continue doing other work
  • Come back when the task is finished

## Simple technical example

console.log("Start");

setTimeout(() => {
console.log("Cooking finished");
}, 2000);

console.log("Doing other work");

Output:
Start
Doing other work
Cooking finished

Over All Summary:

JavaScript needs async code so it does not sit idle while waiting for slow tasks.

Promise vs Callback – What is the difference?

Which one confused you more when you started learning JavaScript?
πŸ‘‰ Callback
πŸ‘‰ Promise