Synchronous vs Asynchronous JavaScript

JavaScript executes code line by line. Some tasks finish instantly, while others take time, like fetching data from an API or waiting for a timer. This is where synchronous and asynchronous behavior becomes important.
Synchronous code runs one step at a time in order. JavaScript waits for the current task to finish before moving to the next one.
console.log("Start");
console.log("Process");
console.log("End");
Output:
Start
Process
End
The execution is simple and predictable.
Now imagine a task that takes 5 seconds. In synchronous programming, everything after it must wait.
console.log("Start");
function waitFiveSeconds() {
const start = Date.now();
while (Date.now() - start < 5000) {}
}
waitFiveSeconds();
console.log("End");
Here, the program freezes for 5 seconds before printing "End". This is called blocking code because other operations cannot continue until the task is complete.
Blocking becomes a serious problem in web applications. Users do not want the entire page to freeze while waiting for data.
That is why JavaScript uses asynchronous behaviour.
Asynchronous code allows long tasks to run in the background while JavaScript continues executing other code.
console.log("Start");
setTimeout(() => {
console.log("Task Completed");
}, 2000);
console.log("End");
Output:
Start
End
Task Completed
Even though the timer takes 2 seconds, JavaScript does not stop the entire program. This is called 'non-blocking behaviour'.
A common real-world example is API calls.
console.log("Fetching data...");
fetch("https://api.example.com/data")
.then((response) => response.json())
.then((data) => {
console.log(data);
});
console.log("Other code running...");
Fetching data may take time depending on the internet speed, but JavaScript keeps running the remaining code.
You can think of asynchronous programming like ordering food in a restaurant. After placing the order, you do not stand inside the kitchen waiting. You continue talking with friends while the food is prepared in the background.
This non-blocking behaviour is one of the main reasons JavaScript can build fast and interactive web applications.



