Synchronous vs Asynchronous JavaScript
CSE Under grad. || Trying to be a better developer each day || Consistency is the key
Synchronous JavaScript
Synchronous code runs line by line. Each statement waits for the previous one to finish before executing.
js
console.log("First");
console.log("Second");
console.log("Third");
It’s simple but can be problematic when tasks take time.
Asynchronous JavaScript
Asynchronous code does not wait. It starts a task and immediately moves to the next line.
js
console.log("First");
setTimeout(() => {
console.log("Second");
}, 2000);
console.log("Third");
Why Asynchronous MattersJavaScript is single-threaded. If it waited for slow operations like API calls, file reading, or database queries, the entire app would freeze.Asynchronous code keeps the application responsive by not blocking the main thread.
Real Example:
When you fetch data from an API, you don’t want your website to freeze while waiting for the response.Summary
Synchronous = Wait and execute (Blocking)
Asynchronous = Start task and continue (Non-blocking)