JavaScript Output Questions: How to Trace Hoisting, Closures, this and the Event Loop

By the NSCT Exam Editorial Team · Updated 2026-11-24 · Facts checked against official sources on 2026-11-24

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

  1. Scan for the mechanism. + with a string means coercion; var or a function used above its line means hoisting; a function returned from a function means a closure; this inside a callback means binding; setTimeout, promises or await mean the event loop.
  2. Hoist first. Before reading line 1, list every var (value undefined), every function declaration (full body) and every let/const (in the dead zone until its line runs).
  3. Run the synchronous code top to bottom, writing each log as it happens.
  4. 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.
  5. For every this, ask how the function was called, not where it was written. Arrow functions are the exception: they take this from the surrounding code.
  6. 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.

Event loop for the page's snippet: synchronous code prints A, F, H; the microtask queue then prints C, E, G, D; the timer task prints B last. Final output A F H C E G D B.
The page's event-loop snippet, output confirmed by running it in Node. All microtasks drain before the next task.

Speed tricks

Common mistakes

Practice set

All nine were run in Node.js.

  1. console.log("10" / "2", "10" - - "2", +"");
  2. console.log([] + [], [2] * [3], typeof ([] + []));
  3. console.log(v); var v = 3; console.log(v);
  4. const fs = []; for (var k = 0; k < 2; k++) { let j = k; fs.push(() => j + k); } console.log(fs[0](), fs[1]());
  5. const o = { v: 1, f() { return () => this.v; } }; const g = o.f(); const p = { v: 2, g }; console.log(p.g());
  6. setTimeout(() => console.log("x"), 10); setTimeout(() => console.log("y"), 0); Promise.resolve().then(() => console.log("z"));
  7. async function a() { return 1; } a().then(v => console.log(v + 1)); console.log(2);
  8. function counter() { let c = 0; return () => c += 2; } const n = counter(); n(); n(); console.log(n(), counter()());
  9. console.log(0 || "a", 0 ?? "a", "" && "b", null ?? "c");
Show answers
  1. 5 12 0. - and / convert to numbers, - "2" is -2, and +"" is 0.
  2. An empty string, then 6 and string. [] + [] is ""; [2] * [3] becomes 2 × 3.
  3. undefined, then 3. Only the declaration is hoisted.
  4. 2 3. Each j is per iteration (0, 1), but the single var k is 2 when the functions run.
  5. 1. The arrow got this (o) when o.f() ran; calling it through p cannot change that.
  6. z, y, x. The microtask first, then the 0 ms timer, then the 10 ms timer.
  7. 2, then 2. The sync log prints 2; the promise callback then prints 1 + 1.
  8. 6 2. The first counter reaches 6 on its third call; a fresh counter starts at 2.
  9. 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

Interactive quiz loading. The first 10 questions are shown below.

  1. What does this code print?

    console.log(typeof undefined, typeof NaN, typeof []);
    1. undefined NaN array
    2. object number array
    3. undefined number object
    4. undefined undefined object
    Show answer

    Answer: C. undefined number object

    typeof undefined is 'undefined'. NaN is a special value of the number type, so typeof NaN is 'number'. Arrays are objects, so typeof [] is 'object'; use Array.isArray() to detect them.

  2. What does this code print?

    let a = [1, 2, 3];
    let b = a;
    b.push(4);
    console.log(a.length);
    1. 3
    2. 4
    3. undefined
    4. TypeError
    Show answer

    Answer: B. 4

    Arrays are objects, and b = a copies the reference, not the array. Both names point to the same array, so pushing through b changes what a sees: length 4. Use [...a] or a.slice() for a copy.

  3. What does this code print?

    console.log(1 + "2" + 3, 1 + 2 + "3");
    1. 123 33
    2. 6 6
    3. 123 123
    4. 15 33
    Show answer

    Answer: A. 123 33

    + is evaluated left to right. In the first, 1 + '2' is the string '12', then '12' + 3 is '123'. In the second, 1 + 2 is the number 3 first, then 3 + '3' is '33'.

  4. What does this code print?

    console.log([] == false, !![]);
    1. false true
    2. false false
    3. true false
    4. true true
    Show answer

    Answer: D. true true

    For [] == false, the boolean becomes 0 and [] becomes '' and then 0, so 0 == 0 is true. But every object, including an empty array, is truthy, so !![] is true. Loose equality and truthiness follow different rules.

  5. What does this code print?

    console.log(typeof f, typeof g);
    function f() {}
    var g = () => 1;
    1. function undefined
    2. function function
    3. undefined undefined
    4. ReferenceError
    Show answer

    Answer: A. function undefined

    A function declaration is hoisted with its body, so f is already a function. For var g only the declaration is hoisted and it starts as undefined; the arrow function is assigned when line 3 runs.

  6. What does this code print?

    console.log(Boolean("false"), Boolean(0), Boolean(" "));
    1. false false false
    2. false false true
    3. true false false
    4. true false true
    Show answer

    Answer: D. true false true

    Any non-empty string is truthy, including 'false' and a single space. The falsy values are false, 0, -0, 0n, '', null, undefined and NaN, so only Boolean(0) is false.

  7. What does this code print?

    function add(x) {
      return y => x + y;
    }
    const add5 = add(5);
    console.log(add5(3), add(1)(1));
    1. NaN NaN
    2. 8 2
    3. 8 undefined
    4. 5 1
    Show answer

    Answer: B. 8 2

    add(5) returns an arrow function that closes over x = 5, so add5(3) is 8. add(1) returns a new closure with x = 1, and calling it with 1 gives 2. Each call to add creates its own x.

  8. What does this code print?

    let count = 0;
    const inc = () => count++;
    inc();
    inc();
    console.log(count, inc());
    1. 2 3
    2. 3 3
    3. 2 2
    4. 3 2
    Show answer

    Answer: C. 2 2

    After two calls count is 2. Arguments are evaluated left to right: count is read as 2, then inc() returns the old value 2 (postfix ++) and only then makes count 3. So it prints 2 2.

  9. What does this code print?

    const user = {
      name: "Hina",
      hi() { return "Hi " + this.name; },
    };
    const g = user.hi.bind({ name: "Bilal" });
    console.log(user.hi(), g());
    1. Hi Hina Hi Hina
    2. Hi Bilal Hi Bilal
    3. Hi Hina Hi undefined
    4. Hi Hina Hi Bilal
    Show answer

    Answer: D. Hi Hina Hi Bilal

    user.hi() is a method call, so this is user and the name is Hina. bind returns a new function whose this is permanently the object passed in, so g() uses Bilal. bind does not change the original method.

  10. In what order are the numbers printed? (Each console.log line is shown separated by commas.)

    console.log(1);
    setTimeout(() => console.log(2));
    queueMicrotask(() => console.log(3));
    Promise.resolve().then(() => console.log(4));
    console.log(5);
    1. 1, 2, 3, 4, 5
    2. 1, 5, 2, 3, 4
    3. 1, 5, 3, 4, 2
    4. 1, 5, 4, 3, 2
    Show answer

    Answer: C. 1, 5, 3, 4, 2

    Synchronous code runs first: 1 and 5. Then the microtask queue empties in the order the tasks were queued: queueMicrotask (3) before the promise reaction (4). The setTimeout callback is a task and runs last: 2.

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.