Interview Q&A · JavaScript · 12 questions in this topic

Tricky Outputs & Gotchas — JavaScript Interview Q&A

All JavaScript topics

The prediction questions interviewers love — coercion, hoisting, this-loss and async ordering. Part of Tricky Outputs & Coding Tasks · 204 questions in the JavaScript bank.

What logs: `console.log(1 + "2" + 3)` vs `console.log(1 + 2 + "3")`?

Answer

Left-to-right with + stringifying on first string contact: 1 + '2' → '12', then + 3 → '123'. Versus 1 + 2 → 3 (numeric), then + '3' → '33'. Type flows left to right; the first string operand flips the rest to concat.

First-string-flips-the-chain is the evaluation rule.

Example

Example.jsjs
console.log(1 + '2' + 3); // '123'
console.log(1 + 2 + '3');   // '33'

What logs: `var` loop with `setTimeout` (and the three fixes)?

Answer

3 3 3: one shared var binding read after the loop finishes. Fixes: let (per-iteration bindings), IIFE capture per iteration (pre-let), forEach/for...of with const per element.

The evergreen closure-scope interview question.

Example

Example.jsjs
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

💡 Shared-vs-per-iteration is the whole explanation.

What is `this` inside: method vs detached vs arrow vs callback?

Answer

Method call (o.m()): o. Detached (const f = o.m; f()): undefined/global. Arrow defined in method: lexical method this (safe). Bare callback (setTimeout(o.m)): detached (lost).

Detachment-loses-receiver explains every variant.

Example

Example.jsjs
const o = { n: 1, m() { return this?.n; } };
o.m();              // 1 (receiver)
const f = o.m; f(); // undefined (detached, strict)

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits