Shashi Bhushan KumarWhy does JavaScript need async code if it runs on a single thread? JavaScript runs on a...
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:
When the rice is ready, you come back.
π This is exactly how async code works.
If JavaScript was NOT async:
Just like:
Standing in the kitchen and doing nothing while food cooks.
Async code tells JavaScript:
"Start this long task,
donβt wait here,
I will handle the result later."
So JavaScript can:
## 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.
Which one confused you more when you started learning JavaScript?
π Callback
π Promise