Expert · Interview preparation and career · topic 58 of 61 · 30 min
Predict-the-output questions
Explanation
The method
- Read the whole snippet once. Spot the traps: var, setTimeout, promises, this, + with strings, sort without a comparator.
- Make columns if timers or promises are involved: Sync, Micro, Macro.
- Go line by line and write each variable's value on paper.
- Say your reasoning aloud: interviewers give credit for the method even if you slip.
Coercion
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
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
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 2this
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 thisSorting and arrays
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]Event loop order
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 BSync: A, D (the async function runs until its first await), F. Micro: C, then E (both queued in order). Macro: B.
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
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.
const out = [];
setTimeout(() => out.push('t'));
Promise.resolve().then(() => out.push('p'));
out.push('s');
setTimeout(() => console.log(out.join(' ')), 5); // s p tPractice (0/3 done)
What does console.log('5' * '2' + '1') print?
let a = { n: 1 }; let b = a; a = { n: 2 }; console.log(b.n);
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Classic coding questionsInterview preparation and career · same module
- Data-structure questions in JavaScriptInterview preparation and career · same module
- Scope, hoisting and closuresFrontend Web Development · JavaScript in depth
- The event loopAsynchronous JavaScript
- Hoisting and the temporal dead zoneScope, this, prototypes and classes
- ClosuresRust Programming · Closures, iterators and smart pointers
Questions people ask about this
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.
typeof function () {} is…Related
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.
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i)); What is printed?Related
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
- 3 more topics in “Interview preparation and career” before its exam: Classic coding questions, Data-structure questions in JavaScript, Projects, portfolio and jobs.
- Module 12 exam: Interview preparation · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- 61 topics left in the course before the final exam.