Programs & Examples
JavaScript Output Questions · Study material
A mixed puzzle, step by step
Promise.resolve(counter.inc()) calls inc() immediately (count = 1, the value is 1); the log on the next line makes it 2. Then the microtask prints 1 + "1" = "11", and finally the timer makes it 3:
// A typical interview puzzle combining scope, closures, coercion and the event loop
var label = "global";
const counter = (() => {
let count = 0;
return { inc: () => ++count, label: "counter" };
})();
setTimeout(() => console.log("D:", counter.inc()), 0);
Promise.resolve(counter.inc()).then((v) => console.log("C:", v + "1"));
console.log("A:", counter.inc());
console.log("B:", typeof label, counter.label);
A: 2 B: string counter C: 11 D: 3