JavaScript Output Questions: How to Trace Hoisting, Closures, this and the Event Loop
A JavaScript output question shows a short snippet and asks what console.log prints, or in what order several lines print. Almost every one tests one of five mechanisms: type coercion, hoisting and the temporal dead zone, closures, the value of this, and the event loop. Web Development carries 10% of the NSCT according to HEC's Areas of Competencies. It had the highest area accuracy in 2026, at 54.1%, per the HEC NSCT report and APP, but output questions are where careful tracing separates strong candidates from guessers.
The concepts themselves are explained on JavaScript Fundamentals and Advanced JavaScript. This page is pure tracing practice with new snippets. Every output shown here was produced by running the code in Node.js 26, and browsers give the same results for these snippets.
The method, step by step
- Scan for the mechanism.
+with a string means coercion;varor a function used above its line means hoisting; a function returned from a function means a closure;thisinside a callback means binding;setTimeout, promises orawaitmean the event loop. - Hoist first. Before reading line 1, list every
var(valueundefined), every function declaration (full body) and everylet/const(in the dead zone until its line runs). - Run the synchronous code top to bottom, writing each log as it happens.
- Keep two queues on paper: microtasks (promise callbacks, code after
await,queueMicrotask) and tasks (timers). When the stack empties, drain all microtasks, then take one task, then drain microtasks again. - For every
this, ask how the function was called, not where it was written. Arrow functions are the exception: they takethisfrom the surrounding code. - Check the format. Commas in
console.log(a, b)become spaces; each call prints a new line.
Type coercion
+ concatenates if either side is a string; -, * and / always convert to numbers.
console.log("3" * "4", "3" + 4 - 1, true + 1, [] + {}, null + 1);
| Expression | Step | Result |
|---|---|---|
"3" * "4" |
both become numbers | 12 |
"3" + 4 - 1 |
"34", then "34" - 1 |
33 |
true + 1 |
true becomes 1 | 2 |
[] + {} |
"" + "[object Object]" |
[object Object] |
null + 1 |
null becomes 0 | 1 |
Output: 12 33 2 [object Object] 1
Hoisting and the temporal dead zone
console.log(a, typeof b);
var a = 1;
let c = 2;
function b() { return c; }
console.log(b());
Trace. Hoisting creates a = undefined, b as the full function, and c in the dead zone. Line 1 prints undefined function. By the last line, c has been initialised, so b() returns 2.
Output: undefined function, then 2.
Now a snippet that throws:
let price = 100;
function apply() {
price = price * 2;
let price = 5;
}
Inside apply, the local let price is hoisted to the top of the function and shadows the outer one, but it is in the dead zone on the first line. Calling apply() throws ReferenceError: Cannot access 'price' before initialization. The outer price = 100 is never touched.
Closures
A closure is a function that keeps access to the variables of the scope it was created in, even after that scope has finished running.
function once(fn) {
let done = false, result;
return (...args) => {
if (!done) { done = true; result = fn(...args); }
return result;
};
}
const init = once(x => x * 2);
console.log(init(5), init(100));
Trace. init(5) finds done false, stores 5 * 2 = 10 and sets done. init(100) finds done true and returns the saved 10. Output: 10 10.
Fixing a var loop without let:
for (var i = 1; i <= 3; i++) {
((n) => setTimeout(() => console.log(n), 0))(i);
}
The immediately invoked arrow copies the current i into its own parameter n, so each timer closes over a different n. Output: 1, 2, 3. Without the wrapper, all three would read the shared i after the loop ends and print 4 three times.
The value of this
| How the function is called | this is |
Example |
|---|---|---|
| Plain call, strict mode | undefined |
who() |
| Method call | the object before the dot | obj.who() |
call, apply, bind |
the object passed in | who.call(other) |
With new |
the newly created object | new Maker() |
| Arrow function | this of the enclosing code |
inside a method |
"use strict";
function who() { return this === undefined ? "undefined" : this.tag; }
const obj = { tag: "obj", who };
const other = { tag: "other" };
function Maker() { this.tag = "new"; }
console.log(who(), obj.who(), who.call(other), new Maker().tag);
Output: undefined obj other new, one result for each row of the table.
Arrows inside methods are the usual fix for callbacks:
const shop = {
name: "Kiosk",
items: ["tea", "rusk"],
list() { return this.items.map(i => `${this.name}:${i}`).join(" "); },
};
console.log(shop.list());
const l = shop.list;
l();
shop.list() prints Kiosk:tea Kiosk:rusk, because the arrow inside map uses list's this. But l() is a plain call, so this is not shop and this.items is undefined: TypeError.
The event loop
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve()
.then(() => console.log("C"))
.then(() => console.log("D"));
queueMicrotask(() => console.log("E"));
(async () => {
console.log("F");
await null;
console.log("G");
})();
console.log("H");
| Phase | Runs | Prints | Microtask queue afterwards | Task queue |
|---|---|---|---|---|
| Sync | whole script | A, F, H | C, E, G | B |
| Microtask | C (queues D) | C | E, G, D | B |
| Microtask | E | E | G, D | B |
| Microtask | rest of the async function | G | D | B |
| Microtask | D | D | empty | B |
| Task | timer | B | empty | empty |
Output: A F H C E G D B, one per line. Two points decide it: the body of an async function runs synchronously up to its first await (so F comes before H), and D is queued only when C finishes, so it lands behind E and G.

Speed tricks
- Sync logs always come first, in source order. Write them down before thinking about anything else.
- Timers come last unless the snippet only has timers; among timers, shorter delay first, then scheduling order.
- A chained
.thenwaits one extra microtask turn for each link. typeofof an undeclared variable is"undefined", but of aletin its dead zone it throws.- Arrow function in an object literal property? Its
thisis not the object.
Common mistakes
- Treating
+as numeric when either operand is a string. - Assuming
letis not hoisted; it is, but it cannot be read before its line. - Thinking a closure captures a value; it captures the variable, which may change later.
- Deciding
thisfrom where a function is written instead of how it is called. - Putting
setTimeout(..., 0)before promise callbacks. - Forgetting that
awaitpauses only the async function, not the code that called it.
Practice set
All nine were run in Node.js.
console.log("10" / "2", "10" - - "2", +"");console.log([] + [], [2] * [3], typeof ([] + []));console.log(v); var v = 3; console.log(v);const fs = []; for (var k = 0; k < 2; k++) { let j = k; fs.push(() => j + k); } console.log(fs[0](), fs[1]());const o = { v: 1, f() { return () => this.v; } }; const g = o.f(); const p = { v: 2, g }; console.log(p.g());setTimeout(() => console.log("x"), 10); setTimeout(() => console.log("y"), 0); Promise.resolve().then(() => console.log("z"));async function a() { return 1; } a().then(v => console.log(v + 1)); console.log(2);function counter() { let c = 0; return () => c += 2; } const n = counter(); n(); n(); console.log(n(), counter()());console.log(0 || "a", 0 ?? "a", "" && "b", null ?? "c");
Show answers
- 5 12 0.
-and/convert to numbers,- "2"is -2, and+""is 0. - An empty string, then 6 and string.
[] + []is"";[2] * [3]becomes 2 × 3. - undefined, then 3. Only the declaration is hoisted.
- 2 3. Each
jis per iteration (0, 1), but the singlevar kis 2 when the functions run. - 1. The arrow got
this(o) wheno.f()ran; calling it through p cannot change that. - z, y, x. The microtask first, then the 0 ms timer, then the 10 ms timer.
- 2, then 2. The sync log prints 2; the promise callback then prints 1 + 1.
- 6 2. The first counter reaches 6 on its third call; a fresh counter starts at 2.
- a 0 (empty string) c.
??only replaces null or undefined;&&returns the first falsy value,"".
Practise
The quiz below has 20 output questions on coercion, hoisting, closures, this and the event loop, filterable by tier and difficulty. Every snippet was run with Node.js and the printed output checked against the marked answer.
Practise: 20 questions
FAQs
Will output questions use browser-only features such as window or alert?
Questions that test core language behaviour should give the same output in a browser and in Node.js, which is why we avoid snippets whose answer depends on the global object. If a snippet uses the DOM or window, read the stem for the assumed environment before answering.
Why does setTimeout with 0 ms run after a resolved promise?
A timer callback is a task, and promise callbacks are microtasks. After the current script finishes, the engine empties the whole microtask queue before it takes the next task, so every ready promise callback runs before even a 0 ms timer.
Is let hoisted or not?
Yes. let and const declarations are hoisted to the top of their block, which is why an inner let can shadow an outer variable from the block's first line. Unlike var, they are not initialised, so reading them before their declaration line throws a ReferenceError (the temporal dead zone).
How fast should I solve an output question?
Aim to finish the trace within a minute or so. Spend the first few seconds naming the mechanism, then follow the method above. If a snippet mixes several mechanisms, write the two queues or the hoisted variables in the margin rather than holding them in your head.
Next step
Revise the concepts in Advanced JavaScript and JavaScript Fundamentals, then see how frameworks build on them in Front-end Frameworks & Libraries. Return to the Web Development MCQ hub or take the NSCT mock test.