learn
JavaScript

Output-prediction puzzles

Twelve classic what-logs puzzles with instant verification.

Twelve puzzles, same rules as interviews: read, commit to an answer, then reveal the real output. Every reveal runs the code — the machine grades you, not your confidence.

Puzzle 1: loop timers — guess first, then reveal.

predict.js
for (var i = 0; i < 2; i = i + 1) {
setTimeout(function () {
  console.log(i);
}, 0);
}

Puzzle 2: order of four — guess first, then reveal.

predict.js
console.log("start");
setTimeout(function () {
console.log("macro");
}, 0);
Promise.resolve().then(function () {
console.log("micro");
});
console.log("end");

Puzzle 3: borrowed method — guess first, then reveal.

predict.js
const account = {
user: "sam",
hi: function () {
  return "hi " + this.user;
},
};
const later = account.hi;
console.log(later());

Puzzle 4: use before line — guess first, then reveal.

predict.js
console.log(typeof total);
var total = 1;

Puzzle 5: minus versus plus — guess first, then reveal.

predict.js
console.log("5" - 2);
console.log("5" + 2);

Puzzle 6: independent counters — guess first, then reveal.

predict.js
function counter() {
let n = 0;
return function () {
  n = n + 1;
  return n;
};
}
const a = counter();
const b = counter();
console.log(a());
console.log(b());

Puzzle 7: chain without return — guess first, then reveal.

predict.js
Promise.resolve(10)
.then(function (n) {
  n * 2;
})
.then(function (n) {
  console.log(n);
});

Puzzle 8: async order — guess first, then reveal.

predict.js
async function f() {
console.log("f");
}
console.log("s");
f().then(function () {
console.log("t");
});
console.log("e");

Puzzle 9: empty versus false — guess first, then reveal.

predict.js
console.log([] == false);
console.log("" == false);

Puzzle 10: shared list — guess first, then reveal.

predict.js
const a = [1];
const b = a;
b.push(2);
console.log(a.length);

Puzzle 11: null check — guess first, then reveal.

predict.js
console.log(typeof null);
console.log(Array.isArray([]));

Puzzle 12: hoisted helper — guess first, then reveal.

predict.js
console.log(double(3));
function double(n) {
return n * 2;
}

Key takeaways

  • Say the order out loud before revealing: sync, microtasks, tasks.
  • Name the mechanism (shared binding, dropped receiver, forgotten return).
  • The puzzles you miss define your review list — retake them in a week.

References

On this page