Middle
What will be the output of the following code? ```javascript console.log(1); setTimeout(() => { console.log(2); }, 0); Promise.resolve().then(() => { console.log(3); }); console.log(4); setTimeout(() => { Promise.resolve().then(() => { console.log(5); }); }, 0); ```
sobes.tech AI
Answer from AI
The output will be:
1
4
3
2
5
Explanation of the output order:
console.log(1);— synchronous call, outputs1.setTimeout(..., 0)— places the callback in the macro task queue, executed later.Promise.resolve().then(...)— places the callback in the micro task queue, which executes after the current stack but before macro tasks.console.log(4);— synchronous call, outputs4.
After the synchronous code finishes:
- Microtasks are executed:
console.log(3); - Then macro tasks from
setTimeout: firstconsole.log(2); - The second
setTimeoutcallsPromise.resolve().then(...), which places a microtask that executesconsole.log(5);after the current macro task.
Thus, the order is: 1, 4, 3, 2, 5.