Synchronous vs Asynchronous JavaScript
Knowing how the code operates, particularly the distinction between synchronous and asynchronous execution, is crucial when working with JavaScript. Let’s simplify it using relatable examples.
What is Synchronous?
Line by line, synchronous code runs in a sequential fashion.Before proceeding to the next task, each one must be finished.
An example:
Let’s say a user completes a website form. The browser begins examining each field individually as soon as they click the “Submit” button: Name → OK
Email → All right
Phone Number → All right
Until all checks are finished, nothing else can happen on the page.
Code Example
console.log(“Validating form…”);
function validateForm() {
for (let i = 0; i < 1e9; i++) {
// Simulate heavy validation (e.g., complex calculations)
}
console.log(“Form is valid.”);
}
validateForm();
console.log(“Form submitted.”);
Output:
Start
Long task finished
End
What is Asynchronous?
Because JavaScript is asynchronous, it can start a task and move on to the next line without waiting for it to finish.
An example:
Modern apps often send data to the server and show a loading spinner so that the user can interact with the page while waiting.
Code Example:
console.log(“Submitting form…”);
setTimeout(() => {
console.log(“Server responded: Form saved successfully.”);
}, 2000); // Simulates network delay
console.log(“Showing loading spinner…”);
Output:
Submitting form…
Showing loading spinner…
Server responded: Form saved successfully.
When to Use Asynchronous Code?
When a task requires a lot of time, use async code, like:
- Fetching data from an API
- Awaiting user input (such as button presses)
- Reading files
- Timers or delays
An example Using fetch (Asynchronous)
console.log(“Start”);
fetch(“https://jsonplaceholder.typicode.com/posts/1”)
.then(response => response.json())
.then(data => console.log(“Post:”, data.title));
console.log(“End”);
Output:
Start
End
Post: sunt aut facere repellat provident occaecati…
JavaScript does not wait for the data, despite the fetch call being above console.log(“End”). While the data is loading, it continues to run.
Conclusion
Understanding the difference:
Concept | Explanation |
Synchronous | Wait your turn — step-by-step |
Asynchronous | Do other things while waiting |
JavaScript may run on a single thread, but with asynchronous code, it feels like it’s multitasking.