In JavaScript, what is the difference between synchronous and asynchronous code?
Asked on Jul 12, 2024
Answer
Synchronous code in JavaScript runs sequentially, blocking the execution of subsequent code until the current operation completes, while asynchronous code allows other operations to run before the current one completes, enabling non-blocking behavior.
<!-- BEGIN COPY / PASTE -->
// Synchronous example
console.log("Start");
console.log("Middle");
console.log("End");
// Asynchronous example
console.log("Start");
setTimeout(() => {
console.log("Middle");
}, 1000);
console.log("End");
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with JavaScript best practices.- In the synchronous example, "Start", "Middle", and "End" are logged in order.
- In the asynchronous example, "Start" and "End" are logged first, and "Middle" is logged after a 1-second delay due to the setTimeout function.
- Asynchronous code is useful for operations that take time, such as network requests, without freezing the UI or blocking other operations.
Recommended Links:
← Back to All Questions