Sobes.tech
Middle+

In what order will console.log be output and why? Explain the order of execution of synchronous and asynchronous code (Event Loop, macro- and microtasks).

sobes.tech AI

Answer from AI

In JavaScript, the order of console.log output depends on whether the code is executed synchronously or asynchronously.

Event Loop is a mechanism that manages the execution of code, event handling, and asynchronous operations. It works with two main task queues:

  • Microtasks: promises, process.nextTick (Node.js), MutationObserver.
  • Macrotasks: setTimeout, setInterval, I/O, UI events.

Execution order:

  1. All synchronous code is executed.
  2. After synchronous code, all microtasks in the microtask queue are executed.
  3. Then the Event Loop takes one macrotask and executes it.
  4. After the macrotask, all microtasks are executed again.

Example:

console.log('Synchronous 1');
setTimeout(() => console.log('Macrotask (setTimeout)'), 0);
Promise.resolve().then(() => console.log('Microtask (Promise)'));
console.log('Synchronous 2');

The output will be:

Synchronous 1
Synchronous 2
Microtask (Promise)
Macrotask (setTimeout)

Because first all synchronous code runs, then microtasks, then macrotasks.

Thus, console.log in synchronous code will output immediately, while in asynchronous code, it depends on the task type and queue.

In what order will console.log be output and why… - sobes.tech