Sobes.tech
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:

  1. console.log(1); — synchronous call, outputs 1.
  2. setTimeout(..., 0) — places the callback in the macro task queue, executed later.
  3. Promise.resolve().then(...) — places the callback in the micro task queue, which executes after the current stack but before macro tasks.
  4. console.log(4); — synchronous call, outputs 4.

After the synchronous code finishes:

  • Microtasks are executed: console.log(3);
  • Then macro tasks from setTimeout: first console.log(2);
  • The second setTimeout calls Promise.resolve().then(...), which places a microtask that executes console.log(5); after the current macro task.

Thus, the order is: 1, 4, 3, 2, 5.