Skip to content

Expert · Interview preparation and career · topic 58 of 61 · 30 min

Predict-the-output questions

Explanation

Interviewers love short snippets that ask "what does this print?". They test type coercion, hoisting, closures in loops, this, sort, and event-loop order. The way to win is not memory but a method: go line by line, write down each value, and apply the rules you learned in this course.

The method

  1. Read the whole snippet once. Spot the traps: var, setTimeout, promises, this, + with strings, sort without a comparator.
  2. Make columns if timers or promises are involved: Sync, Micro, Macro.
  3. Go line by line and write each variable's value on paper.
  4. Say your reasoning aloud: interviewers give credit for the method even if you slip.

Coercion

javascript
console.log('2' + 2 - 1);   // '22' - 1 → 21
console.log([] + {});        // '' + '[object Object]' → '[object Object]'
console.log([] + []);        // ''
console.log(true + 1);       // 2
console.log(null + 1);       // 1   (null → 0)
console.log(undefined + 1);  // NaN
console.log([1, 2] == '1,2'); // true ([1, 2] → '1,2')
console.log(typeof NaN);     // 'number'

Rule: + with any string joins; - * / always convert to numbers. Objects and arrays become strings first (arrays join with commas, plain objects become "[object Object]").

Hoisting and scope

javascript
var x = 1;
function f() {
  console.log(x);   // undefined: the local var x is hoisted
  var x = 2;
}
f();

console.log(typeof g, typeof h); // 'function' 'undefined'
function g() {}
var h = () => {};

Closures in loops

javascript
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i));  // 3 3 3
for (let j = 0; j < 3; j++) setTimeout(() => console.log(j));  // 0 1 2

this

javascript
const user = {
  name: 'Asha',
  regular() { return this.name; },
  arrow: () => typeof this,
  later() { return [1].map(function () { return this; })[0]; },
};
console.log(user.regular());  // 'Asha'
console.log(user.arrow());    // 'undefined' in an ES module (this is undefined there)
console.log(user.later());    // undefined in strict code: a plain function callback loses this

Sorting and arrays

javascript
console.log([10, 1, 2].sort());          // [1, 10, 2] (string order)
console.log([3, 1, 2].sort((a, b) => a - b)); // [1, 2, 3]
const a = [1, 2, 3];
a.length = 1;
console.log(a);                          // [1] (setting length truncates)
console.log([1, 2, 3].map(parseInt));    // [1, NaN, NaN]
map passes (value, index): parseInt(2, 1) and parseInt(3, 2) are NaN because 1 is not a valid radix and 3 is not a digit in base 2.

Event loop order

javascript
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
(async () => {
  console.log('D');
  await null;
  console.log('E');
})();
console.log('F');
// A D F C E B

Sync: A, D (the async function runs until its first await), F. Micro: C, then E (both queued in order). Macro: B.

Careful: Many output questions behave differently in sloppy scripts, strict mode, ES modules and the browser console (for example what this is at the top level). If unsure, state your assumption: "assuming this runs in an ES module, where top-level this is undefined…". That shows real understanding.
Think of it like this: Predicting output is like a cricket umpire reviewing a run-out frame by frame. You do not guess from the overall impression; you look at each frame (line) and apply the exact rule.
Tip: Practise by writing your prediction first, then running the snippet in Node or the browser console. Every wrong prediction is a rule you did not know yet; write it down.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Predict-the-output questions · 1/6

Predict the output

In this lesson you will trace tricky "what does this print" questions with a reliable method.

Prefer a video by a teacher? Find free videos on “javascript tricky output questions interview coercion event loop” on YouTube ↗

In real life: A screening test on a hiring platform

Many Indian companies use online screening tests (on platforms like HackerRank or HackerEarth) with 10–15 "what is the output?" questions in 20 minutes before any human interview. Candidates who trace methodically score well; candidates who guess from memory often fall for the coercion and event-loop traps.

javascript
const out = [];
setTimeout(() => out.push('t'));
Promise.resolve().then(() => out.push('p'));
out.push('s');
setTimeout(() => console.log(out.join(' ')), 5); // s p t

Practice (0/3 done)

Task 1 · Question

What does console.log('5' * '2' + '1') print?

Task 2 · Question

let a = { n: 1 }; let b = a; a = { n: 2 }; console.log(b.n);

Task 3 · Code · Javascript

Fill in the array predictions with what each expression evaluates to, in order: 1) [] + [] 2) 1 + "2" + 3 3) 1 + 2 + "3" 4) typeof null 5) [5, 25, 100].sort()[0]. Use the exact values (strings stay strings, numbers stay numbers).

Quick quiz

Question 1

1.console.log([1, 2] + [3]) prints…

Question 2

2.console.log(0 || null || "x" || 5) prints…

Question 3

3.Promise.resolve(1).then(console.log); console.log(2); prints…

Question 4

4.console.log(typeof typeof 1) prints…

Question 5

5.const a = [1, 2, 3]; a[10] = 4; console.log(a.length) prints…

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

console.log([1, 2] + [3]) prints…

Answer: "1,23"

Arrays become strings "1,2" and "3", then they are joined.

console.log(0 || null || "x" || 5) prints…

Answer: "x"

|| returns the first truthy value.

Promise.resolve(1).then(console.log); console.log(2); prints…

Answer: 2 1

The then callback is a microtask that runs after the sync log.

console.log(typeof typeof 1) prints…

Answer: "string"

typeof 1 is the string "number", and typeof a string is "string".

const a = [1, 2, 3]; a[10] = 4; console.log(a.length) prints…

Answer: 11

Setting index 10 makes the length 11 (with empty slots).

if (true) { let x = 5; } console.log(x); What happens?Related

Answer: ReferenceError: x is not defined

let is block-scoped. x exists only inside the { } of the if, so outside it does not exist.

From Scope, hoisting and closures

typeof function () {} is…Related

Answer: "function"

Functions are objects, but typeof reports "function".

From Core concept questions

let a = 3; const b = a++; What are a and b?Related

Answer: a 4, b 3

Postfix ++ gives the old value (3) to b, then increases a to 4.

From Operators and type coercion

for (var i = 0; i < 3; i++) setTimeout(() => console.log(i)); What is printed?Related

Answer: 3 3 3

var gives one shared i, which is 3 when the timers run.

From Scope and closures

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 3 more topics in “Interview preparation and career” before its exam: Classic coding questions, Data-structure questions in JavaScript, Projects, portfolio and jobs.
  2. Module 12 exam: Interview preparation · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. 61 topics left in the course before the final exam.

← Previous: Core concept questions