← JavaScript

Asynchrony

What is the difference between synchronous and asynchronous code in JavaScript?

Show answer — try answering out loud first

Synchronous code runs line by line, blocking until each line finishes. Asynchronous code lets you launch a task that takes time (like a network request or a timer) and keep running the rest of the code without waiting; the result is handled later.

JavaScript is single-threaded: it does one thing at a time. If everything were synchronous, a slow task (like fetching data from a server) would freeze the entire page until it finished.

To avoid that, JavaScript uses asynchronous code: it starts the slow task, delegates it, and keeps running everything else. When the task completes, its result is handled through a callback, a promise, or async/await.

  • Synchronous: "I'll stand here waiting until you finish."
  • Asynchronous: "Start the task and let me know when you're done; meanwhile, I'll keep going with my own thing."
// SYNCHRONOUS: runs in order, line by line
console.log("1");
console.log("2");
console.log("3");
// Output: 1, 2, 3

// ASYNCHRONOUS: setTimeout doesn't block
console.log("A");
setTimeout(() => {
  console.log("B"); // runs later, even with a delay of 0
}, 0);
console.log("C");
// Output: A, C, B
// "B" appears last because setTimeout is asynchronous:
// the synchronous code runs first.

Assuming that setTimeout(fn, 0) runs the function immediately. Even with a delay of 0, the function is placed in a queue and only runs when the current synchronous code has finished. That's why "B" appears after "C".

"JavaScript is single-threaded, so it runs one thing at a time. Synchronous code runs line by line and blocks until each line finishes. Asynchronous code lets me launch a task that takes time, like a server request, and keep going with the rest of my code without waiting around; when the task finishes, I handle the result with callbacks, promises, or async/await. This keeps the app from freezing while it waits for slow operations."

Quick challenge

In what order are the words printed?

console.log("inicio");
setTimeout(() => console.log("timeout"), 0);
console.log("fin");
See answer

inicio, fin, timeout. The synchronous code (inicio and fin) runs first; the setTimeout callback is asynchronous and runs last, even with a delay of 0.