Problem Statement
What is the output order? console.log('1'); setTimeout(() => console.log('2'), 0); Promise.resolve().then(() => console.log('3')); console.log('4');
Explanation
The output is 1, 4, 3, 2 because of how the event loop works.
JavaScript executes synchronous code first. So 1 and 4 print immediately.
Promises are microtasks and have higher priority than setTimeout which is a macrotask.
Microtasks run after the current script but before macrotasks. So 3 prints before 2.
Understanding the event loop, microtasks, and macrotasks is crucial for advanced JavaScript.
This is a very common and important interview question.
Code Solution
SolutionRead Only
console.log('1'); // Synchronous - runs immediately
setTimeout(() => console.log('2'), 0); // Macrotask - queued
Promise.resolve().then(() => console.log('3')); // Microtask - queued
console.log('4'); // Synchronous - runs immediately
// Execution order:
// 1. Run all synchronous code: 1, 4
// 2. Run microtasks: 3
// 3. Run macrotasks: 2
// Output: 1, 4, 3, 2
// More complex example
console.log('Start');
setTimeout(() => {
console.log('Timeout 1');
Promise.resolve().then(() => console.log('Promise in timeout'));
}, 0);
Promise.resolve()
.then(() => {
console.log('Promise 1');
return Promise.resolve();
})
.then(() => console.log('Promise 2'));
setTimeout(() => console.log('Timeout 2'), 0);
console.log('End');
// Output:
// Start
// End
// Promise 1
// Promise 2
// Timeout 1
// Promise in timeout
// Timeout 2
// Event Loop Summary:
// 1. Synchronous code runs first
// 2. Microtasks (Promises, queueMicrotask)
// 3. Macrotasks (setTimeout, setInterval, I/O)