‍25 JavaScript Interview Questions for Automation Testers With Answers

Ravi Teja

November 18, 2026

•

5 mins

A Playwright test clicks Save and immediately checks for a confirmation message. It passes locally but fails in CI. How would you tell whether the test forgot to await an action, checked the UI too early, or exposed a real product bug?

That is the kind of problem JavaScript interview questions for automation testers can help you prepare for. This guide covers 25 questions and answers for QA engineers, freshers, and SDET candidates. You’ll start with language fundamentals, work through coding questions using test data, and finish with Playwright scenarios involving UI updates, API responses, and flaky tests.

Beginner JavaScript Interview Questions for Freshers

1. What is the difference between var, let, and const?

var is scoped to its enclosing function when declared inside one. let and const are block-scoped. You can reassign a let binding, while a const binding stays fixed after initialization. Object properties can still change.

In test code, declare selectors, expected values, and references with const. Use let for values you intentionally reassign, such as a retry counter.

2. What is hoisting in JavaScript?

JavaScript creates bindings before it executes the statements in a scope. A var binding starts with the value undefined. A let or const binding stays uninitialized until execution reaches its declaration. Accessing it earlier throws a ReferenceError. That interval is called the temporal dead zone.

For example, logging status before var status = 'ready' prints undefined in a fresh scope. Using let in the same example throws.

3. What is the difference between == and ===?

== can convert the types of its operands before comparison. === compares without type coercion. Therefore, 200 == '200' is true, while 200 === '200' is false.

If an API contract defines statusCode as a number, a strict check can catch a response that sends it as a string.

4. What is the difference between null, undefined, and a missing property?

null commonly represents an explicitly empty value. Reading an absent object property returns undefined. An object can also contain a property whose value is explicitly undefined. Use Object.hasOwn(object, key) to distinguish the two cases. In JSON, a payload can include a property with null or omit the property.

That distinction matters when an API requires middleName: null even if the user has no middle name.

5. When should you use the nullish coalescing operator?

Use ?? when a default should apply only to null or undefined. The || operator also falls back for falsy values such as 0, false, and an empty string. For example, 0 ?? 3 returns 0, while 0 || 3 returns 3. A test configuration may use zero retries deliberately.

6. What is the difference between map, filter, and find?

map() transforms every element and returns a new array. filter() returns all elements that meet a condition. find() returns the first matching element or undefined.

In a test report, use filter() to collect failed cases, map() to extract their IDs, and find() to locate a specific case by ID.

7. Does the spread operator create a deep copy?

Spreading an object copies its own enumerable properties into a new object. Nested objects remain shared by reference. If a user fixture contains a nested preferences object, copy that object before changing its fields for a test.

const template = { preferences: { locale: 'en' } };
const user = {
  ...template,
  preferences: { ...template.preferences, locale: 'fr' },
};

console.log(template.preferences.locale); // en

8. How does optional chaining help when reading a response?

Optional chaining returns undefined when the value immediately before ?. is null or undefined. For example, payload.user?.address?.city works when payload exists but user or address is absent. If the API contract requires a city, follow that read with an assertion so missing data still fails the test.

Intermediate JavaScript Interview Questions on Promises and Async/Await

These async/await interview questions in JavaScript cover execution order, error handling, and when test operations can safely run together. MDN guide to using promises

9. What is a closure?

A closure lets a function access bindings from its enclosing scope after that scope has finished executing. For example, const hasStatus = status => result => result.status === status; returns a predicate that retains access to the supplied status. You can then use results.filter(hasStatus('failed')) to reuse the same rule with different statuses.

10. How do arrow functions handle this?

Arrow functions use this from the surrounding scope. With a regular function, the call determines the receiver in common cases such as pageObject.open(). If a page object method reads this.page, you can define it as a regular class method and call it through the instance. If you pass the method as a callback, preserve its receiver with a wrapper such as () => pageObject.open().

11. What is a Promise, and what does await do?

A Promise represents a value that can become available later or an error that can occur. It starts pending and settles as fulfilled or rejected. await pauses the surrounding async function, then gives you the fulfilled value or throws the rejection reason. Other work can continue while that function waits.

For a Playwright test, await button.click() waits for the click action to complete. A separate assertion can verify the resulting state.

12. How do Promise.all and Promise.allSettled differ?

Promise.all() fulfills when every input fulfills and rejects as soon as an input rejects. It preserves input order in the returned values and leaves other operations running if one fails. Use it when a test needs all results from independent operations.

Promise.allSettled() waits for every result and gives each one a status. It suits cleanup reporting when several independent cleanup calls can fail and you need to record every outcome.

13. What is the output order in this JavaScript interview question?

console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');

The output is A, D, C, B. Synchronous statements run first. The Promise callback runs as a microtask after the call stack empties. The timer callback runs in a later task. In JavaScript output-based interview questions, explain where each callback is scheduled before giving the order.

14. Why can async callbacks inside forEach cause an automation bug?

forEach() ignores the returned Promises, so the surrounding code can continue before the callbacks finish. Use a for...of loop with await when order matters. For independent work that can run together, use await Promise.all(items.map(fn)). For example, clicking a series of controls on one Playwright page generally needs a sequence, because each action can change what is shown next.

15. When should you use try, catch, and finally in test automation?

Use try around operations you want to monitor, catch to add failure details or handle a specific error, and finally for cleanup. If you catch an assertion failure to collect evidence, rethrow it so the runner records the failure. In a shared test framework, fixtures or teardown hooks can centralize cleanup. Keep the original failure visible when cleanup also fails.

16. How do you choose between sequential and concurrent async operations?

Run actions sequentially when one depends on the result or state change from another. For example, sign in before opening an authenticated settings page. Run independent tasks concurrently when they can safely overlap, such as fetching two read-only API resources that use separate state. Confirm that concurrent tasks can safely share any test account, records, or browser page they use.

JavaScript Coding Interview Questions for Testers

17. How do you extract the IDs of failed tests?

First filter by the exact status, then transform each selected result into its ID.

function failedTestIds(results) {
  return results
    .filter(result => result.status === 'failed')
    .map(result => result.id);
}

// [{ id: 'T1', status: 'passed' }, { id: 'T2', status: 'failed' }]
// returns ['T2']

Check an empty array and a report with all passing tests. Both should return an empty array.

18. How do you find duplicate test case IDs?

Use one set to track IDs already seen and another to collect duplicates once each. This returns duplicate IDs in the order in which they first repeat.

function duplicateIds(ids) {
  const seen = new Set();
  const duplicates = new Set();

  for (const id of ids) {
    if (seen.has(id)) duplicates.add(id);
    seen.add(id);
  }

  return [...duplicates];
}

console.log(duplicateIds(['T1', 'T2', 'T1', 'T2', 'T1']));
// ['T1', 'T2']

19. How do you count test results by status?

A Map can count every observed status without a fixed list of categories. Define the allowed statuses separately if the report format requires validation.

function countByStatus(results) {
  const counts = new Map();

  for (const { status } of results) {
    counts.set(status, (counts.get(status) ?? 0) + 1);
  }

  return Object.fromEntries(counts);
}

// [{ status: 'passed' }, { status: 'failed' }, { status: 'passed' }]
// returns { passed: 2, failed: 1 }

20. How do you check whether an API payload contains mandatory fields?

Test for property presence separately from value validity. The helper below checks top-level fields on a JSON object. Values like false, 0, and null count as present. Add type or value assertions where the contract requires them.

function missingFields(payload, requiredFields) {
  return requiredFields.filter(field => !Object.hasOwn(payload, field));
}

console.log(missingFields({ active: false, balance: 0 }, ['active', 'balance', 'id']));
// ['id']

For example, if id must be a nonempty string, check its presence, type, and length.

Playwright JavaScript Interview Questions for Automation Testers

21. How do you fix an assertion that reads the UI too early?

When the UI updates asynchronously, use a web-first assertion. await expect(locator).toHaveText(...) keeps checking the locator until the expected text appears or the assertion times out. A single await locator.textContent() followed by a value assertion captures the text at the time it is read.

await page.getByRole('button', { name: 'Save' }).click();
await expect(page.getByRole('status')).toHaveText('Changes saved');

This example assumes the confirmation is exposed as a status region. Playwright assertions

22. How do you wait for the API response triggered by a click?

Start listening before the click so the test can capture a fast response. Match the endpoint and method, then assert the status separately. This way, an error response from the expected endpoint produces an assertion failure with its actual status.

const responsePromise = page.waitForResponse(response =>
  new URL(response.url()).pathname === '/api/profile' &&
  response.request().method() === 'PATCH'
);

const [response] = await Promise.all([
  responsePromise,
  page.getByRole('button', { name: 'Save' }).click(),
]);

expect(response.status()).toBe(200);
await expect(page.getByRole('status')).toHaveText('Changes saved');

Use the status your endpoint specifies. If several requests share a path and method, narrow the matcher using a resource ID or request data. Playwright network events

23. What do you do when a locator matches two Save buttons?

Scope the locator to the relevant component. For example, use page.getByRole('dialog', { name: 'Edit profile' }).getByRole('button', { name: 'Save' }) when the intended button is inside a named dialog. Check the accessible roles and names if the scoped locator still fails. Selecting .first() only makes sense when first position is part of the expected behavior. Playwright locators

24. How do you stop tests from changing each other’s data?

Playwright Test gives each test an isolated browser context by default, which helps isolate cookies and browser storage. Backend records can still be shared. Create unique test data through fixtures or setup APIs, keep test cases independent, and clean up the records each test owns. If two workers edit the same profile, a fresh browser context on each worker still leaves both requests writing to the same account. Playwright browser contexts

25. How would you debug a test that fails only in CI?

Inspect the Playwright trace, failed assertion, and relevant network activity. Then reproduce the CI browser, environment settings, and worker count where practical. Check for missing await calls, ambiguous locators, shared data, and actual server errors.

For example, if the trace shows the save request returned HTTP 500 before the confirmation failed to appear, investigate the failing request and backend logs. If the response succeeds and the confirmation appears after the test reads the page, inspect the assertion and its timing. Playwright Trace Viewer

How to Prepare for a JavaScript Automation Interview

  1. Explain the concept in one or two sentences and give a small example from a test.
  2. Predict the output of one Promise and timer example, then run it and explain any difference.
  3. Practice transforming a test report with arrays, sets, and maps. Include empty inputs and duplicate data.
  4. Write one Playwright test that checks a save response and verifies what the user sees.
  5. Explain what evidence you would collect if that test fails only in CI.

Key Takeaways

  • Start with scope, equality, arrays, and objects. These concepts show up in test fixtures, API assertions, and reusable helpers.
  • Practice predicting JavaScript execution order. It helps you spot missing await calls and explain race conditions.
  • Use a Playwright assertion that retries when the UI updates asynchronously. Register a network wait before the action that triggers the request.
  • When answering a scenario question, explain the expected behavior, the failure you would investigate, and the evidence that would confirm it.

Conclusion

Start with the JavaScript concepts you use every day in test automation. Then practice applying them to a single workflow with a UI action, an API response, and a visible result. That gives you a concrete example for questions about promises, assertions, and debugging.

Continue with Frugal Testing’s Playwright guide to end-to-end testing and guide to API automation with Playwright. If your team needs help building or stabilizing a regression suite, explore Frugal Testing’s automation testing services.

Frequently Asked Questions

Is JavaScript required for automation testing?

The language depends on the tool and team. Cypress tests use JavaScript or TypeScript. Playwright supports several languages, including JavaScript, Python, Java, and .NET. For a Playwright Test or Cypress role, JavaScript fundamentals are valuable even if the team writes its tests in TypeScript.

What JavaScript topics should freshers prepare for QA interviews?

Start with variables, scope, strict equality, arrays, objects, promises, and async/await. Practice reading a JSON response, filtering a test report, and predicting the order of synchronous code, Promise callbacks, and timers.

What JavaScript coding questions are useful for SDET interviews?

Practice deduplicating record IDs, grouping results, validating API fields, and coordinating asynchronous operations. Explain what your function returns for an empty input and how it handles edge cases.

Should I learn JavaScript before TypeScript for Playwright?

Start with JavaScript fundamentals, especially objects, functions, modules, and asynchronous code. Then add TypeScript to describe test fixtures and API response shapes, and to catch incompatible values earlier in development.

How do you answer a flaky test interview question?

Describe the expected behavior, identify where the test can race with the application, and explain what you would inspect in the trace. Then show how you would verify the relevant UI or network state and repeat the test under CI-like conditions.

Ravi Teja

Rupesh Garg

Founder and principal architect at Frugal Testing, a SaaS startup in the field of performance testing and scalability. Possess almost 2 decades of diverse technical and management experience with top Consulting Companies (in the US, UK, and India) in Test Tools implementation, Advisory services, and Delivery. I have end-to-end experience in owning and building a business, from setting up an office to hiring the best talent and ensuring the growth of employees and business.

Our blog

Latest blog posts

Discover the latest in software testing: expert analysis, innovative strategies, and industry forecasts
Software Testing

‍25 JavaScript Interview Questions for Automation Testers With Answers

Ravi Teja
November 18, 2026
•
5 mins
Software Testing

What is contract testing? A Complete Guide for Beginners

Yeshwanth Varma
November 18, 2026
•
10 mins
API Testing
Software Testing

Postman Vs APIdog: A comparative analysis

Tumpilli Pavan
November 17, 2026
•
10 mins