How does JavaScript event loop work?

Asked by Robert Brown Feb 24, 2025 advanced 1519 views
98

I'm trying to understand the JavaScript event loop. I know JavaScript is single-threaded, but how does async code work then?

Can someone explain:

  1. What is the call stack?
  2. What is the task queue?
  3. What is the microtask queue?
  4. How do they all work together?

This code confuses me:

console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');

Why does it print 1, 4, 3, 2?

Solutions

0 answers

No solutions yet

Be the first to help solve this problem!