In JavaScript, understanding the difference between synchronous and asynchronous code is essential for writing efficient and responsive programs—especially in web development.
Synchronous Code
Synchronous code is executed line by line, in order. Each operation waits for the previous one to complete before it runs.
console.log("Start");
console.log("Processing...");
console.log("End");
Output:
Start
Processing...
End
Here, each line runs only after the previous one finishes. This is simple to understand but can cause problems if a long-running operation blocks the code—for example, file access or network requests.
Asynchronous Code
Asynchronous code allows certain tasks to run in the background without blocking the rest of the code. This is commonly used with timers, network requests, or reading files.
console.log("Start");
setTimeout(() => {
console.log("Fetching data...");
}, 1000);
console.log("End");
Output:
Start
End
Fetching data...
The setTimeout function runs the callback after 1 second, but JavaScript doesn’t wait—it continues running the rest of the code.
Why It Matters
- Synchronous code is easier to write but can block execution.
- Asynchronous code helps avoid freezing the UI in web apps.
Common Asynchronous Techniques
setTimeout/setInterval- Promises
- async/await
- AJAX and Fetch API calls
Example Using Promises
console.log("Start");
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log("Data received:", data));
console.log("End");
This keeps your app responsive while waiting for the network response.
Conclusion
Synchronous code runs step by step and is simple but can block the program. Asynchronous code helps manage delays like network or timer events without freezing the app. Understanding both is key to writing efficient JavaScript.
Post a Comment