Synchronous vs Asynchronous JavaScript
Understanding how JavaScript executes code is key to writing efficient, responsive applications. Let's explore the difference between Synchronous and Asynchronous behavior in JavaScript.
1. What is Synchronous JavaScript?
Synchronous code runs line-by-line, and each operation waits for the previous one to complete before continuing.
Example:
console.log("Start");
console.log("Processing...");
console.log("End");
Output
Start
Processing...
End
Processing...
End
Everything executes in order—no skipping or delays.
2. What is Asynchronous JavaScript?
Asynchronous code doesn't block the execution. It allows other code to run while waiting for operations like API calls, timeouts, or file loading.
Example with setTimeout():
console.log("Start");
setTimeout(() => {
console.log("Async Task Complete");
}, 2000);
console.log("End");
Output
Start
End
Async Task Complete ← after 2 seconds
End
Async Task Complete ← after 2 seconds
The rest of the code continues running while waiting for the asynchronous task.
Common Asynchronous Features in JavaScript
Feature | Description |
---|---|
setTimeout() | Run a task after a delay |
setInterval() | Run repeatedly at intervals |
AJAX / Fetch | Get data from APIs without blocking |
Promises | Handle async operations with cleaner syntax |
Async/Await | Write async code like it's synchronous |
Event Listeners | Handle events like clicks or keyboard input |
Real-World Use Case
Synchronous:
let result = calculateSum(5, 10); // Waits for result
console.log(result);
Asynchronous:
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data)); // Doesn't block other code
Key Differences
Feature | Synchronous | Asynchronous |
---|---|---|
Execution | One task at a time (blocking) | Non-blocking, multiple at once |
Performance | Slower, can freeze UI | Faster, smooth user experience |
Examples | Loops, functions, math | API calls, timers, fetch |
Use Cases | Small tasks, calculations | Network requests, UI updates, loading |