JavaScript Interview Questions for 3–5 Years Experience (Scenario-Based)

With three to five years of experience, interviews move from “what is a closure?” to “here is a problem, how would you solve it, and why?”. Expect questions about how JavaScript really works (this, prototypes, the event loop), about asynchronous code and error handling, and about the engineering decisions in a test framework: data, flakiness, performance, structure. This lesson groups those questions by theme. Each answer is written as you would say it, with runnable code where it helps; every output was produced on Node.js 26.

Advertisement

📖 What You’ll Learn: how this is decided, call/apply/bind, prototypes and classes, the event loop with microtasks and macrotasks, promise chaining and combinators, error handling in async code, closures in loops, immutability and deep copies, memory leaks, debounce and throttle, modules, design patterns in test frameworks, flaky-test diagnosis, API and data strategies, and how to structure answers to scenario questions.


🎯 this, Prototypes and Classes

Q1. How is the value of this decided?

By how a function is called, not where it is written: as a method (obj.fn()) it is obj; as a plain function in strict mode it is undefined; with new it is the new object; with call/apply/bind it is whatever you pass. Arrow functions have no own this: they use the surrounding one.

📄 q1.js

"use strict";
const page = {
  name: "LoginPage",
  regular() { return this?.name; },
  arrow: () => typeof this,
  delayed() { return [1].map(() => this.name); },     // arrow inside a method keeps this
};
console.log(page.regular());
const detached = page.regular;
console.log(detached());                // lost: called without an object
console.log(page.arrow());
console.log(page.delayed());
console.log(detached.call({ name: "CartPage" }), detached.bind({ name: "Bound" })());

⌨️ Terminal

node q1.js

🖥️ Output

LoginPage
undefined
object
[ 'LoginPage' ]
CartPage Bound

Q2. Scenario: a class method passed as a callback says “Cannot read properties of undefined”. Why and how do you fix it?

Passing obj.method detaches it from the object, so this is undefined when the callback runs. Fix with an arrow wrapper, bind, or a class field arrow function:

📄 q2.js

class Reporter {
  failures = [];
  record(result) { if (result.status === "failed") this.failures.push(result.name); }
  recordSafe = (result) => { if (result.status === "failed") this.failures.push(result.name); };
}
const r = new Reporter();
const results = [{ name: "cart", status: "failed" }];
try {
  results.forEach(r.record);                 // detached method
} catch (e) {
  console.log(`${e.name}: ${e.message}`);
}
results.forEach((x) => r.record(x));          // fix 1: arrow wrapper
results.forEach(r.recordSafe);                // fix 2: class field arrow
console.log(r.failures);

⌨️ Terminal

node q2.js

🖥️ Output

TypeError: Cannot read properties of undefined (reading 'failures')
[ 'cart', 'cart' ]

Q3. What is the prototype chain, and how do classes relate to it?

Every object has a hidden link to a prototype object. When a property is missing, JavaScript looks it up along that chain. class syntax is a cleaner way to set up the same mechanism: methods live on the prototype and are shared by all instances.

📄 q3.js

class BasePage { open() { return `open ${this.url}`; } }
class LoginPage extends BasePage { url = "/login"; }
const p = new LoginPage();
console.log(p.open());
console.log(Object.hasOwn(p, "open"), "open" in p);
console.log(Object.getPrototypeOf(p) === LoginPage.prototype, Object.getPrototypeOf(LoginPage.prototype) === BasePage.prototype);

⌨️ Terminal

node q3.js

🖥️ Output

open /login
false true
true true

🔄 The Event Loop and Promises

Q4. Predict the order and explain microtasks vs macrotasks.

Synchronous code runs first. Then all microtasks (promise callbacks, queueMicrotask, the code after await) run until the queue is empty. Then one macrotask (timer, I/O) runs, followed again by all microtasks, and so on.

📄 q4.js

console.log("A: sync start");
setTimeout(() => console.log("G: timeout (macrotask)"), 0);
Promise.resolve()
  .then(() => console.log("D: first then"))
  .then(() => console.log("F: second then"));
(async () => {
  console.log("B: async function body runs synchronously");
  await null;
  console.log("E: code after await");
})();
console.log("C: sync end");

⌨️ Terminal

node q4.js

🖥️ Output

A: sync start
B: async function body runs synchronously
C: sync end
D: first then
E: code after await
F: second then
G: timeout (macrotask)

Walk through it: A, B and C are synchronous. At that point two microtasks are queued: “first then” (D) and the continuation after await (E). D runs and only then queues “second then” (F), so E comes before F. The timer (G) is a macrotask and runs last, after the microtask queue is empty. Explaining why E beats F is what turns a correct guess into a strong answer.

Advertisement

Q5. Promise.all vs allSettled vs race vs any: when do you use each?

MethodResolves whenRejects whenUse case
allAll fulfil (array of values)The first one rejectsSet up test data in parallel; all must succeed
allSettledAll finish (statuses)NeverHealth-check many services and report each
raceThe first one settlesThe first one settles with a rejectionTimeouts
anyThe first one fulfilsAll reject (AggregateError)Fastest of several mirrors

📄 q5.mjs

const ok = (v, ms) => new Promise((r) => setTimeout(() => r(v), ms));
const fail = (msg, ms) => new Promise((_, j) => setTimeout(() => j(new Error(msg)), ms));

console.log(await Promise.all([ok("users", 20), ok("products", 10)]));
console.log((await Promise.allSettled([ok("api", 10), fail("db down", 5)])).map((r) => r.status));
console.log(await Promise.race([ok("fast", 5), ok("slow", 50)]));
console.log(await Promise.any([fail("mirror 1", 5), ok("mirror 2", 10)]));
try { await Promise.all([ok("a", 20), fail("b failed", 5)]); } catch (e) { console.log("all rejected with:", e.message); }

⌨️ Terminal

node q5.mjs

🖥️ Output

[ 'users', 'products' ]
[ 'fulfilled', 'rejected' ]
fast
mirror 2
all rejected with: b failed

Q6. Scenario: a loop of API calls takes 10 seconds. How do you speed it up safely?

If the calls are independent, run them in parallel with Promise.all instead of awaiting each one in a for loop. To avoid overloading the server or hitting rate limits, cap concurrency with a small pool. Keep sequential execution when order matters or each call depends on the previous one.

📄 q6.mjs

const call = (id) => new Promise((r) => setTimeout(() => r(id), 50));
const ids = [1, 2, 3, 4, 5, 6];

let start = performance.now();
for (const id of ids) await call(id);
const sequential = performance.now() - start;

start = performance.now();
await Promise.all(ids.map(call));
const parallel = performance.now() - start;

console.log("sequential took about 6 × 50 ms:", sequential >= 300);
console.log("parallel took about one call:", parallel < 150);
console.log("parallel at least 3x faster:", sequential / parallel > 3);

⌨️ Terminal

node q6.mjs

🖥️ Output

sequential took about 6 × 50 ms: true
parallel took about one call: true
parallel at least 3x faster: true

Q7. What happens to an error thrown inside a then callback, and to a rejection nobody handles?

A throw inside then turns the returned promise into a rejected one, skipping later thens until a catch. A rejection without any handler triggers an unhandledRejection; in Node.js the default is to crash the process, which is good: silent failures are worse.

📄 q7.js

Promise.resolve(1)
  .then((v) => { throw new Error(`step 2 failed with ${v}`); })
  .then(() => console.log("never runs"))
  .catch((e) => { console.log("caught:", e.message); return "recovered"; })
  .then((v) => console.log("continues with:", v));

⌨️ Terminal

node q7.js

🖥️ Output

caught: step 2 failed with 1
continues with: recovered

🧠 Closures, Copies and Memory

Q8. Classic: var in a loop with setTimeout. What prints and how do you fix it?

📄 q8.js

for (var i = 0; i < 3; i++) setTimeout(() => console.log("var:", i), 0);
for (let j = 0; j < 3; j++) setTimeout(() => console.log("let:", j), 0);

⌨️ Terminal

node q8.js

🖥️ Output

var: 3
var: 3
var: 3
let: 0
let: 1
let: 2

var creates one variable shared by all iterations, so every callback sees its final value 3. let creates a new binding per iteration, so each closure captures its own value.

Advertisement

Q9. Scenario: shared test data gets corrupted between tests. How do you prevent it?

Never mutate shared fixtures: create fresh data per test (factory or builder functions), freeze constants, copy with structuredClone when nested data must change, and prefer non-mutating methods (toSorted, map, spread). Playwright fixtures help by giving each test its own instance.

📄 q9.js

const FIXTURE = Object.freeze({ users: Object.freeze(["admin", "tester"]) });
const makeUsers = () => structuredClone({ users: [...FIXTURE.users] });

const test1 = makeUsers();
test1.users.push("guest");
const test2 = makeUsers();
console.log(test1.users, test2.users);
try { FIXTURE.users.push("hacker"); } catch (e) { console.log("fixture protected:", e.name); }

⌨️ Terminal

node q9.js

🖥️ Output

[ 'admin', 'tester', 'guest' ] [ 'admin', 'tester' ]
fixture protected: TypeError

Q10. What causes memory leaks in long-running JavaScript (a test runner, a dashboard), and how do you find them?

Unbounded caches and arrays, timers never cleared, listeners added repeatedly, closures holding large objects, and references to removed DOM nodes. Find them by repeating an action and comparing heap snapshots (DevTools Memory or node --inspect), looking for object counts that only grow. Bound caches, clear intervals, remove listeners (AbortController), use WeakMap for per-object metadata.

Q11. Implement debounce and explain when to use it instead of throttle.

📄 q11.js

function debounce(fn, wait) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), wait);
  };
}
const search = debounce((q) => console.log("search for", q), 50);
search("p"); search("pl"); search("play");
setTimeout(() => search("playwright"), 100);

⌨️ Terminal

node q11.js

🖥️ Output

search for play
search for playwright

Debounce runs once after events stop (search-as-you-type, auto-save); throttle runs at most once per interval while events continue (scroll, progress updates). In tests, both mean the UI updates later: wait for the outcome, never sleep.


🏗️ Code Organisation and Frameworks

Q12. ES modules vs CommonJS: what problems have you seen?

“Cannot use import statement outside a module” (file treated as CommonJS: add "type": "module" or use .mjs), missing file extensions in ESM imports, __dirname not defined in ESM (use import.meta.dirname), and tools such as older Jest setups needing extra configuration for ESM.

Q13. Which design patterns do you use in an automation framework, and why?

Page Object Model (locators and actions in one place), factories and builders for test data, a configuration singleton read from environment variables, observer-style reporters and hooks, strategy for interchangeable login methods (UI, API, stored state), and decorators such as retry wrappers for genuinely unreliable infrastructure. Mention trade-offs: avoid giant page objects and hidden assertions.

Q14. How do you structure test data for several environments?

Non-secret settings (URLs, timeouts) in a config module keyed by an environment name from TEST_ENV; secrets in environment variables (CI secrets locally mirrored in a git-ignored .env); data created through APIs in setup and removed in teardown; unique values (timestamps or seeded generators) to avoid collisions in parallel runs.

Q15. How do you decide what to test at unit, API and UI level?

Business rules with many combinations at unit level (fast, precise); contracts and integration between services at API level; a focused set of critical user journeys end-to-end in the browser. Avoid repeating every unit case in the UI, and use API calls to set up UI tests.


🧪 Scenario Questions from Testing Interviews

Q16. A test is flaky: it fails 1 time in 20. Walk me through your investigation.

Reproduce with repetition (--repeat-each=20) and collect traces, screenshots and logs from failures. Look for the common causes: a missing await, fixed sleeps, unstable locators, shared data between parallel tests, dependence on test order, animations or debounced UI, time zones and dates, and real third-party services. Fix the cause (wait for a specific state, isolate data, mock the unstable dependency); use retries only as a temporary safety net and track flaky tests visibly.

Q17. The UI shows a wrong total. How do you narrow down whether it is a front-end or back-end bug?

Check the network response in DevTools or with page.waitForResponse: if the API already returns the wrong total, it is a back-end bug; if the API is correct and the display is wrong, the bug is in front-end calculation or formatting (rounding, currency, locale, string concatenation). Then reproduce it at the lowest level with a unit or API test.

Q18. How do you test something that depends on the current date or time?

Make “now” controllable: inject it as a parameter in code, use fake timers in unit tests (mock.timers, vi.useFakeTimers) and page.clock in Playwright, and fix the browser’s time zone and locale in the config. Generate dates relative to a fixed “today” and cover boundaries: midnight, month ends, leap years, daylight-saving changes.

Q19. How do you handle authentication efficiently in a large suite?

Log in once per role (through the UI or, faster, the API) in a setup project, save the storage state (cookies and localStorage), and reuse it in tests. Keep one UI login test so the login page itself stays covered. Use separate accounts for parallel workers if tests change user state.

Q20. A teammate wants to add retries to every API call in the framework. What is your response?

Retries are right for transient network failures (connection reset, 503 during deployment) and must be logged, but retrying everything hides real bugs, can repeat non-idempotent actions (creating two orders) and slows failure feedback. I would add a retry decorator only for idempotent requests and specific error types, with a small limit and backoff, and report every retry.


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. What does this print, and why?

const obj = { n: 1, get() { return () => this.n; } };
const f = obj.get;
console.log(obj.get()());
console.log(f()());
Show answer

📄 p1.js

const obj = { n: 1, get() { return () => this.n; } };
const f = obj.get;
console.log(obj.get()());
try { console.log(f()()); } catch (e) { console.log(`${e.name}: ${e.message}`); }

🖥️ Output

1
undefined

The arrow function takes this from get. Called as obj.get(), that is obj, so it returns 1. Called detached as f(), this is undefined in a module or strict mode and the global object in sloppy scripts; here (a CommonJS script) this.n on globalThis is undefined.

Q2. Implement withTimeout(promise, ms) that rejects with “Timed out after X ms” if the promise is too slow.

Show answer

📄 p2.mjs

function withTimeout(promise, ms) {
  let timer;
  const timeout = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`Timed out after ${ms} ms`)), ms); });
  return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
const slow = new Promise((r) => setTimeout(() => r("done"), 200));
const fast = new Promise((r) => setTimeout(() => r("fast done"), 10));
console.log(await withTimeout(fast, 100));
await withTimeout(slow, 50).catch((e) => console.log(e.message));

🖥️ Output

fast done
Timed out after 50 ms

Q3. Implement retry(fn, attempts) for async functions, with a short wait between attempts.

Show answer

📄 p3.mjs

async function retry(fn, attempts = 3, delayMs = 10) {
  for (let i = 1; ; i++) {
    try { return await fn(); }
    catch (e) {
      if (i >= attempts) throw e;
      console.log(`attempt ${i} failed: ${e.message}`);
      await new Promise((r) => setTimeout(r, delayMs * i));
    }
  }
}
let calls = 0;
console.log(await retry(async () => { if (++calls < 3) throw new Error("503"); return "ok"; }));

🖥️ Output

attempt 1 failed: 503
attempt 2 failed: 503
ok

Q4. Group test results by status into an object of arrays of names.

Show answer

📄 p4.js

const results = [{ name: "a", status: "passed" }, { name: "b", status: "failed" }, { name: "c", status: "passed" }];
const grouped = Object.fromEntries(Object.entries(Object.groupBy(results, (r) => r.status)).map(([k, v]) => [k, v.map((r) => r.name)]));
console.log(grouped);

🖥️ Output

{ passed: [ 'a', 'c' ], failed: [ 'b' ] }

Q5. Run 5 async tasks with at most 2 at a time and return results in the original order.

Show answer

📄 p5.mjs

async function pool(tasks, limit) {
  const results = [];
  let next = 0;
  const worker = async () => { while (next < tasks.length) { const i = next++; results[i] = await tasks[i](); } };
  await Promise.all(Array.from({ length: limit }, worker));
  return results;
}
const task = (v, ms) => () => new Promise((r) => setTimeout(() => r(v), ms));
console.log(await pool([task("a", 30), task("b", 5), task("c", 20), task("d", 5), task("e", 1)], 2));

🖥️ Output

[ 'a', 'b', 'c', 'd', 'e' ]

Q6. Scenario: tests pass locally with 1 worker but fail randomly with 4 workers in CI. What is the most likely class of problem and how do you confirm it?

Show answer

Shared state between tests running in parallel: the same user account, the same records, a shared file or a global counter. Confirm by running locally with the same number of workers and with --repeat-each, and by checking whether failing tests touch the same data. Fix by giving each test or worker its own data (unique ids, per-worker accounts, fresh contexts) and removing order dependencies.


🧠 MCQ Quiz: Interview Questions: 3-5 Years

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. In strict mode, what is this inside a plain function call fn()?
  2. What do arrow functions use for this?
  3. Which runs first after synchronous code finishes?
  4. Which combinator never rejects?
  5. What does var in a for loop with setTimeout callbacks typically print?
  6. How do you run independent async calls faster?
  7. Where are class methods stored?
  8. Which is a good reason to retry an API call?
  9. What is the best first step for a flaky test?
  10. How should a test that depends on today’s date be written?

💼 Interview Questions and Answers

Q1. Describe the architecture of the last automation framework you worked on.

Structure the answer: language and runner (TypeScript + Playwright Test), layers (tests, page objects or components, fixtures, API clients, test-data builders, utilities), configuration per environment, authentication strategy (storageState), reporting (HTML, JUnit, traces), CI (sharding, retries policy, artifacts), and what you improved (flakiness rate, runtime, coverage). Have numbers ready: number of tests, runtime, flaky rate.

Q2. How do you review a pull request that adds new tests?

Check that each test has a clear purpose and name, independent data, stable locators, no fixed sleeps, all awaits in place, assertions that check behaviour (not just “no error”), proper clean-up, reasonable runtime, and that it fails for the right reason (ideally seen failing once). Also check duplication with existing tests and whether the check belongs at a lower level.

Q3. What has been the hardest bug you investigated?

Choose a real example with technical depth: a race condition, a time-zone bug, a memory leak, or a flaky test with a subtle cause. Explain the symptoms, the hypotheses you tested, the tools (traces, network logs, heap snapshots, minimal reproductions), the root cause and the fix, plus the test you added so it cannot return.

Q4. How do you keep a large test suite fast?

Push checks down the pyramid, run tests in parallel and shard across CI machines, set up state through APIs and stored sessions instead of the UI, avoid sleeps, reuse expensive setup with worker-scoped fixtures, run a smoke subset on every commit and the full suite on merge or nightly, and monitor slowest tests and flaky rates over time.


Advertisement

❓ Frequently Asked Questions

🤔 How is a 3–5 year interview different from a fresher interview?

Fewer definitions, more “why” and “how would you”: design decisions, debugging stories, trade-offs and code you can write and explain under time pressure.

🤔 Should I expect live coding?

Usually yes: a small utility (debounce, retry, groupBy, deep clone), an async problem, or a test for a given page. Practise in a plain editor and explain while you type.

🤔 How do I prepare for scenario questions?

Collect 5–6 real stories from your work (a flaky test, a production bug, a framework improvement) and practise telling each in 2 minutes with the problem, your actions and the measurable result.

🤔 What should I read next?

The senior lesson in this module for tricky output questions and deeper topics, and the Playwright course for framework-level questions.


🏁 Summary

  • this depends on the call site; arrows inherit it; detached methods lose it.
  • Know the event loop order (sync, microtasks, macrotasks) and when to use each Promise combinator.
  • Run independent async work in parallel with limits; handle rejections explicitly.
  • Prevent shared mutable state and leaks; know debounce, throttle, retry and timeouts by heart.
  • Answer scenario questions with evidence-driven debugging and clear trade-offs about test levels, data, auth and retries.

Next, continue with Lesson 77: Interview Questions: Senior.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in