What is the difference between synchronous and asynchronous code?
The difference is whether code waits for a task to finish before moving on.
Synchronous — runs line by line; each step blocks the next until it completes.
Asynchronous — starts a task and continues; a callback, Promise, or await handles the result later.
Why it matters: JavaScript is single-threaded, so async keeps the UI responsive during slow work like network requests.
// Synchronous — blocks until complete
console.log('1');
const data = heavyComputation(); // Blocks everything!
console.log('2');
// Output: 1, (wait...), 2 — sequential
// Asynchronous — does not block
console.log('1');
setTimeout(() => console.log('2'), 1000); // Schedules for later
console.log('3');
// Output: 1, 3, 2 — 3 runs before 2!
// Async/await — looks sync, runs async
async function loadData() {
console.log('Start');
const data = await fetch('/api/data'); // Non-blocking wait
console.log('Data loaded');
// Other code can run during the await
}
// Parallel async
const [users, posts] = await Promise.all([
fetch('/api/users'),
fetch('/api/posts')
]); // Both run concurrentlySynchronous: 1 then computation then 2 (sequential, blocking). Asynchronous: 1, 3, then 2 (setTimeout schedules for later, 3 runs immediately). async/await: looks synchronous but does not block — other code can run during the await.
Promise.all enables parallel execution.
Sync = blocking (one at a time). Async = non-blocking (continue while waiting).
The setTimeout example (1, 3, 2 ordering) demonstrates async behavior. async/await makes async code LOOK synchronous but is NOT blocking. Promise.all for parallel operations.