Sync vs Async
Overview
JavaScript is inherently Single-Threaded and Synchronous. This means it can only execute one line of code at a time, top to bottom. If a line of code takes 5 seconds to run, the entire application (and the browser tab) freezes for 5 seconds.
Asynchronous (Async) JavaScript allows the engine to initiate a slow task (like fetching data from a database), set it aside, and continue running the rest of the code. Once the slow task finishes, the engine comes back to it.
Syntax
console.log("1. Start");
// Imagine this takes 3 seconds to run
expensiveMathCalculation();
// This won't print until the math is completely finished
console.log("2. End");console.log("1. Start");
// Starts the timer, but DOES NOT WAIT! It moves to the next line.
setTimeout(() => {
console.log("2. Timer Finished");
}, 2000);
// This prints BEFORE the timer finishes!
console.log("3. End");
// Output:
// 1. Start
// 3. End
// 2. Timer FinishedCommon Pitfalls
- Believing that JavaScript itself is multi-threaded. It is not. Asynchronous operations are handed off to the Web Browser's internal APIs (like the Network module or the Timer module). The browser does the waiting in the background, and pushes the result back into JS when it's done via the 'Event Loop'.
Interview Questions
The Event Loop is a mechanism that continuously monitors the Call Stack and the Callback Queue. If the Call Stack is empty (all synchronous code is done), the Event Loop pushes the next waiting asynchronous callback from the Queue onto the Stack to be executed.
Real-World Example
Fetching a large user profile image from an AWS server. If this was synchronous, the user couldn't scroll or click anything on the page until the image fully downloaded.
fetch(imageUrl).then(renderImage);Check Your Knowledge
Test your understanding of Sync vs Async with these quick questions.