Middle
Order the sequence of console.log calls: arrange the order of log outputs (part 1 — synchronous code, part 2 — with asynchronous code, promises, and setTimeout).
sobes.tech AI
Answer from AI
Let's consider the order of output for console.log in two parts:
Part 1 — Synchronous code
All console.log statements are executed sequentially in the order they are written.
console.log('1');
console.log('2');
console.log('3');
// Output: 1, 2, 3
Part 2 — With asynchronous code, promises, and setTimeout
Example:
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');
Output order:
'1'— synchronous code'4'— synchronous code'3'— microtask (promise) after synchronous code'2'— macrotask (setTimeout) after microtasks
Result: 1, 4, 3, 2
This is because microtasks (promises) are executed immediately after the current call stack, while macrotasks (setTimeout) are executed later.