Synchronous vs Asynchronous JavaScript
Synchronous code runs line by line, one after another.
Each line waits for the previous one to finish.
console.log("one");
console.log("two");
console.log("three");
Output:
one
two
three
Execution happens in order, step by step.
What Asynchronous Code Means
Asynchronous code does not wait for a task to finish.
It allows other code to run while waiting.
console.log("one");
setTimeout(() => {
console.log("two");
}, 1000);
console.log("three");
Output:
one
three
two
The delayed task runs later, without blocking the rest of the code.
Why JavaScript Needs Asynchronous Behavior
JavaScript runs on a single thread.
This means:
- It can do one thing at a time
If everything was synchronous:
- long tasks would block the entire program
Asynchronous behavior allows JavaScript to:
handle tasks like API calls, timers, file reading
without freezing execution
Examples (API Calls, Timers)
Timer Example
setTimeout(() => {
console.log("after 2 seconds");
}, 2000);
API Call Example
fetch("https://api.example.com/data")
.then(res => res.json())
.then(data => console.log(data));
These operations take time, so they run asynchronously.
Problems with Blocking Code
Blocking code stops everything until it finishes.
Example:
function heavyTask() {
for (let i = 0; i < 1e9; i++) {}
}
console.log("start");
heavyTask();
console.log("end");
Output:
start
(wait...)
end
Problems:
UI freezes (in browser)
delays everything else
poor user experience