[object Object],[object Object]

FE Interview Question - Guess the output I

// Start here
const promise = new Promise((resolve) => {
  console.log(1);
  resolve();
  console.log(2);
});

console.log(3);
console.log(4);

setTimeout(() => {
  console.log(5);
}, 100);

setTimeout(() => {
  console.log(6);
}, 0);
promise.then(() => {
  console.log(7);
});

console.log(8);

The output of the code will be:

// Start here
1
2
3
4
8
7
6
5

Explanation:

  • The console.log(1) and console.log(2) statements are executed synchronously when the Promise is created.
  • The console.log(3) and console.log(4) statements are executed next.
  • The console.log(8) statement is executed after the Promise is created.
  • The promise.then() method is called and the callback function is added to the microtask queue.
  • The first setTimeout() function is added to the task queue and will execute after 100ms.
  • The second setTimeout() function is added to the task queue and will execute after 0ms (but only after the microtask queue is cleared).
  • Finally, the microtask queue is cleared and the callback function in promise.then() is executed, logging 7.
  • The second setTimeout() function then executes, logging 6, followed by the first setTimeout() function which logs 5.

← Go home