SmartCodingTips

🔄 Synchronous vs Asynchronous JavaScript

JavaScript is single-threaded — it runs code line-by-line in a single sequence. But thanks to asynchronous features, it can perform non-blocking operations (like fetching data or timers).

⏱️ What is Synchronous Code?

Synchronous code runs line-by-line. One operation must finish before the next begins.

console.log("1");
console.log("2");
console.log("3");
// Output: 1, 2, 3

🚦 What is Asynchronous Code?

Asynchronous code allows tasks to run in the background while the rest of the code continues.

console.log("1");

setTimeout(() => {
  console.log("2");
}, 2000);

console.log("3");
// Output: 1, 3, (then after 2 sec) 2

🧠 Why Use Asynchronous Code?

  • Fetching data from a server
  • Waiting for user input
  • Running animations or delays

🛠️ Common Asynchronous Tools

  • setTimeout and setInterval
  • fetch() for API calls
  • Promises and async/await
  • Event listeners
💡 Tip: Asynchronous programming helps you write non-blocking code, improving performance and user experience.