What gets logged 2?
Medium
Prompt
What gets logged when the following code is executed?
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');
Solution
The output of the code is 1, 4, 3, 2
.
This output is a classic example of how the JavaScript event loop works, prioritizing different types of tasks. Here's a breakdown of the execution flow:
console.log('1');
- This is a synchronous task. It gets executed immediately, and '1' is printed to the console.
setTimeout(() => console.log('2'), 0);
- setTimeout is a Web API function, making it asynchronous.
- Even with a delay of 0 milliseconds, its callback function (() => console.log('2')) is not executed right away. Instead, it's placed in the macrotask queue (or task queue) to be run later.
Promise.resolve().then(() => console.log('3'));
- Promises are also asynchronous. The .then() callback (() => console.log('3')) is placed in the microtask queue.
console.log('4');
- This is another synchronous task, so it executes immediately, and '4' is printed to the console.
The Event Loop in Action
After all the synchronous code in the main script has run, the JavaScript engine checks the task queues. The rule is: the microtask queue is always processed before the macrotask queue.
- Microtask Queue: The event loop checks the microtask queue and finds the promise's
.then()
callback. It executes this task, printing3
. - Macrotask Queue: After the microtask queue is empty, the event loop moves to the macrotask queue. It finds the
setTimeout
callback and executes it, printing2
.
This specific order of operations—synchronous code, then microtasks, then macrotasks—is what leads to the final output: 1, 4, 3, 2
.
00:00