Senior JavaScript Interview Questions: Tricky Output Puzzles and Deep Dives

Senior interviews often include “what does this print?” puzzles. They are not about memorising trivia: each one tests whether you understand a mechanism (coercion, hoisting, closures, this, the event loop, references) well enough to predict behaviour and explain it. This lesson has 24 such puzzles grouped by mechanism, each with the real output from Node.js 26 and the reasoning you would give, followed by the deeper design questions senior engineers and SDET leads are asked. Try each puzzle before reading the output.

Advertisement

📖 What You’ll Learn: type coercion rules behind surprising results, floating point, sort and map gotchas, hoisting and the temporal dead zone, closures in loops, this with methods, arrows, classes and callbacks, getters and prototypes, the exact event loop order with promises, await and timers, error handling with finally and async functions, references and object keys, JSON edge cases, and senior-level questions on architecture, quality strategy and leadership.


🔀 Coercion and Numbers

Q1. What do these additions print?

📄 puzzle.js

console.log(1 + "2", "3" - 1, "3" * "4", true + true, [] + [], [] + {}, 1 + null, 1 + undefined);

⌨️ Terminal

node puzzle.js

🖥️ Output

12 2 12 2  [object Object] 1 NaN

+ concatenates as soon as one side is a string (after converting objects to primitives: [] becomes "", {} becomes "[object Object]"). Other arithmetic operators convert to numbers: null is 0 and undefined is NaN.

Q2. Loose equality traps

📄 puzzle.js

console.log("" == 0, "0" == 0, "" == "0");
console.log(null == 0, null >= 0, undefined == null);
console.log([1] == 1, [1, 2] == "1,2", NaN == NaN);

⌨️ Terminal

node puzzle.js

🖥️ Output

true true false
false true true
true true false

== is not transitive: "" == 0 and "0" == 0 but "" != "0". null == 0 is false (null only loosely equals undefined), yet null >= 0 is true because relational operators convert null to 0. Arrays are converted to strings. This is why teams ban == with linting.

Q3. Floating point

📄 puzzle.js

console.log(0.1 + 0.2, 0.1 + 0.2 === 0.3);
console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);
console.log((0.1 * 3).toFixed(2), 9007199254740993);

⌨️ Terminal

node puzzle.js

🖥️ Output

0.30000000000000004 false
true
0.30 9007199254740992

Numbers are 64-bit binary floating point, so 0.1 and 0.2 cannot be stored exactly. Compare with a tolerance, keep money in integer paise/cents, and remember integers above Number.MAX_SAFE_INTEGER lose precision (use BigInt).

Q4. Default sort and map(parseInt)

📄 puzzle.js

console.log([10, 9, 1, 100].sort());
console.log(["10", "10", "10"].map(parseInt));
console.log([10, 9, 1, 100].sort((a, b) => a - b));

⌨️ Terminal

node puzzle.js

🖥️ Output

[ 1, 10, 100, 9 ]
[ 10, NaN, 2 ]
[ 1, 9, 10, 100 ]

Default sort compares strings, so “100” comes before “9”. map passes (value, index), and parseInt("10", 1) is NaN (radix 1 is invalid) while parseInt("10", 2) is 2. Always pass a comparator and wrap parseInt: map((s) => Number(s)).

Q5. typeof and instanceof oddities

📄 puzzle.js

console.log(typeof NaN, typeof null, typeof function () {}, typeof class {});
console.log([] instanceof Object, Object.prototype.toString.call([]), Array.isArray({ length: 0 }));

⌨️ Terminal

node puzzle.js

🖥️ Output

number object function function
true [object Array] false

NaN is a number, null reports “object”, classes are functions. For reliable type checks use Array.isArray, Number.isNaN and Object.prototype.toString.


🏗️ Hoisting, Scope and Closures

Q6. Hoisting of var and functions

📄 puzzle.js

console.log(typeof greet, typeof sayHi, value);
var value = 1;
function greet() {}
var sayHi = function () {};

⌨️ Terminal

node puzzle.js

🖥️ Output

function undefined undefined

Function declarations are hoisted with their body; var declarations are hoisted but initialised to undefined, even when they hold a function expression.

Q7. The temporal dead zone inside a block

📄 puzzle.js

let x = "outer";
{
  try {
    console.log(x);
  } catch (e) {
    console.log(`${e.name}: ${e.message}`);
  }
  let x = "inner";
}

⌨️ Terminal

node puzzle.js

🖥️ Output

ReferenceError: Cannot access 'x' before initialization

The inner let x is hoisted to the top of its block, shadowing the outer one, but stays uninitialised until its line: accessing it throws instead of printing “outer”.

Q8. Closures in a loop

📄 puzzle.js

const fns = [];
for (var i = 0; i < 3; i++) fns.push(() => i);
const fixed = [];
for (let j = 0; j < 3; j++) fixed.push(() => j);
console.log(fns.map((f) => f()), fixed.map((f) => f()));

⌨️ Terminal

node puzzle.js

🖥️ Output

[ 3, 3, 3 ] [ 0, 1, 2 ]

One var i is shared by all closures and ends at 3; let creates a fresh binding per iteration.

Q9. Function scope with the same name

📄 puzzle.js

var name = "global";
function show() {
  console.log(name);
  var name = "local";
  console.log(name);
}
show();

⌨️ Terminal

node puzzle.js

🖥️ Output

undefined
local

The local var name is hoisted inside show, so the first log sees the local variable before assignment (undefined), not the global.


Advertisement

🎯 this, Classes and Prototypes

Q10. this in different call styles

📄 puzzle.js

"use strict";
const user = {
  name: "Asha",
  hello() { return `hi ${this?.name}`; },
  later() { return [1].map(function () { return this; }); },
  laterArrow() { return [1].map(() => this.name); },
};
const { hello } = user;
console.log(user.hello(), hello(), user.later(), user.laterArrow());

⌨️ Terminal

node puzzle.js

🖥️ Output

hi Asha hi undefined [ undefined ] [ 'Asha' ]

Destructuring detaches the method (this is undefined in strict mode). A regular callback function gets its own undefined this; an arrow keeps the method’s this.

Q11. Getters and shared prototype state

📄 puzzle.js

class Cart {
  items = [];
  static count = 0;
  constructor() { Cart.count++; }
  get total() { return this.items.reduce((s, i) => s + i, 0); }
}
const a = new Cart(), b = new Cart();
a.items.push(100);
console.log(a.total, b.total, Cart.count, typeof Object.getOwnPropertyDescriptor(Cart.prototype, "total").get);

⌨️ Terminal

node puzzle.js

🖥️ Output

100 0 2 function

Class fields (items) are created per instance, so carts do not share arrays; static fields belong to the class; getters live on the prototype and compute on access.

Q12. A mutable default on the prototype

📄 puzzle.js

function Team() {}
Team.prototype.members = [];
const qa = new Team(), dev = new Team();
qa.members.push("Asha");
console.log(dev.members, qa.members === dev.members);

⌨️ Terminal

node puzzle.js

🖥️ Output

[ 'Asha' ] true

Putting an array on the prototype shares one array among all instances: a classic bug in old-style constructors. Class fields or constructor assignments avoid it.


⏱️ Event Loop, Promises and async

Q13. Full ordering puzzle

📄 puzzle.js

console.log(1);
setTimeout(() => console.log(2), 0);
Promise.resolve().then(() => {
  console.log(3);
  setTimeout(() => console.log(4), 0);
}).then(() => console.log(5));
queueMicrotask(() => console.log(6));
console.log(7);

⌨️ Terminal

node puzzle.js

🖥️ Output

1
7
3
6
5
2
4

Sync: 1, 7. Microtasks in queue order: 3 (which schedules timer 4 and queues 5), 6, then 5. Macrotasks in scheduling order: 2, then 4.

Q14. async functions return order

📄 puzzle.mjs

async function a() { console.log("a start"); await b(); console.log("a end"); }
async function b() { console.log("b"); }
a();
Promise.resolve().then(() => console.log("then"));
console.log("script end");

⌨️ Terminal

node puzzle.mjs

🖥️ Output

a start
b
script end
a end
then

An async function runs synchronously until its first await. “a end” is queued as a microtask when b’s promise resolves; it is queued before the “then” callback, so it prints first.

Q15. Errors inside promises and setTimeout

📄 puzzle.js

try {
  Promise.reject(new Error("rejected"));
  setTimeout(() => {}, 0);
} catch (e) {
  console.log("caught synchronously?", e.message);
}
process.on("unhandledRejection", (e) => console.log("unhandledRejection:", e.message));
console.log("try block finished without catching anything");

⌨️ Terminal

node puzzle.js

🖥️ Output

try block finished without catching anything
unhandledRejection: rejected

try...catch only catches errors thrown synchronously in the block. A rejected promise is handled later (or reported as unhandled); errors inside timer callbacks also escape the surrounding try. Use await inside try, or .catch().

Q16. await in forEach

📄 puzzle.mjs

const wait = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
const order = [];
[30, 10, 20].forEach(async (ms) => { order.push(await wait(ms, ms)); });
console.log("after forEach:", order);
await wait(50);
console.log("later:", order);
const seq = [];
for (const ms of [30, 10, 20]) seq.push(await wait(ms, ms));
console.log("for...of:", seq);

⌨️ Terminal

node puzzle.mjs

🖥️ Output

after forEach: []
later: [ 10, 20, 30 ]
for...of: [ 30, 10, 20 ]

forEach ignores the promises returned by async callbacks, so it neither waits nor keeps order. Use for...of with await for sequential work, or Promise.all(arr.map(...)) for parallel work.

Q17. finally overriding return

📄 puzzle.js

function f() {
  try { return "try"; }
  finally { console.log("finally runs"); }
}
function g() {
  try { throw new Error("boom"); }
  finally { return "finally wins"; }
}
console.log(f(), g());

⌨️ Terminal

node puzzle.js

🖥️ Output

finally runs
try finally wins

finally always runs; if it returns, that value replaces the try’s return or even a thrown error, silently swallowing it. Never return from finally.


📦 References, Objects and JSON

Advertisement

Q18. Object keys and ordering

📄 puzzle.js

const obj = { b: 1, 2: "two", a: 3, 1: "one" };
console.log(Object.keys(obj));
const key = { id: 1 };
const map = {};
map[key] = "first";
map[{ id: 2 }] = "second";
console.log(Object.keys(map), map[key]);

⌨️ Terminal

node puzzle.js

🖥️ Output

[ '1', '2', 'b', 'a' ]
[ '[object Object]' ] second

Integer-like keys come first in ascending order, then string keys in insertion order. Object keys are strings, so both objects become “[object Object]” and overwrite each other: use a Map for object keys.

Q19. Mutation through references

📄 puzzle.js

function addTag(test) { test.tags.push("regression"); test = { tags: [] }; return test; }
const t = { tags: ["smoke"] };
const result = addTag(t);
console.log(t.tags, result.tags);

⌨️ Terminal

node puzzle.js

🖥️ Output

[ 'smoke', 'regression' ] []

Arguments are passed by value, but the value of an object is a reference: mutating through it changes the caller’s object, while reassigning the parameter only changes the local variable.

Q20. JSON.stringify edge cases

📄 puzzle.js

const data = { a: undefined, b: () => 1, c: NaN, d: new Date(0), e: [undefined, () => 1], f: Infinity, g: new Map([["k", 1]]) };
console.log(JSON.stringify(data));
try { JSON.stringify({ big: 10n }); } catch (e) { console.log(`${e.name}: ${e.message}`); }

⌨️ Terminal

node puzzle.js

🖥️ Output

{"c":null,"d":"1970-01-01T00:00:00.000Z","e":[null,null],"f":null,"g":{}}
TypeError: Do not know how to serialize a BigInt

Undefined and functions are dropped in objects and become null in arrays; NaN and Infinity become null; Dates become ISO strings; Maps become {}; BigInt throws. Snapshot and API tests must account for these conversions.

Q21. Array holes and length

📄 puzzle.js

const a = [1, 2, 3];
a[6] = 7;
console.log(a.length, a);
console.log(a.map((x) => x * 2).length, a.filter(() => true).length);
delete a[0];
console.log(a, a.length);

⌨️ Terminal

node puzzle.js

🖥️ Output

7 [ 1, 2, 3, <3 empty items>, 7 ]
7 4
[ <1 empty item>, 2, 3, <3 empty items>, 7 ] 7

Assigning beyond the end creates empty slots (holes); map keeps holes while filter skips them; delete leaves a hole and keeps the length. Use splice or toSpliced to remove items.

Q22. Spread copies are shallow; frozen is shallow too

📄 puzzle.js

const original = Object.freeze({ env: "qa", tags: ["smoke"] });
const copy = { ...original, env: "prod" };
copy.tags.push("ui");
console.log(original.tags, Object.isFrozen(copy), original.env);

⌨️ Terminal

node puzzle.js

🖥️ Output

[ 'smoke', 'ui' ] false qa

Spread copies top-level properties only (the tags array is shared) and does not copy the frozen state. Freeze is shallow too: nested arrays remain mutable unless frozen separately.

Q23. Comparing objects and NaN in collections

📄 puzzle.js

console.log({ a: 1 } === { a: 1 }, [NaN].includes(NaN), [NaN].indexOf(NaN), new Set([NaN, NaN]).size);
console.log(Object.is(0, -0), 0 === -0);

⌨️ Terminal

node puzzle.js

🖥️ Output

false true -1 1
false true

Objects compare by reference. includes and Sets use SameValueZero (NaN equals NaN), while indexOf uses ===. Object.is distinguishes +0 and -0.

Q24. Generators are lazy and resumable

📄 puzzle.js

function* ids() {
  console.log("generator started");
  let n = 1;
  while (true) {
    const reset = yield n++;
    if (reset) n = 1;
  }
}
const gen = ids();
console.log("created");
console.log(gen.next().value, gen.next().value, gen.next(true).value, gen.next().value);

⌨️ Terminal

node puzzle.js

🖥️ Output

created
generator started
1 2 1 2

Creating a generator runs nothing; each next() runs until the next yield. A value passed to next(value) becomes the result of the paused yield expression.


🏛️ Senior Topics Beyond Puzzles

Q25. How would you design a test automation strategy for a new product?

Start from risks and architecture: what breaks, how often it changes, what it costs. Define the pyramid for this product (unit and component tests owned by developers, API/contract tests for services, a thin layer of critical end-to-end journeys), environments and test data strategy, CI gates (fast checks on every commit, broader suites before release), non-functional testing (performance, security, accessibility), observability of test results (flaky rate, duration, coverage of critical flows) and ownership. Revisit it as the product evolves.

Q26. How do you scale a Playwright/JavaScript suite to thousands of tests?

Independent tests with isolated data, API-driven setup, stored authentication, parallel workers and CI sharding with merged reports, tags for smoke and regression subsets, worker-scoped fixtures for expensive resources, strict linting (floating promises, no focused tests, no hard waits), quarantine and tracking of flaky tests with owners, and dashboards for duration trends. Remove tests that duplicate lower-level coverage.

Q27. Explain how you would find the root cause of a memory leak in a Node.js service or a long test run.

Reproduce with a repeatable load, watch heap usage over time, take heap snapshots at intervals (node --inspect + DevTools, or --heapsnapshot-signal), compare retained sizes and look at retainer paths to see what keeps objects alive: usually caches, listeners, timers or closures. Fix, then add a regression check (memory growth after N iterations).

Q28. How do you mentor testers moving into automation?

Pair on real tests from their own manual cases, start with JavaScript fundamentals and small wins, review their code with explanations, establish conventions (locators, structure, data) and a definition of done for tests, encourage reading traces and debugging rather than retrying, and give ownership of a feature area gradually.


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Predict the output.

console.log([1, 2, 3] + [4, 5]);
console.log("b" + "a" + +"a" + "a");
Show answer

📄 p1.js

console.log([1, 2, 3] + [4, 5]);
console.log("b" + "a" + +"a" + "a");

🖥️ Output

1,2,34,5
baNaNa

Arrays become “1,2,3” and “4,5” and are concatenated. +"a" is NaN, giving “baNaNa”.

Q2. Predict the output order.

setTimeout(() => console.log("T"), 0);
(async () => { console.log("A"); await undefined; console.log("B"); })();
Promise.resolve().then(() => console.log("P"));
console.log("S");
Show answer

📄 p2.js

setTimeout(() => console.log("T"), 0);
(async () => { console.log("A"); await undefined; console.log("B"); })();
Promise.resolve().then(() => console.log("P"));
console.log("S");

🖥️ Output

A
S
B
P
T

A runs synchronously, then S. The await continuation (B) was queued before the then callback (P). Timers last.

Q3. What does this print, and how would you fix the bug?

const counter = { count: 0, inc: () => { this.count++; } };
counter.inc();
console.log(counter.count);
Show answer

📄 p3.js

const counter = { count: 0, inc: () => { this.count++; } };
counter.inc();
console.log(counter.count);
const fixed = { count: 0, inc() { this.count++; } };
fixed.inc();
console.log(fixed.count);

🖥️ Output

0
1

An arrow function does not get the object as this; it increments a property on the outer this (module.exports here). Use method syntax.

Q4. Predict the output.

const a = {};
const b = { key: "b" };
const c = { key: "c" };
a[b] = 123;
a[c] = 456;
console.log(a[b]);
Show answer

📄 p4.js

const a = {};
const b = { key: "b" };
const c = { key: "c" };
a[b] = 123;
a[c] = 456;
console.log(a[b]);

🖥️ Output

456

Both objects become the key “[object Object]”, so the second assignment overwrites the first.

Q5. Predict the output.

let x = 1;
function outer() {
  let x = 2;
  return function inner() { return x++; };
}
const fn = outer();
console.log(fn(), fn(), x);
Show answer

📄 p5.js

let x = 1;
function outer() {
  let x = 2;
  return function inner() { return x++; };
}
const fn = outer();
console.log(fn(), fn(), x);

🖥️ Output

2 3 1

The closure has its own x starting at 2 and post-increments it; the outer x is untouched.

Q6. Predict the output.

console.log(Math.max(), Math.min(), [] == false, !![]);
Show answer

📄 p6.js

console.log(Math.max(), Math.min(), [] == false, !![]);

🖥️ Output

-Infinity Infinity true true

With no arguments, max returns -Infinity and min returns Infinity (identity values). [] == false converts both to 0, while !![] is true because objects are truthy.


🧠 MCQ Quiz: Interview Questions: Senior

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What is [] + {}?
  2. What does [10, 9, 1].sort() return?
  3. What is null >= 0?
  4. What does accessing a let variable before its declaration in the same block do?
  5. Which prints first: code after await in an async function, or a then registered after calling it?
  6. Does forEach wait for async callbacks?
  7. What happens if finally contains a return?
  8. How does JSON.stringify treat undefined in an array?
  9. Which finds NaN in an array?
  10. When does a generator function body start running?

💼 Interview Questions and Answers

Q1. Why do companies ask output puzzles, and how should you answer them?

They test whether you can reason about language mechanics that cause real bugs: coercion in comparisons, shared references, lost this, async ordering. Answer by naming the mechanism first (“+ with a string concatenates”, “microtasks before macrotasks”), walking through the code step by step, and stating the result; if unsure, say what you would check. Then mention how you avoid the problem in real code (===, linting, immutability, await).

Q2. What is your approach to code quality in a JavaScript/TypeScript test codebase?

TypeScript with strict settings, ESLint with rules for floating promises, no focused or skipped tests and no hard waits, Prettier, code review checklists, small composable helpers, page objects or components with clear boundaries, consistent naming and data builders, and CI that blocks on lint, type check and a fast smoke suite. Quality also means test value: remove or rewrite tests that never fail or fail for the wrong reasons.

Q3. How do you evaluate whether to adopt a new tool or framework?

Define the problem and success criteria, run a time-boxed proof of concept on real tests, compare maintenance cost, speed, reliability, debugging tools, community and licensing, consider team skills and migration cost, and plan an incremental rollout with a way back. Avoid switching for novelty alone.

Q4. Tell me about a time you improved test reliability or speed significantly.

Use measurable before/after numbers: for example, flaky rate from 8% to under 1% by replacing sleeps with web-first assertions and isolating data, and runtime from 45 to 12 minutes by API setup, storage-state login and sharding. Explain diagnosis, decisions and how you kept it from regressing (dashboards, lint rules, review checklist).


Advertisement

❓ Frequently Asked Questions

🤔 Do I need to memorise all coercion rules?

No. Know the main ones (+ with strings, == conversions, falsy values, object-to-primitive) and the safe habits: ===, explicit Number(), linting. Interviewers care about reasoning.

🤔 Are these puzzles relevant for SDET roles?

Yes: lost this in page-object callbacks, forEach with async, shared fixture objects and promise ordering all appear in real automation code.

🤔 How can I practise output questions?

Write small snippets, predict the output, run them with Node.js and explain any surprise. The earlier lessons in this course show the mechanism behind each puzzle.

🤔 What else do senior interviews include?

System and framework design, debugging stories, test strategy, CI/CD, performance and security testing basics, and leadership or mentoring examples.


🏁 Summary

  • + concatenates with strings, other operators convert to numbers; avoid == and default sort.
  • Hoisting, the TDZ and closures in loops explain many “unexpected” values.
  • this depends on the call; arrows inherit it; prototypes share state across instances.
  • Event loop: sync, then microtasks (then, await continuations), then macrotasks; forEach does not await; never return in finally.
  • References, object keys, JSON conversion and shallow copies are frequent sources of real bugs.

Next, continue with Lesson 78: Coding Interview Programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in