Understanding the order of execution in JavaScript is critical when orchestrating async operations.

Task Queues Breakdown

  1. Call Stack: Executes synchronous operations until empty.
  2. Microtask Queue: Resolved promises (Promise.then), queueMicrotask, and MutationObserver. Emptied completely after each stack frame.
  3. Macrotask Queue: setTimeout, setInterval, setImmediate, and I/O. Executed one per tick.
console.log('1')
setTimeout(() => console.log('2'), 0)
Promise.resolve().then(() => console.log('3'))
console.log('4')

// Output: 1, 4, 3, 2