JavaScript Promises Explained: States, then, catch, finally and Chaining

A promise is an object that represents a value you will get later: the result of an API call, a file read or a page navigation. Promises replaced nested callbacks with flat, chainable code, and they are the foundation of async/await and of every Playwright command, since page.click(), page.goto() and expect() all return promises. In this lesson you will learn how promises work, how to create and consume them, how errors flow through a chain, and the mistakes that cause unhandled rejections and flaky tests.

📖 What You’ll Learn: what a promise is, the three states, creating promises with new Promise, resolve and reject, consuming them with then, catch and finally, chaining and returning values or promises, error propagation through a chain, Promise.resolve and Promise.reject, promisifying callback APIs, common mistakes (forgetting return, nesting, missing catch), unhandled rejections, and promises in tests.


🤝 What Is a Promise?

Definition: a promise is an object representing the eventual result of an asynchronous operation. It is a placeholder: you get it immediately, and it later becomes either a value or an error.

A promise is always in one of three states:

StateMeaning
pendingThe operation is still running
fulfilledIt finished successfully and has a value
rejectedIt failed and has a reason (usually an Error)

Once a promise is fulfilled or rejected it is settled, and it never changes state again.

📄 states.js

const util = require("node:util");

const pending = new Promise(() => {});
const fulfilled = Promise.resolve(42);
const rejected = Promise.reject(new Error("failed"));
rejected.catch(() => {});      // handle it so Node.js does not report it

console.log(util.inspect(pending));
console.log(util.inspect(fulfilled));
console.log(util.inspect(rejected).split("\n").slice(0, 2).map((s) => s.trim()).join(" "), "}");

⌨️ Terminal

node states.js

🖥️ Output

Promise { <pending> }
Promise { 42 }
Promise { <rejected> Error: failed }

🏗️ Creating a Promise

The Promise constructor takes an executor function that receives two functions: call resolve(value) on success and reject(error) on failure. The executor runs immediately.

📄 create.js

function fetchOrder(id) {
  return new Promise((resolve, reject) => {
    console.log(`executor runs immediately for order ${id}`);
    setTimeout(() => {
      if (id <= 0) reject(new Error(`Order ${id} not found`));
      else resolve({ id, total: 1299 });
    }, 20);
  });
}

const p = fetchOrder(451);
console.log("got a promise right away:", p instanceof Promise);
p.then((order) => console.log("fulfilled with", order));

fetchOrder(-1).catch((err) => console.log("rejected with", err.message));

⌨️ Terminal

node create.js

🖥️ Output

executor runs immediately for order 451
got a promise right away: true
executor runs immediately for order -1
fulfilled with { id: 451, total: 1299 }
rejected with Order -1 not found
  • Only the first call to resolve or reject counts; later calls are ignored.
  • Always reject with an Error object so stack traces and instanceof work.
  • If the executor throws, the promise is rejected automatically.

📥 Consuming: then, catch and finally

MethodRuns whenTypical use
.then(onFulfilled)The promise is fulfilledUse the value
.catch(onRejected)The promise is rejectedHandle or report the error
.finally(onSettled)Either wayCleanup: hide a spinner, close a connection

📄 then-catch.js

const delay = (ms) => new Promise((r) => setTimeout(r, ms));

function login(user) {
  return delay(10).then(() => {
    if (!user) throw new Error("username is required");
    return { user, token: "t-123" };
  });
}

login("asha")
  .then((session) => console.log("logged in:", session.token))
  .catch((err) => console.log("error:", err.message))
  .finally(() => console.log("cleanup after first login"));

login("")
  .then((session) => console.log("logged in:", session.token))
  .catch((err) => console.log("error:", err.message))
  .finally(() => console.log("cleanup after second login"));

⌨️ Terminal

node then-catch.js

🖥️ Output

logged in: t-123
cleanup after first login
error: username is required
cleanup after second login

.then callbacks always run asynchronously (as microtasks), even when the promise is already settled. See the Event Loop lesson for the exact order.


⛓️ Chaining Promises

Every call to .then returns a new promise, which is what makes chains possible. What the callback returns decides what the next step receives:

  • Return a value: the next .then receives that value.
  • Return a promise: the chain waits for it and passes on its result.
  • Return nothing: the next step receives undefined.
  • Throw: the chain skips to the next .catch.

📄 chain.js

const delay = (ms, value) => new Promise((r) => setTimeout(() => r(value), ms));

const api = {
  login: (user) => delay(10, { token: `token-for-${user}` }),
  getCart: (token) => delay(10, { token, items: [{ price: 499 }, { price: 1299 }] }),
  checkout: (cart) => delay(10, { orderId: 451, total: cart.items.reduce((s, i) => s + i.price, 0) }),
};

api.login("asha")
  .then((session) => api.getCart(session.token))   // return a promise: the chain waits
  .then((cart) => api.checkout(cart))
  .then((order) => `Order ${order.orderId} total ₹${order.total}`)  // return a value
  .then((message) => console.log(message))
  .catch((err) => console.log("checkout flow failed:", err.message));

⌨️ Terminal

node chain.js

🖥️ Output

Order 451 total ₹1798

Compare this flat chain with the nested callback version in the Callbacks and Timers lesson: one level of indentation and one .catch for the whole flow.


🚨 Error Propagation

An error (a rejection or a thrown exception) skips every following .then until it reaches a .catch. After a .catch handles it, the chain continues normally with the value the .catch returned:

📄 propagation.js

Promise.resolve(1)
  .then((n) => { console.log("step 1:", n); return n + 1; })
  .then((n) => { throw new Error(`step 2 failed with ${n}`); })
  .then(() => console.log("step 3: skipped"))
  .catch((err) => { console.log("caught:", err.message); return "fallback"; })
  .then((value) => console.log("chain continues with:", value));

⌨️ Terminal

node propagation.js

🖥️ Output

step 1: 1
caught: step 2 failed with 2
chain continues with: fallback

💡 Tip: Put one .catch at the end of a chain to handle failures from any step. Add a .catch in the middle only if you can genuinely recover, such as using cached data when a request fails.


🧰 Promise.resolve, Promise.reject and promisify

Promise.resolve(value) and Promise.reject(error) create already-settled promises, which is useful for tests, defaults and functions that must always return a promise:

📄 resolve-reject.js

function getConfig(useCache) {
  if (useCache) return Promise.resolve({ env: "qa", cached: true });   // still a promise
  return new Promise((r) => setTimeout(() => r({ env: "qa", cached: false }), 10));
}

getConfig(true).then((c) => console.log("cache:", c));
getConfig(false).then((c) => console.log("fresh:", c));
Promise.reject(new Error("not allowed")).catch((e) => console.log("rejected:", e.message));

⌨️ Terminal

node resolve-reject.js

🖥️ Output

cache: { env: 'qa', cached: true }
rejected: not allowed
fresh: { env: 'qa', cached: false }

Old callback-based APIs can be wrapped into promises with util.promisify, or by hand. Most Node.js modules also have a promise version already, such as node:fs/promises:

📄 promisify.js

const fs = require("node:fs");
const util = require("node:util");
const fsp = require("node:fs/promises");

fs.writeFileSync("note.txt", "hello promises");

const readFileAsync = util.promisify(fs.readFile);
readFileAsync("note.txt", "utf8").then((text) => console.log("promisify:", text));

fsp.readFile("note.txt", "utf8").then((text) => console.log("fs/promises:", text));

⌨️ Terminal

node promisify.js

🖥️ Output

promisify: hello promises
fs/promises: hello promises

⚠️ Common Promise Mistakes

1. Forgetting to return inside then

📄 no-return.js

const delay = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));

delay(10, 1)
  .then((n) => { delay(10, n + 1); })     // promise created but not returned
  .then((n) => console.log("without return:", n));

delay(10, 1)
  .then((n) => delay(10, n + 1))          // returned: the chain waits for it
  .then((n) => console.log("with return:", n));

⌨️ Terminal

node no-return.js

🖥️ Output

without return: undefined
with return: 2

Without return, the next step does not wait and receives undefined, and any error in the forgotten promise is lost.

2. Nesting then inside then

Writing a().then((x) => { b(x).then((y) => { c(y).then(...) }) }) rebuilds callback hell. Return the inner promise and chain at the top level instead.

3. No catch: unhandled rejections

A rejected promise that nobody handles is an unhandled rejection. Since Node.js 15, it crashes the process:

📄 unhandled.js

function deleteUser(id) {
  return Promise.reject(new Error(`User ${id} is protected and cannot be deleted`));
}

deleteUser(1);              // no .catch and no await
console.log("this line still runs first");

⌨️ Terminal

node unhandled.js

🖥️ Output

this line still runs first
/home/you/js-course/unhandled.js:2
  return Promise.reject(new Error(`User ${id} is protected and cannot be deleted`));
                        ^

Error: User 1 is protected and cannot be deleted
    at deleteUser (/home/you/js-course/unhandled.js:2:25)
    at Object.<anonymous> (/home/you/js-course/unhandled.js:5:1)

Node.js v26.13.0

⚠️ Watch out: Every promise chain needs a .catch at the end, or must be awaited inside a try. In test code, an unhandled rejection can crash a worker and hide which test caused it.


🧪 Tester Scenario: Promise-Based Test Steps

Each step of a test returns a promise; chaining runs them in order, a failure in any step skips the rest and is reported once, and finally always cleans up the test data:

📄 test-steps.js

const delay = (ms) => new Promise((r) => setTimeout(r, ms));
const log = [];

const step = (name, fn) => () => delay(5).then(() => {
  log.push(name);
  return fn();
});

const createUser = step("create user", () => ({ id: 77 }));
const addToCart = step("add to cart", () => ({ items: 1 }));
const payWithCard = step("pay with card", () => { throw new Error("Payment API returned 502"); });
const verifyOrder = step("verify order", () => true);

createUser()
  .then(addToCart)
  .then(payWithCard)
  .then(verifyOrder)
  .then(() => console.log("TEST PASSED"))
  .catch((err) => console.log(`TEST FAILED at step ${log.length}: ${err.message}`))
  .finally(() => console.log("steps run:", log.join(" -> "), "| cleanup: delete user 77"));

⌨️ Terminal

node test-steps.js

🖥️ Output

TEST FAILED at step 3: Payment API returned 502
steps run: create user -> add to cart -> pay with card | cleanup: delete user 77

In practice you will write this with async/await (lesson 50), which reads like synchronous code, but it is built on exactly these promise rules.


📝 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. Create a function wait(ms) that returns a promise resolving after ms milliseconds, and use it to print "ready" after 20 ms.

Show answer

📄 practice1.js

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
wait(20).then(() => console.log("ready"));

🖥️ Output

ready

Q2. Write checkAge(age) that returns a promise resolving with "allowed" for 18+ and rejecting with an Error otherwise. Test with 21 and 15.

Show answer

📄 practice2.js

const checkAge = (age) => new Promise((resolve, reject) =>
  age >= 18 ? resolve("allowed") : reject(new Error(`age ${age} is under 18`)));

checkAge(21).then(console.log).catch((e) => console.log(e.message));
checkAge(15).then(console.log).catch((e) => console.log(e.message));

🖥️ Output

allowed
age 15 is under 18

Q3. Chain three steps: start with 2, double it, add 10, then print the result.

Show answer

📄 practice3.js

Promise.resolve(2)
  .then((n) => n * 2)
  .then((n) => n + 10)
  .then((n) => console.log(n));

🖥️ Output

14

Q4. Predict the output, then run it.

Promise.resolve("A")
  .then((v) => { throw new Error(v + "B"); })
  .then(() => console.log("C"))
  .catch((e) => e.message + "D")
  .then((v) => console.log(v))
  .finally(() => console.log("E"));
Show answer

📄 practice4.js

Promise.resolve("A")
  .then((v) => { throw new Error(v + "B"); })
  .then(() => console.log("C"))
  .catch((e) => e.message + "D")
  .then((v) => console.log(v))
  .finally(() => console.log("E"));

🖥️ Output

ABD
E

The thrown error skips “C”, the catch returns “ABD” which the next then prints, and finally always runs.

Q5. Convert this callback function to return a promise using util.promisify.

function getStatus(url, cb) {
  setTimeout(() => cb(null, url.includes("health") ? 200 : 404), 5);
}
Show answer

📄 practice5.js

const util = require("node:util");
function getStatus(url, cb) {
  setTimeout(() => cb(null, url.includes("health") ? 200 : 404), 5);
}
const getStatusAsync = util.promisify(getStatus);
getStatusAsync("/health").then((s) => console.log("status", s));

🖥️ Output

status 200

Q6. This chain prints undefined. Fix it so it prints "token-123".

const login = () => new Promise((r) => setTimeout(() => r("token-123"), 10));
Promise.resolve()
  .then(() => { login(); })
  .then((token) => console.log(token));
Show answer

📄 practice6.js

const login = () => new Promise((r) => setTimeout(() => r("token-123"), 10));
Promise.resolve()
  .then(() => login())
  .then((token) => console.log(token));

🖥️ Output

token-123

Return the promise from the callback (the arrow function without braces returns it implicitly).


🧠 MCQ Quiz: Promises

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 are the three states of a promise?
  2. When does the executor function of new Promise run?
  3. What does .then() return?
  4. If a then callback returns a promise, what does the next then receive?
  5. What happens when a then callback throws?
  6. When does finally run?
  7. Since Node.js 15, what does an unhandled promise rejection do by default?
  8. What is wrong with .then(() => { fetchData(); })?
  9. What does Promise.resolve(5) create?
  10. Which converts an error-first callback function into a promise-returning one?

💼 Interview Questions and Answers

Q1. What is a promise and why was it introduced?

A promise is an object representing the eventual result of an asynchronous operation, in one of three states: pending, fulfilled or rejected. Promises replaced nested callbacks with composable chains, give one consistent way to handle errors (rejections propagate to .catch), and can be combined (Promise.all etc.). They are the basis of async/await.

Q2. What is the difference between returning and not returning inside then?

Returning a value passes it to the next .then; returning a promise makes the chain wait and pass on its result; throwing rejects the chain. Not returning means the next step runs immediately with undefined, and any promise created inside is “floating”: its errors are not caught by the chain’s .catch.

Q3. Predict the output.

📄 predict.js

const p = new Promise((resolve) => {
  console.log(1);
  resolve(2);
  console.log(3);
});
p.then((v) => console.log(v));
console.log(4);

⌨️ Terminal

node predict.js

🖥️ Output

1
3
4
2

The executor runs synchronously, so 1 and 3 print immediately (resolve does not stop the executor). Then the synchronous 4, and finally the then callback prints 2 as a microtask.

Q4. What is an unhandled promise rejection and how do you prevent it?

It is a rejected promise with no rejection handler attached by the time the microtask queue is processed. Node.js emits unhandledRejection and, by default since v15, terminates the process. Prevent it by ending every chain with .catch, awaiting promises inside try...catch, not leaving “floating” promises (lint rule no-floating-promises), and logging in a global process.on("unhandledRejection") handler as a last resort.


❓ Frequently Asked Questions

🤔 Can a promise be resolved twice?

No. The first resolve or reject settles it; later calls are ignored.

🤔 Are promises asynchronous?

The executor runs synchronously, but then, catch and finally callbacks always run asynchronously as microtasks.

🤔 Should I use then/catch or async/await?

Use async/await for most code; it is easier to read and debug. then chains are still useful for short transformations and for running code without making the surrounding function async.

🤔 Can I cancel a promise?

Not directly. Cancel the underlying operation with an AbortController signal where the API supports it, such as fetch and Node.js timers.


🏁 Summary

  • A promise represents a future value and is pending, fulfilled or rejected; once settled it never changes.
  • Create promises with new Promise((resolve, reject) => ...), Promise.resolve and Promise.reject.
  • Consume them with then, catch and finally; each then returns a new promise, which enables chaining.
  • Errors skip to the next catch; always return promises inside then and end chains with catch.
  • Unhandled rejections crash Node.js; promisify callback APIs with util.promisify or use built-in promise modules.

Next, continue with Lesson 49: Promise.all, allSettled, race, any.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Event Loop Explained: Call Stack, Task Queue and Microtasks

JavaScript runs your code on a single thread, yet a Node.js server handles thousands of requests and a Playwright test waits for pages, clicks and network calls without freezing. The mechanism behind this is the event loop. Understanding it explains the order in which callbacks and promises run, why setTimeout(fn, 0) is not instant, why a long loop freezes everything, and why a missing await makes tests flaky. This lesson builds that understanding step by step, with outputs you can predict.

📖 What You’ll Learn: what single-threaded means, the call stack, how the runtime (browser or Node.js) does slow work in the background, the task (macrotask) queue, the microtask queue for promises, the order the event loop follows, setTimeout(fn, 0), process.nextTick and queueMicrotask, blocking the event loop, starving it with microtasks, and what this means for writing reliable tests.


🧵 Single-Threaded, but Not Blocking

Definition: JavaScript is single-threaded: one piece of your code runs at a time, on one call stack. Slow operations (timers, network requests, file reads, browser events) are handed to the runtime (the browser or Node.js), which does them in the background. When one finishes, its callback is put in a queue. The event loop takes callbacks from the queues and runs them, but only when the call stack is empty.

📄 basics.js

console.log("1. start");

setTimeout(() => console.log("4. timer callback"), 0);   // handed to the runtime

console.log("2. still running synchronous code");
for (let i = 0; i < 3; i++) console.log("3. loop", i);
// the stack empties here, then the event loop runs the queued timer callback

⌨️ Terminal

node basics.js

🖥️ Output

1. start
2. still running synchronous code
3. loop 0
3. loop 1
3. loop 2
4. timer callback
  • All synchronous code runs first, from top to bottom, without interruption.
  • setTimeout only schedules its callback; even with 0 ms it runs later.
  • The timer callback runs once the call stack is empty.

📚 The Call Stack

Definition: the call stack records which functions are running. Calling a function pushes it on the stack; returning pops it off. The program only does one thing at a time: whatever is on top of the stack.

📄 call-stack.js

function third() {
  console.trace("inside third");   // prints the current call stack
}
function second() { third(); }
function first() { second(); }
first();

⌨️ Terminal

node call-stack.js

🖥️ Output

Trace: inside third
    at third (/home/you/js-course/call-stack.js:2:11)
    at second (/home/you/js-course/call-stack.js:4:21)
    at first (/home/you/js-course/call-stack.js:5:20)
    at Object.<anonymous> (/home/you/js-course/call-stack.js:6:1)

Error stack traces are a snapshot of this same stack, which is why they list the most recent call first.


📬 Task Queue and Microtask Queue

There are two main queues of waiting callbacks, and they have different priorities:

QueueFilled byWhen it runs
Microtask queuePromise reactions (.then, .catch, code after await), queueMicrotaskImmediately after the current task, completely emptied before anything else
Task (macrotask) queuesetTimeout, setInterval, I/O callbacks, UI events, setImmediate (Node.js)One task per loop turn, after all microtasks are done

The event loop repeats these steps:

  1. Run the current task (at the start: your whole script) until the call stack is empty.
  2. Run all microtasks, including any new microtasks they add.
  3. In the browser, update rendering if needed.
  4. Take the next task from a task queue and go back to step 1.

📄 queues.js

console.log("A: script start");

setTimeout(() => console.log("E: timeout (task)"), 0);

Promise.resolve().then(() => console.log("C: promise then (microtask)"));
queueMicrotask(() => console.log("D: queueMicrotask (microtask)"));

console.log("B: script end");

⌨️ Terminal

node queues.js

🖥️ Output

A: script start
B: script end
C: promise then (microtask)
D: queueMicrotask (microtask)
E: timeout (task)

The promise and queueMicrotask callbacks run before the timer, even though the timer was scheduled first, because microtasks always run before the next task.


🧩 Predict the Order: A Classic Puzzle

Interviewers love this kind of question. Read it, predict the output using the rules above, then compare:

📄 puzzle.js

console.log(1);

setTimeout(() => {
  console.log(2);
  Promise.resolve().then(() => console.log(3));
}, 0);

Promise.resolve()
  .then(() => {
    console.log(4);
    setTimeout(() => console.log(5), 0);
  })
  .then(() => console.log(6));

(async () => {
  console.log(7);
  await null;
  console.log(8);
})();

console.log(9);

⌨️ Terminal

node puzzle.js

🖥️ Output

1
7
9
4
8
6
2
3
5
  1. Synchronous code: 1, then the async function runs until its first await: 7, then 9.
  2. Microtasks, in the order they were queued: the first .then logs 4 (and schedules timer 5); the code after await logs 8; the chained .then logs 6.
  3. Next task: the first timer logs 2 and queues a microtask, which runs right away: 3.
  4. Next task: the timer scheduled inside the promise logs 5.

💡 Tip: Code after await always continues as a microtask, even when the awaited value is not a promise (await null). That is why 8 comes after the synchronous 9.


⏱️ setTimeout(fn, 0) Is Not Instant

A timer’s delay is a minimum, not a guarantee. The callback runs only when its time has passed and the call stack is empty and all microtasks are done.

📄 delay.js

const start = Date.now();

setTimeout(() => {
  const waited = Date.now() - start;
  console.log(`timer asked for 10 ms, actually waited at least 200 ms: ${waited >= 200}`);
}, 10);

// Busy synchronous work for ~200 ms blocks the timer
while (Date.now() - start < 200) {}
console.log("busy loop finished");

⌨️ Terminal

node delay.js

🖥️ Output

busy loop finished
timer asked for 10 ms, actually waited at least 200 ms: true

⚠️ Watch out: Because delays are only minimums, fixed waits such as await page.waitForTimeout(2000) in tests are fragile: on a slow CI machine 2 seconds may not be enough, and on a fast one it wastes time. Wait for a condition instead (an element, a URL, a response), which is what Playwright’s auto-waiting and web-first assertions do.


🚦 process.nextTick, queueMicrotask and setImmediate (Node.js)

Node.js adds two scheduling functions of its own:

FunctionRuns
process.nextTick(fn)Before promise microtasks, as soon as the current operation finishes (Node.js only)
queueMicrotask(fn) / promise callbacksIn the microtask queue
setTimeout(fn, 0)In the timers phase of the next loop turn
setImmediate(fn)In the “check” phase, right after I/O callbacks (Node.js only)

📄 node-order.js

const fs = require("node:fs");

fs.readFile(__filename, () => {          // inside an I/O callback the order is predictable
  setTimeout(() => console.log("4. setTimeout"), 0);
  setImmediate(() => console.log("3. setImmediate"));
  Promise.resolve().then(() => console.log("2. promise"));
  process.nextTick(() => console.log("1. nextTick"));
});

⌨️ Terminal

node node-order.js

🖥️ Output

1. nextTick
2. promise
3. setImmediate
4. setTimeout

📌 Note: At the top level of a script, the order of setTimeout(fn, 0) and setImmediate(fn) is not guaranteed; it depends on how fast the process starts. Inside an I/O callback, as above, setImmediate always runs first. Do not write code that depends on this race.


🧊 Blocking the Event Loop

While synchronous code runs, nothing else can happen: no timers, no network callbacks, no clicks, no page rendering. In a browser the page freezes; in Node.js a server stops answering every user.

📄 blocking.js

let ticks = 0;
const interval = setInterval(() => ticks++, 10);   // should tick ~every 10 ms

setTimeout(() => {
  const start = Date.now();
  while (Date.now() - start < 300) {}               // 300 ms of blocking work
  console.log("blocking work done");
}, 0);

setTimeout(() => {
  clearInterval(interval);
  console.log(`ticks in ~400 ms: ${ticks} (would be about 40 without blocking)`);
  console.log("far fewer ticks than expected:", ticks < 20);
}, 400);

⌨️ Terminal

node blocking.js

🖥️ Output

blocking work done
ticks in ~400 ms: 7 (would be about 40 without blocking)
far fewer ticks than expected: true

Common causes of blocking: huge synchronous loops, JSON.parse of very large files, synchronous file APIs (fs.readFileSync) in servers, and heavy regular expressions. Fixes: use async APIs, split work into chunks, or move it to a worker thread.

Starving the loop with microtasks

Because the microtask queue is emptied completely before the next task, code that keeps adding microtasks forever starves timers just as badly as a busy loop. This is rare, but it is the reason a never-ending chain of .then calls can freeze a page.


🧪 Tester Scenario: Why a Missing await Makes Tests Flaky

A test function returns before the work it started has finished if that work is not awaited. The checks then run against stale state, or after the test is already reported as passed:

📄 missing-await.js

const delay = (ms) => new Promise((r) => setTimeout(r, ms));

const page = {
  heading: "Login",
  async clickLogin() {
    await delay(20);                 // navigation takes time
    this.heading = "Dashboard";
  },
};

async function flakyTest() {
  page.heading = "Login";
  page.clickLogin();                 // missing await!
  return page.heading === "Dashboard" ? "PASS" : `FAIL (heading is "${page.heading}")`;
}

async function correctTest() {
  page.heading = "Login";
  await page.clickLogin();           // waits for the navigation to finish
  return page.heading === "Dashboard" ? "PASS" : `FAIL (heading is "${page.heading}")`;
}

(async () => {
  console.log("without await:", await flakyTest());
  await delay(30);
  console.log("with await:   ", await correctTest());
})();

⌨️ Terminal

node missing-await.js

🖥️ Output

without await: FAIL (heading is "Login")
with await:    PASS

In a real test the “work” is a click, a navigation or an API call. If its result happens to arrive fast, the flaky version sometimes passes, which is exactly what makes these bugs hard to find. Playwright and ESLint (@typescript-eslint/no-floating-promises) can warn about promises that are not awaited.


📝 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 order, then run it.

setTimeout(() => console.log("timeout"), 0);
Promise.resolve().then(() => console.log("promise"));
console.log("sync");
Show answer

📄 practice1.js

setTimeout(() => console.log("timeout"), 0);
Promise.resolve().then(() => console.log("promise"));
console.log("sync");

🖥️ Output

sync
promise
timeout

Synchronous code first, then microtasks (the promise), then the next task (the timer).

Q2. Predict the output, then run it.

async function f() {
  console.log("a");
  await undefined;
  console.log("b");
}
f();
console.log("c");
Show answer

📄 practice2.js

async function f() {
  console.log("a");
  await undefined;
  console.log("b");
}
f();
console.log("c");

🖥️ Output

a
c
b

An async function runs synchronously until its first await; the rest continues as a microtask after the current synchronous code.

Q3. Show that two timers with the same delay run in the order they were scheduled, and that a 0 ms timer still runs after a microtask.

Show answer

📄 practice3.js

setTimeout(() => console.log("timer A"), 0);
setTimeout(() => console.log("timer B"), 0);
queueMicrotask(() => console.log("microtask"));
console.log("sync");

🖥️ Output

sync
microtask
timer A
timer B

Q4. Write a function that splits a long job (summing 1 to 3,000,000) into chunks of 1,000,000 with setTimeout between them, so the event loop can handle other work in between. Print the final sum.

Show answer

📄 practice4.js

function sumInChunks(n, chunk, done) {
  let total = 0, i = 1;
  function work() {
    const end = Math.min(i + chunk, n + 1);
    for (; i < end; i++) total += i;
    if (i <= n) setTimeout(work, 0);   // let other callbacks run
    else done(total);
  }
  work();
}
sumInChunks(3_000_000, 1_000_000, (total) => console.log("sum:", total));
setTimeout(() => console.log("another callback got a turn"), 0);

🖥️ Output

another callback got a turn
sum: 4500001500000

The “another callback” line runs between chunks, proving the loop was not blocked for the whole job.

Q5. Predict the output, then run it.

process.nextTick(() => console.log("tick"));
Promise.resolve().then(() => console.log("promise"));
console.log("sync");
Show answer

📄 practice5.js

process.nextTick(() => console.log("tick"));
Promise.resolve().then(() => console.log("promise"));
console.log("sync");

🖥️ Output

sync
tick
promise

In Node.js, the process.nextTick queue runs before the promise microtask queue.

Q6. Explain in two sentences why await page.waitForTimeout(3000) is a poor way to wait for a slow page in a test, and what to use instead.

Show answer

A fixed delay is a guess: it is too short on a slow machine (flaky failures) and wastes time on a fast one, and timers only guarantee a minimum delay anyway. Wait for the actual condition instead, for example await expect(page.getByText("Dashboard")).toBeVisible() or await page.waitForURL("**/dashboard").


🧠 MCQ Quiz: Event Loop

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. How many pieces of your JavaScript code run at the same time on the main thread?
  2. When does a setTimeout(fn, 0) callback run?
  3. Which runs first?
  4. Which of these is a microtask?
  5. What happens to timers while a long synchronous loop runs?
  6. In Node.js, which runs before promise callbacks?
  7. What is printed?
    Promise.resolve().then(() => console.log("p"));
    console.log("s");
  8. Why is the order of top-level setTimeout(fn, 0) and setImmediate(fn) not guaranteed in Node.js?
  9. What can freeze a web page?
  10. Why can a missing await make a test pass sometimes and fail other times?

💼 Interview Questions and Answers

Q1. Explain the JavaScript event loop.

JavaScript executes code on one call stack. Asynchronous operations are delegated to the host environment (browser Web APIs or Node.js/libuv). When they complete, their callbacks are queued: promise reactions in the microtask queue, timers and I/O in task queues. The event loop takes the next task only when the call stack is empty, and after every task it drains the entire microtask queue. This lets a single thread handle many concurrent operations without blocking.

Q2. What is the difference between microtasks and macrotasks?

Microtasks (promise then/catch/finally, code after await, queueMicrotask, and process.nextTick in Node.js with higher priority) run right after the current task and are drained completely. Macrotasks (setTimeout, setInterval, I/O, UI events, setImmediate) run one per event-loop turn. So a resolved promise’s callback always runs before a setTimeout(fn, 0) scheduled at the same time.

Q3. Predict the output.

📄 interview-order.js

console.log("start");
setTimeout(() => console.log("timeout 1"), 0);
Promise.resolve().then(() => {
  console.log("promise 1");
  setTimeout(() => console.log("timeout 2"), 0);
}).then(() => console.log("promise 2"));
console.log("end");

⌨️ Terminal

node interview-order.js

🖥️ Output

start
end
promise 1
promise 2
timeout 1
timeout 2

Synchronous: start, end. Microtasks: promise 1 (which schedules timeout 2), promise 2. Tasks in scheduling order: timeout 1, timeout 2.

Q4. How does the event loop relate to flaky UI tests?

UI actions, network responses and rendering complete asynchronously at times that vary between runs and machines. Tests that check state without awaiting the operation (missing await) or that rely on fixed sleeps race against the event loop and pass or fail depending on timing. Reliable tests await every action and wait for observable conditions, which Playwright’s auto-waiting and retrying assertions are designed for.


❓ Frequently Asked Questions

🤔 Is JavaScript really single-threaded?

Your JavaScript code runs on one main thread. The runtime uses other threads for I/O, and you can create extra JavaScript threads explicitly with Web Workers or Node.js worker threads.

🤔 Is the event loop part of the JavaScript language?

The language defines jobs (microtasks) and promises; the full event loop with timers, I/O and rendering is provided by the host: the HTML specification for browsers and libuv for Node.js.

🤔 Why does my setTimeout run later than the delay I set?

Delays are minimums. The callback waits for the call stack to clear and all microtasks to finish, and browsers also clamp nested and background-tab timers.

🤔 Does await block the whole program?

No. It pauses only the current async function; the event loop keeps running other code until the awaited promise settles.


🏁 Summary

  • JavaScript runs one call stack; slow work happens in the runtime, and callbacks are queued for later.
  • The event loop runs a task, then drains all microtasks, then takes the next task.
  • Promise callbacks and code after await are microtasks; timers and I/O are tasks, so promises run first.
  • Timer delays are minimums; long synchronous code blocks timers, I/O and rendering.
  • In tests, await every async action and wait for conditions instead of fixed delays.

Next, continue with Lesson 47: Callbacks and Timers.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Callbacks and Timers: setTimeout, setInterval and Polling

Before promises existed, all asynchronous JavaScript was written with callbacks: “do this, and call me back when you are done”. You still meet callbacks everywhere, in timers, event listeners, Node.js core APIs and older libraries, and timers are the building blocks of retries, polling and timeouts in test helpers. In this lesson you will learn to schedule and cancel work with setTimeout and setInterval, understand Node.js error-first callbacks, see why deeply nested callbacks became a problem, and build a reliable polling helper.

📖 What You’ll Learn: asynchronous callbacks, setTimeout and passing arguments, clearTimeout, setInterval and clearInterval, why setInterval can drift and the recursive setTimeout pattern, error-first callbacks in Node.js, callback hell and how to flatten it, timers that return promises (node:timers/promises), cancelling with AbortController, and a waitFor polling helper with a timeout.


📞 Asynchronous Callbacks

Definition: an asynchronous callback is a function you pass to an API that will call it later, when something has happened: a timer has expired, a file has been read, a button has been clicked. The code after the call keeps running in the meantime.

📄 async-callback.js

function fetchUser(id, onDone) {
  console.log(`requesting user ${id}...`);
  setTimeout(() => {
    onDone({ id, name: "Asha" });     // call back later with the result
  }, 20);
}

fetchUser(7, (user) => console.log("got user:", user.name));
console.log("request sent, doing other work");

⌨️ Terminal

node async-callback.js

🖥️ Output

requesting user 7...
request sent, doing other work
got user: Asha

The result is only available inside the callback. Code written after fetchUser(...) runs before the user arrives, a constant source of beginner bugs:

📄 too-early.js

let user;
setTimeout(() => { user = { name: "Asha" }; }, 10);
console.log("user right after scheduling:", user);   // not set yet

⌨️ Terminal

node too-early.js

🖥️ Output

user right after scheduling: undefined

⏲️ setTimeout and clearTimeout

setTimeout(callback, delayMs, ...args) runs the callback once, after at least delayMs milliseconds. Extra arguments are passed to the callback. It returns a timer ID (an object in Node.js, a number in browsers) that you can pass to clearTimeout to cancel it.

📄 set-timeout.js

const greet = (name, role) => console.log(`Hello ${name}, ${role}`);

setTimeout(greet, 20, "Asha", "tester");      // arguments after the delay

const reminder = setTimeout(() => console.log("this never prints"), 50);
clearTimeout(reminder);                        // cancelled before it ran

setTimeout(() => console.log("done after 30 ms"), 30);
console.log("timers scheduled");

⌨️ Terminal

node set-timeout.js

🖥️ Output

timers scheduled
Hello Asha, tester
done after 30 ms

⚠️ Watch out: Pass the function, do not call it: setTimeout(greet("Asha"), 1000) runs greet immediately and passes its return value (undefined) to setTimeout.


🔁 setInterval and clearInterval

setInterval(callback, intervalMs) runs the callback repeatedly, every intervalMs milliseconds, until you stop it with clearInterval. Always keep the ID and always stop the interval, or it runs forever and keeps a Node.js process alive.

📄 set-interval.js

let count = 0;
const id = setInterval(() => {
  count++;
  console.log(`heartbeat ${count}`);
  if (count === 3) {
    clearInterval(id);
    console.log("stopped");
  }
}, 20);

⌨️ Terminal

node set-interval.js

🖥️ Output

heartbeat 1
heartbeat 2
heartbeat 3
stopped

Recursive setTimeout instead of setInterval

setInterval schedules the next run on a fixed clock, even if the previous run (for example a slow network call) has not finished. A recursive setTimeout schedules the next run only after the current one completes, so runs never overlap and the gap can change dynamically:

📄 recursive-timeout.js

let attempt = 0;

function poll() {
  attempt++;
  const delay = 10 * 2 ** attempt;     // back off: 20, 40, 80 ms
  console.log(`attempt ${attempt}, next check in ${delay} ms`);
  if (attempt < 3) setTimeout(poll, delay);
  else console.log("finished polling");
}

poll();

⌨️ Terminal

node recursive-timeout.js

🖥️ Output

attempt 1, next check in 20 ms
attempt 2, next check in 40 ms
attempt 3, next check in 80 ms
finished polling

⚠️ Error-First Callbacks in Node.js

Definition: Node.js core callback APIs follow the error-first convention: the callback’s first argument is an error (or null when everything went well), and the result comes after it. Always check the error before using the result.

📄 error-first.js

const fs = require("node:fs");

fs.writeFileSync("users.json", JSON.stringify([{ name: "Asha" }]));

fs.readFile("users.json", "utf8", (err, text) => {
  if (err) {
    console.log("could not read:", err.code);
    return;                           // stop here on error
  }
  console.log("users:", JSON.parse(text).length);
});

fs.readFile("missing.json", "utf8", (err, text) => {
  if (err) {
    console.log("could not read:", err.code);
    return;
  }
  console.log(text);
});

⌨️ Terminal

node error-first.js

🖥️ Output

could not read: ENOENT
users: 1

⚠️ Watch out: A try...catch around fs.readFile(...) does not catch errors from the callback: the callback runs later, after the try block has finished. That is why the error is passed in as an argument instead.

Writing your own function in this style:

📄 own-error-first.js

function divideLater(a, b, callback) {
  setTimeout(() => {
    if (b === 0) return callback(new Error("Division by zero"));
    callback(null, a / b);
  }, 5);
}

divideLater(10, 2, (err, result) => console.log(err ? err.message : `result ${result}`));
divideLater(10, 0, (err, result) => console.log(err ? err.message : `result ${result}`));

⌨️ Terminal

node own-error-first.js

🖥️ Output

result 5
Division by zero

🌀 Callback Hell

When each step depends on the previous one, callbacks nest inside callbacks. The code drifts to the right, error handling is repeated at every level, and the flow is hard to follow. This shape is called callback hell or the “pyramid of doom”:

📄 callback-hell.js

const api = {
  login: (user, cb) => setTimeout(() => cb(null, { token: "t-123" }), 5),
  getCart: (token, cb) => setTimeout(() => cb(null, { items: 2 }), 5),
  checkout: (cart, cb) => setTimeout(() => cb(cart.items ? null : new Error("empty cart"), { orderId: 451 }), 5),
};

api.login("asha", (err, session) => {
  if (err) return console.log("login failed", err);
  api.getCart(session.token, (err, cart) => {
    if (err) return console.log("cart failed", err);
    api.checkout(cart, (err, order) => {
      if (err) return console.log("checkout failed", err);
      console.log("order placed:", order.orderId);
    });
  });
});

⌨️ Terminal

node callback-hell.js

🖥️ Output

order placed: 451

Three steps already need three nesting levels and three error checks. Promises and async/await (the next lessons) were created to solve exactly this. The same flow with await becomes four flat lines inside one try...catch.

💡 Tip: If you must work with callbacks, flatten them with small named functions instead of anonymous nested ones, or convert the API to promises with util.promisify (shown in the Promises lesson).


⏳ Promise-Based Timers in Node.js

Node.js provides promise versions of the timers in node:timers/promises. They work with await, which reads much more naturally than callbacks:

📄 timers-promises.js

const { setTimeout: sleep, setInterval: every } = require("node:timers/promises");

async function main() {
  console.log("waiting 20 ms...");
  const value = await sleep(20, "timer value");
  console.log("woke up with:", value);

  let n = 0;
  for await (const _ of every(10)) {       // async iteration over an interval
    console.log("tick", ++n);
    if (n === 3) break;                     // break also stops the interval
  }
}
main();

⌨️ Terminal

node timers-promises.js

🖥️ Output

waiting 20 ms...
woke up with: timer value
tick 1
tick 2
tick 3

In browsers (and in Node.js too), the common one-line helper is const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));.


🛑 Cancelling with AbortController

Definition: an AbortController creates a signal that can be passed to cancellable APIs (promise timers, fetch, event listeners). Calling controller.abort() cancels them all. AbortSignal.timeout(ms) creates a signal that aborts by itself after a delay.

📄 abort.js

const { setTimeout: sleep } = require("node:timers/promises");

async function main() {
  const controller = new AbortController();
  setTimeout(() => controller.abort(), 20);          // cancel after 20 ms

  try {
    await sleep(1000, null, { signal: controller.signal });
    console.log("finished waiting");
  } catch (e) {
    console.log(`${e.name}: wait was cancelled`);
  }

  try {
    await sleep(1000, null, { signal: AbortSignal.timeout(15) });
  } catch (e) {
    console.log(`${e.name}: gave up after the timeout`);
  }
}
main();

⌨️ Terminal

node abort.js

🖥️ Output

AbortError: wait was cancelled
AbortError: gave up after the timeout

You will use the same signal option with fetch in the Fetch API lesson to stop requests that take too long.


🧪 Tester Scenario: A waitFor Polling Helper

Many test situations need “check this repeatedly until it is true, but give up after a timeout”: an email arriving in a test inbox, a background job finishing, an order status changing. This helper does it with a recursive setTimeout and reports a clear error when the timeout is reached:

📄 wait-for.js

function waitFor(check, { timeout = 1000, interval = 50, message = "condition" } = {}) {
  const start = Date.now();
  return new Promise((resolve, reject) => {
    let attempts = 0;
    function tick() {
      attempts++;
      const value = check();
      if (value) return resolve({ value, attempts });
      if (Date.now() - start >= timeout) {
        return reject(new Error(`Timed out after ${timeout} ms waiting for ${message} (${attempts} attempts)`));
      }
      setTimeout(tick, interval);
    }
    tick();
  });
}

// Simulated backend: the order becomes "shipped" after ~120 ms
const order = { status: "processing" };
setTimeout(() => { order.status = "shipped"; }, 120);

waitFor(() => order.status === "shipped" && order.status, { timeout: 500, interval: 50, message: "order to ship" })
  .then(({ value, attempts }) => console.log(`status: ${value} (checked ${attempts >= 3 ? "3 or more" : attempts} times)`))
  .then(() => waitFor(() => order.status === "delivered", { timeout: 150, interval: 50, message: "order delivery" }))
  .catch((e) => console.log(e.message.replace(/\(\d+ attempts\)/, "(several attempts)")));

⌨️ Terminal

node wait-for.js

🖥️ Output

status: shipped (checked 3 or more times)
Timed out after 150 ms waiting for order delivery (several attempts)
  • The check runs immediately, then every interval ms, and never overlaps itself.
  • The error message names what was being waited for, so a failing test explains itself.
  • Playwright has this built in: await expect.poll(() => getStatus()).toBe("shipped") and await expect(async () => {...}).toPass(). Use those inside Playwright tests.

📝 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. Print "3", "2", "1", "Go!" with 10 ms between each using setTimeout (not setInterval).

Show answer

📄 practice1.js

function countdown(n) {
  if (n === 0) return console.log("Go!");
  console.log(String(n));
  setTimeout(() => countdown(n - 1), 10);
}
countdown(3);

🖥️ Output

3
2
1
Go!

Q2. Use setInterval to print the numbers 1 to 5, then stop the interval.

Show answer

📄 practice2.js

let n = 0;
const id = setInterval(() => {
  console.log(++n);
  if (n === 5) clearInterval(id);
}, 10);

🖥️ Output

1
2
3
4
5

Q3. Schedule a “session expired” message for 100 ms, but cancel it because the user “clicked” after 20 ms. Print what happened.

Show answer

📄 practice3.js

const expiry = setTimeout(() => console.log("session expired"), 100);
setTimeout(() => {
  clearTimeout(expiry);
  console.log("user active: expiry cancelled");
}, 20);

🖥️ Output

user active: expiry cancelled

Q4. Write an error-first function parseJsonLater(text, cb) that calls back with an error for invalid JSON and with the parsed value otherwise. Test it with valid and invalid input.

Show answer

📄 practice4.js

function parseJsonLater(text, cb) {
  setTimeout(() => {
    try {
      cb(null, JSON.parse(text));
    } catch (e) {
      cb(e);
    }
  }, 0);
}
parseJsonLater('{"a":1}', (err, data) => console.log(err ? "error" : data));
parseJsonLater("{a:1}", (err, data) => console.log(err ? `error: ${err.name}` : data));

🖥️ Output

{ a: 1 }
error: SyntaxError

Q5. Use sleep from node:timers/promises with await to print "step 1", wait 20 ms, then print "step 2".

Show answer

📄 practice5.js

const { setTimeout: sleep } = require("node:timers/promises");
(async () => {
  console.log("step 1");
  await sleep(20);
  console.log("step 2");
})();

🖥️ Output

step 1
step 2

Q6. Explain why this prints undefined and fix it so the total is printed.

let total;
setTimeout(() => { total = 42; }, 10);
console.log(total);
Show answer

The callback runs after 10 ms, but console.log runs immediately, before total is set. Use the value inside the callback (or await a promise):

📄 practice6.js

setTimeout(() => {
  const total = 42;
  console.log(total);
}, 10);

🖥️ Output

42

🧠 MCQ Quiz: Callbacks and Timers

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 does setTimeout return?
  2. How do you pass arguments to a setTimeout callback?
  3. How do you stop a setInterval?
  4. What is the first argument of a Node.js error-first callback?
  5. Why can’t try/catch around fs.readFile catch its errors?
  6. What is callback hell?
  7. What is an advantage of recursive setTimeout over setInterval?
  8. What does AbortSignal.timeout(500) create?
  9. What is wrong with setTimeout(save(), 1000)?
  10. Which Playwright API replaces a hand-written polling helper?

💼 Interview Questions and Answers

Q1. What is the difference between setTimeout and setInterval?

setTimeout runs a callback once after a minimum delay; setInterval runs it repeatedly at a fixed interval until clearInterval. Intervals do not wait for the previous run to finish, so slow callbacks can overlap or pile up; a recursive setTimeout avoids that and allows back-off. Both delays are minimums.

Q2. What are error-first callbacks?

A Node.js convention where the callback signature is (err, result): err is null on success or an Error on failure. The caller checks err first and returns early on failure. It exists because exceptions thrown in a later callback cannot be caught by the original caller’s try...catch.

Q3. How would you convert a callback-based function to a promise?

📄 promisify.js

const util = require("node:util");

function legacyAdd(a, b, cb) {
  setTimeout(() => cb(null, a + b), 5);
}

const addAsync = util.promisify(legacyAdd);
addAsync(2, 3).then((sum) => console.log("promisified:", sum));

const manual = (a, b) => new Promise((resolve, reject) =>
  legacyAdd(a, b, (err, result) => (err ? reject(err) : resolve(result))));
manual(4, 5).then((sum) => console.log("manual:", sum));

⌨️ Terminal

node promisify.js

🖥️ Output

promisified: 5
manual: 9

util.promisify works for any error-first callback API; the manual version shows what it does.

Q4. How do you implement waiting for a condition with a timeout?

Check the condition immediately; if it is not met and the timeout has not elapsed, schedule another check with setTimeout after an interval; resolve when it is met and reject with a descriptive error when time runs out. Use a recursive timeout (not an interval) so checks never overlap, and support cancellation with an AbortSignal. In Playwright tests, prefer expect.poll or toPass.


❓ Frequently Asked Questions

🤔 Is setTimeout precise?

No. The delay is a minimum: the callback runs when the time has passed and the call stack is free. Browsers also slow down timers in background tabs.

🤔 What is the maximum delay for setTimeout?

About 24.8 days (231 − 1 ms). Larger values overflow and the callback runs almost immediately, with a warning in Node.js.

🤔 Why does my Node.js script not exit?

An active interval, timer, server or open handle keeps the process alive. Clear intervals and close servers, or call timer.unref() for timers that should not keep the process running.

🤔 Should I still write callback-based code?

For new asynchronous code, use promises and async/await. Callbacks remain normal for events, array methods and timers.


🏁 Summary

  • Asynchronous callbacks run later; their results are only available inside the callback.
  • setTimeout runs once and setInterval repeats; cancel them with clearTimeout/clearInterval.
  • Prefer a recursive setTimeout when runs must not overlap or the delay should change.
  • Node.js callbacks are error-first: check err before using the result; nested callbacks lead to callback hell.
  • Use node:timers/promises with await, AbortController for cancellation, and polling helpers (or Playwright’s expect.poll) for waiting.

Next, continue with Lesson 48: Promises.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Custom Errors: Error Classes, Codes, Causes and AggregateError

A plain Error("Request failed") tells you something went wrong but not what kind of problem it was or what to do about it. Custom error classes fix that: an ApiError can carry the status code and URL, a ValidationError can name the field, and code can decide to retry a TimeoutError but fail fast on a ValidationError. In this lesson you will build custom errors properly, organise them into a small hierarchy, chain causes, collect several errors with AggregateError, and use them to make test failures self-explanatory.

📖 What You’ll Learn: why custom errors help, extending Error correctly, setting name automatically, adding context properties and error codes, checking errors with instanceof and codes, error hierarchies, cause chains and printing them, AggregateError for multiple failures, serialising errors for logs and reports, result objects as an alternative, and a retry decision based on error types.


🤔 Why Create Custom Errors?

Compare what the caller can do with a generic error versus a custom one:

📄 why.js

class ApiError extends Error {
  constructor(message, { status, url } = {}) {
    super(message);
    this.name = "ApiError";
    this.status = status;
    this.url = url;
  }
}

const generic = new Error("Request failed");
const custom = new ApiError("Request failed", { status: 503, url: "/api/orders" });

console.log(generic.name, "|", generic.message);
console.log(custom.name, "|", custom.message, "|", custom.status, custom.url);
console.log("retry?", custom instanceof ApiError && custom.status >= 500);

⌨️ Terminal

node why.js

🖥️ Output

Error | Request failed
ApiError | Request failed | 503 /api/orders
retry? true
  • Type: instanceof ApiError lets code handle API problems differently from bugs.
  • Context: status and URL travel with the error to wherever it is caught or logged.
  • Decisions: callers can retry server errors (5xx) but not client errors (4xx).

🏗️ Extending Error Correctly

Definition: a custom error is a class that extends Error (or one of its subclasses). Three rules make it behave like a built-in error:

  1. Call super(message, options) first, so message, stack and cause are set.
  2. Set this.name so the type appears in logs and stack traces. Using new.target.name or this.constructor.name sets it automatically for every subclass.
  3. Add only the extra properties callers need.

📄 extend.js

class AppError extends Error {
  constructor(message, options) {
    super(message, options);            // options may contain { cause }
    this.name = new.target.name;        // "AppError", or the subclass name
  }
}

class ConfigError extends AppError {}

const e = new ConfigError("BASE_URL is not set");
console.log(e.name, "|", e.message);
console.log(e instanceof ConfigError, e instanceof AppError, e instanceof Error);
console.log(e.stack.split("\n")[0]);
console.log(String(e));

⌨️ Terminal

node extend.js

🖥️ Output

ConfigError | BASE_URL is not set
true true true
ConfigError: BASE_URL is not set
ConfigError: BASE_URL is not set

⚠️ Watch out: If you forget this.name, the error prints as a plain Error in stack traces and logs, which hides its type. Setting it once in a base class with new.target.name covers every subclass.


🏷️ Context Properties and Error Codes

Messages are for humans; error codes are for code. Node.js itself uses codes such as ENOENT and ERR_ASSERTION. Codes stay stable when messages are reworded, so checks based on them do not break.

📄 codes.js

class ValidationError extends Error {
  constructor(field, problem, value) {
    super(`${field}: ${problem} (got ${JSON.stringify(value)})`);
    this.name = "ValidationError";
    this.code = "E_VALIDATION";
    this.field = field;
    this.value = value;
  }
}

function validateUser(user) {
  if (!user.email?.includes("@")) throw new ValidationError("email", "must contain @", user.email);
  if (!(user.age >= 18)) throw new ValidationError("age", "must be 18 or older", user.age);
  return true;
}

for (const user of [{ email: "asha@sqatools.in", age: 29 }, { email: "asha", age: 29 }, { email: "a@b.in", age: 15 }]) {
  try {
    console.log("valid:", validateUser(user));
  } catch (e) {
    if (e.code === "E_VALIDATION") console.log(`invalid field "${e.field}" -> ${e.message}`);
    else throw e;
  }
}

const fs = require("node:fs");
try {
  fs.readFileSync("missing-file.json");
} catch (e) {
  console.log("Node.js error code:", e.code);
}

⌨️ Terminal

node codes.js

🖥️ Output

valid: true
invalid field "email" -> email: must contain @ (got "asha")
invalid field "age" -> age: must be 18 or older (got 15)
Node.js error code: ENOENT

🌳 A Small Error Hierarchy

Group related errors under a common base so callers can catch broadly or narrowly. Keep it shallow: two levels are usually enough.

📄 hierarchy.js

class AppError extends Error {
  constructor(message, options) { super(message, options); this.name = new.target.name; }
}
class HttpError extends AppError {
  constructor(status, url, options) {
    super(`HTTP ${status} for ${url}`, options);
    this.status = status;
    this.url = url;
  }
  get retryable() { return this.status >= 500 || this.status === 429; }
}
class NotFoundError extends HttpError {
  constructor(url) { super(404, url); }
}
class TimeoutError extends AppError {
  constructor(ms, url) { super(`Timed out after ${ms} ms: ${url}`); this.retryable = true; }
}

const errors = [new NotFoundError("/api/users/99"), new HttpError(503, "/api/orders"), new TimeoutError(5000, "/api/search"), new TypeError("x is not a function")];

for (const e of errors) {
  const kind = e instanceof NotFoundError ? "not found"
    : e instanceof HttpError ? "http error"
    : e instanceof AppError ? "app error"
    : "unexpected bug";
  console.log(`${e.name.padEnd(13)} ${kind.padEnd(14)} retryable=${e.retryable ?? false}`);
}

⌨️ Terminal

node hierarchy.js

🖥️ Output

NotFoundError not found      retryable=false
HttpError     http error     retryable=true
TimeoutError  app error      retryable=true
TypeError     unexpected bug retryable=false

💡 Tip: Check the most specific class first. NotFoundError is also an HttpError and an AppError, so the order of instanceof checks matters.


🔗 Cause Chains

Each layer of a program can add context by wrapping the error it caught, passing the original as cause. The result is a chain from the high-level problem down to the root cause:

📄 cause-chain.js

class AppError extends Error {
  constructor(message, options) { super(message, options); this.name = new.target.name; }
}

function readRow() {
  return JSON.parse("{'id': 1}");                  // low level: SyntaxError
}
function loadUsers() {
  try { return readRow(); }
  catch (e) { throw new AppError("Could not parse users.csv row 3", { cause: e }); }
}
function setupTest() {
  try { return loadUsers(); }
  catch (e) { throw new AppError("Test data setup failed for checkout.spec", { cause: e }); }
}

function printChain(error) {
  let depth = 0;
  for (let e = error; e; e = e.cause) {
    console.log(`${"  ".repeat(depth++)}${depth > 1 ? "caused by " : ""}${e.name}: ${e.message}`);
  }
}

try {
  setupTest();
} catch (e) {
  printChain(e);
}

⌨️ Terminal

node cause-chain.js

🖥️ Output

AppError: Test data setup failed for checkout.spec
  caused by AppError: Could not parse users.csv row 3
    caused by SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)

Node.js also prints the cause chain automatically when such an error is uncaught.


📦 AggregateError: Several Errors at Once

Definition: AggregateError is a built-in error that holds an array of errors in its errors property. Promise.any throws it when every promise fails, and you can throw it yourself when a validation or a batch produces several failures:

📄 aggregate.js

function validateForm(form) {
  const problems = [];
  if (!form.name) problems.push(new Error("name is required"));
  if (!/^\d{6}$/.test(form.pin ?? "")) problems.push(new Error("pin must be 6 digits"));
  if (!form.terms) problems.push(new Error("terms must be accepted"));
  if (problems.length) throw new AggregateError(problems, `${problems.length} field(s) invalid`);
  return true;
}

try {
  validateForm({ name: "", pin: "41100" });
} catch (e) {
  console.log(e.name, "-", e.message);
  e.errors.forEach((err, i) => console.log(`  ${i + 1}. ${err.message}`));
}

Promise.any([Promise.reject(new Error("mirror 1 down")), Promise.reject(new Error("mirror 2 down"))])
  .catch((e) => console.log(e.constructor.name, e.errors.map((x) => x.message)));

⌨️ Terminal

node aggregate.js

🖥️ Output

AggregateError - 3 field(s) invalid
  1. name is required
  2. pin must be 6 digits
  3. terms must be accepted
AggregateError [ 'mirror 1 down', 'mirror 2 down' ]

Reporting every problem at once (“3 fields invalid”) is much friendlier than failing on the first one and making someone fix and rerun three times.


📝 Serialising Errors for Logs and Reports

JSON.stringify(error) returns {} for errors, because message and stack are not enumerable own properties. Add a toJSON() method, or convert errors explicitly before writing them to a JSON report:

📄 serialize.js

console.log(JSON.stringify(new Error("boom")));

class ApiError extends Error {
  constructor(message, { status, url } = {}) {
    super(message);
    this.name = "ApiError";
    this.status = status;
    this.url = url;
  }
  toJSON() {
    return { name: this.name, message: this.message, status: this.status, url: this.url };
  }
}

console.log(JSON.stringify(new ApiError("Service unavailable", { status: 503, url: "/api/pay" })));

const toPlain = (e) => ({ name: e.name, message: e.message, ...(e.cause && { cause: toPlain(e.cause) }) });
console.log(JSON.stringify(toPlain(new Error("outer", { cause: new TypeError("inner") }))));

⌨️ Terminal

node serialize.js

🖥️ Output

{}
{"name":"ApiError","message":"Service unavailable","status":503,"url":"/api/pay"}
{"name":"Error","message":"outer","cause":{"name":"TypeError","message":"inner"}}

⚠️ Watch out: Before logging an error’s context, make sure it contains no secrets. Request headers, tokens and passwords stored on an error object end up in CI logs and reports.


⚖️ Throwing vs Returning a Result

Exceptions are for situations the current code cannot handle. When a failure is an expected, normal outcome (a search with no results, an optional file), returning a result object can be clearer than throwing:

📄 result.js

function findUser(users, email) {
  const user = users.find((u) => u.email === email);
  return user ? { ok: true, user } : { ok: false, reason: `no user with email ${email}` };
}

const users = [{ email: "asha@sqatools.in", name: "Asha" }];
for (const email of ["asha@sqatools.in", "ghost@sqatools.in"]) {
  const result = findUser(users, email);
  console.log(result.ok ? `found ${result.user.name}` : result.reason);
}

⌨️ Terminal

node result.js

🖥️ Output

found Asha
no user with email ghost@sqatools.in
Throw an error when…Return a result when…
The caller cannot continue (bad config, broken API, failed assertion)Failure is a normal, expected case
The problem must not be ignoredThe caller will always check the outcome
You want a stack tracePerformance matters in a hot loop

🧪 Tester Scenario: Retry Only What Is Worth Retrying

This API helper throws typed errors, and a retry wrapper uses those types to decide: retry timeouts and 5xx responses, fail immediately on 4xx and on bugs. Every failure keeps its full context for the report.

📄 retry.js

class AppError extends Error {
  constructor(message, options) { super(message, options); this.name = new.target.name; }
}
class HttpError extends AppError {
  constructor(status, url) { super(`HTTP ${status} for ${url}`); this.status = status; this.url = url; }
  get retryable() { return this.status >= 500; }
}
class TimeoutError extends AppError {
  retryable = true;
}

// Simulated server: answers differ per attempt
const scripted = { "/api/orders": [new TimeoutError("timeout 5000 ms"), new HttpError(503, "/api/orders"), { items: 3 }], "/api/users/99": [new HttpError(404, "/api/users/99")] };
function fakeGet(url, attempt) {
  const answer = scripted[url][Math.min(attempt - 1, scripted[url].length - 1)];
  if (answer instanceof Error) throw answer;
  return answer;
}

function getWithRetry(url, maxAttempts = 3) {
  for (let attempt = 1; ; attempt++) {
    try {
      const body = fakeGet(url, attempt);
      console.log(`  ${url} attempt ${attempt}: ok`);
      return body;
    } catch (e) {
      const canRetry = e.retryable === true && attempt < maxAttempts;
      console.log(`  ${url} attempt ${attempt}: ${e.name} - ${e.message}${canRetry ? " -> retrying" : ""}`);
      if (!canRetry) throw new AppError(`GET ${url} failed after ${attempt} attempt(s)`, { cause: e });
    }
  }
}

console.log(getWithRetry("/api/orders"));
try {
  getWithRetry("/api/users/99");
} catch (e) {
  console.log(`${e.message} | cause: ${e.cause.name} status=${e.cause.status}`);
}

⌨️ Terminal

node retry.js

🖥️ Output

  /api/orders attempt 1: TimeoutError - timeout 5000 ms -> retrying
  /api/orders attempt 2: HttpError - HTTP 503 for /api/orders -> retrying
  /api/orders attempt 3: ok
{ items: 3 }
  /api/users/99 attempt 1: HttpError - HTTP 404 for /api/users/99
GET /api/users/99 failed after 1 attempt(s) | cause: HttpError status=404

Playwright exports its own error classes, for example errors.TimeoutError from @playwright/test, so the same instanceof technique works with real browser timeouts.


📝 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. Create class NotFoundError extends Error that takes a resource name and builds the message "<resource> not found". Throw and catch it, printing the name and message.

Show answer

📄 practice1.js

class NotFoundError extends Error {
  constructor(resource) {
    super(`${resource} not found`);
    this.name = "NotFoundError";
    this.resource = resource;
  }
}
try {
  throw new NotFoundError("Order 451");
} catch (e) {
  console.log(e.name, "|", e.message, "|", e instanceof NotFoundError);
}

🖥️ Output

NotFoundError | Order 451 not found | true

Q2. Write a base class AppError that sets name automatically, then two subclasses AuthError and DbError. Show that each has the right name without setting it again.

Show answer

📄 practice2.js

class AppError extends Error {
  constructor(message) { super(message); this.name = new.target.name; }
}
class AuthError extends AppError {}
class DbError extends AppError {}
console.log(new AuthError("token expired").name, new DbError("connection lost").name);

🖥️ Output

AuthError DbError

Q3. Add a numeric status and a getter isClientError (400–499) to an HttpError class. Test it with 404 and 502.

Show answer

📄 practice3.js

class HttpError extends Error {
  constructor(status) {
    super(`HTTP ${status}`);
    this.name = "HttpError";
    this.status = status;
  }
  get isClientError() { return this.status >= 400 && this.status < 500; }
}
console.log(new HttpError(404).isClientError, new HttpError(502).isClientError);

🖥️ Output

true false

Q4. Wrap a TypeError in an error "Checkout step failed" using cause, and print the message and the cause’s name.

Show answer

📄 practice4.js

try {
  try {
    undefined.total;
  } catch (e) {
    throw new Error("Checkout step failed", { cause: e });
  }
} catch (e) {
  console.log(e.message, "<-", e.cause.name, ":", e.cause.message);
}

🖥️ Output

Checkout step failed <- TypeError : Cannot read properties of undefined (reading 'total')

Q5. Validate an array of prices [10, -5, "abc", 20, -1] and throw one AggregateError listing every invalid entry with its index.

Show answer

📄 practice5.js

const prices = [10, -5, "abc", 20, -1];
const problems = prices
  .map((p, i) => (typeof p !== "number" || p < 0 ? new Error(`index ${i}: invalid price ${JSON.stringify(p)}`) : null))
  .filter(Boolean);
try {
  if (problems.length) throw new AggregateError(problems, `${problems.length} invalid prices`);
} catch (e) {
  console.log(e.message);
  for (const err of e.errors) console.log(" -", err.message);
}

🖥️ Output

3 invalid prices
 - index 1: invalid price -5
 - index 2: invalid price "abc"
 - index 4: invalid price -1

Q6. Make JSON.stringify of your custom error include the name, message and a code property.

Show answer

📄 practice6.js

class CodedError extends Error {
  constructor(code, message) {
    super(message);
    this.name = "CodedError";
    this.code = code;
  }
  toJSON() { return { name: this.name, code: this.code, message: this.message }; }
}
console.log(JSON.stringify(new CodedError("E_TIMEOUT", "Page load timed out")));

🖥️ Output

{"name":"CodedError","code":"E_TIMEOUT","message":"Page load timed out"}

🧠 MCQ Quiz: Custom Errors

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 must a custom error constructor call first?
  2. Why set this.name in a custom error?
  3. What does this.name = new.target.name in a base class do?
  4. Why use error codes like E_VALIDATION?
  5. With class NotFound extends HttpError, what is new NotFound() instanceof HttpError?
  6. What does AggregateError hold?
  7. What does JSON.stringify(new Error("x")) return?
  8. How do you attach the original error when wrapping it?
  9. Which error should a retry helper usually NOT retry?
  10. When is returning a result object better than throwing?

💼 Interview Questions and Answers

Q1. How do you create a custom error class in JavaScript?

📄 payment-error.js

class PaymentError extends Error {
  constructor(message, { orderId, cause } = {}) {
    super(message, { cause });
    this.name = "PaymentError";
    this.orderId = orderId;
  }
}
const e = new PaymentError("Card declined", { orderId: 451 });
console.log(e.name, e.message, e.orderId, e instanceof PaymentError, e instanceof Error);

⌨️ Terminal

node payment-error.js

🖥️ Output

PaymentError Card declined 451 true true

Extend Error, call super with the message (and optional cause), set name, and add context properties. Callers can then use instanceof and read the extra fields.

Q2. Why are custom errors useful in a test framework?

They make failures diagnosable and actionable: an ApiError carries the URL, status and response snippet; a DataSetupError says which fixture failed; a ConfigError points at a missing environment variable. Retry logic and reporters can branch on the type, and reports group failures by category (product bug, test bug, environment issue).

Q3. What is the error cause feature and why use it?

ES2022 added an options argument to Error: new Error(message, { cause }). It keeps the original error when you wrap it with a higher-level message, so you get both the business context (“checkout setup failed”) and the root technical reason (a JSON SyntaxError) without string concatenation. Node.js prints the chain when the error is uncaught.

Q4. How would you report several validation failures at once?

Collect the individual problems into an array while validating, then throw one AggregateError(errors, message) (or a custom ValidationError with an issues array). Callers iterate error.errors to show every problem. Test frameworks offer the same idea with soft assertions, such as Playwright’s expect.soft.


❓ Frequently Asked Questions

🤔 Should every error in my project be a custom class?

No. Create custom classes for categories that callers handle differently (HTTP, validation, timeout, configuration). Built-in types are fine for programming bugs.

🤔 Does instanceof work with custom errors across modules?

Yes, as long as both sides use the same class from the same module. Duplicate copies of a library (different versions) can break instanceof, which is one reason to also set name or code.

🤔 What is Error.captureStackTrace?

A V8 (Node.js and Chrome) function that sets a stack on any object and can hide frames. With class extends Error and super() you rarely need it.

🤔 Can I add a custom error to a Playwright test?

Yes. Throw it from helpers or page objects; Playwright reports its name and message, and expect(() => fn()).toThrow(MyError) checks the type.


🏁 Summary

  • Custom errors extend Error, call super(message, options) and set name (automatically with new.target.name).
  • Add context (status, url, field) and stable codes so callers can decide what to do.
  • Shallow hierarchies let code catch broadly or narrowly; check the most specific instanceof first.
  • Chain errors with cause and report several failures at once with AggregateError.
  • Add toJSON for logs and reports, never include secrets, and return results instead of throwing for expected outcomes.

Next, continue with Lesson 45: Debugging in VS Code and DevTools.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Debugging JavaScript in VS Code, Node.js and Chrome DevTools

Debugging is the skill that separates a tester who reports “the test is failing” from one who reports “the test fails because the API returns the price as a string since build 4512”. In this lesson you will learn a repeatable debugging process, how to read stack traces (including async ones), how to use breakpoints, conditional breakpoints, logpoints and watches in VS Code, how to debug Node.js with Chrome DevTools, how to debug code running in the browser, and the tools Playwright gives you for debugging tests.

📖 What You’ll Learn: a step-by-step debugging process, reading synchronous and async stack traces, targeted logging and util.inspect, debug logging switched on by environment variables, VS Code breakpoints, conditional breakpoints, logpoints, exception breakpoints, watches and the call stack, launch.json, node –inspect with Chrome DevTools, debugging browser code in the Sources panel, source maps, Playwright debugging tools, and a checklist of common bugs.


🧭 A Debugging Process That Works

Definition: debugging is finding the cause of a difference between what the code should do and what it actually does, then fixing it. Guessing and changing code randomly wastes hours; a process finds the cause quickly:

  1. Reproduce the problem reliably. Note the exact input, environment and steps. A bug you cannot reproduce cannot be confirmed as fixed.
  2. Read the error fully: type, message and the first stack frame in your own code.
  3. Isolate it: shrink the input or the code until the problem disappears; the last change points at the cause.
  4. Form a hypothesis (“the price is a string, not a number”) and check it with a breakpoint or a log, not by assuming.
  5. Fix the cause, not the symptom, and add a test or assertion so it cannot come back unnoticed.

💡 Tip: Explaining the code line by line to someone else, or even to a rubber duck on your desk, often reveals the bug. Saying “and here the value is definitely a number” out loud makes you notice that you never checked.


📜 Reading Stack Traces

A stack trace lists the function calls that were active when the error happened, most recent first. Find the first line that points into your code; that is usually where to start.

📄 stack.js

function parsePrice(text) {
  return text.replace("₹", "");          // fails if text is not a string
}
function lineTotal(item) {
  return Number(parsePrice(item.price)) * item.qty;
}
function cartTotal(items) {
  return items.reduce((sum, item) => sum + lineTotal(item), 0);
}

console.log(cartTotal([{ price: "₹10", qty: 2 }, { price: 45, qty: 1 }]));

⌨️ Terminal

node stack.js

🖥️ Output

/home/you/js-course/stack.js:2
  return text.replace("₹", "");          // fails if text is not a string
              ^

TypeError: text.replace is not a function
    at parsePrice (/home/you/js-course/stack.js:2:15)
    at lineTotal (/home/you/js-course/stack.js:5:17)
    at /home/you/js-course/stack.js:8:44
    at Array.reduce (<anonymous>)
    at cartTotal (/home/you/js-course/stack.js:8:16)
    at Object.<anonymous> (/home/you/js-course/stack.js:11:13)

Node.js v26.13.0
  • Line 1 of the trace shows the source line and a caret ^ at the failing expression.
  • TypeError: text.replace is not a function: text was not a string (it was the number 45).
  • Read down the frames: parsePrice ← lineTotal ← the reduce callback ← cartTotal. The data came from the second cart item.

Async stack traces

With async/await, Node.js keeps the chain of awaiting functions in the trace, shown as at async ...:

📄 async-stack.js

const delay = (ms) => new Promise((r) => setTimeout(r, ms));

async function fetchUser(id) {
  await delay(5);
  if (id === 0) throw new Error(`User ${id} not found`);
  return { id };
}
async function loginAs(id) {
  const user = await fetchUser(id);
  return user;
}
async function runTest() {
  await loginAs(0);
}

runTest().catch((e) => console.log(e.stack));

⌨️ Terminal

node async-stack.js

🖥️ Output

Error: User 0 not found
    at fetchUser (/home/you/js-course/async-stack.js:5:23)
    at async loginAs (/home/you/js-course/async-stack.js:9:16)
    at async runTest (/home/you/js-course/async-stack.js:13:3)

⚠️ Watch out: The async chain is only kept when every step is awaited. If a function returns a promise without awaiting it, or uses .then callbacks, frames can disappear from the trace, which makes failures much harder to locate.


🔎 Targeted Logging

Logging is still the fastest tool for many problems, when it is targeted: log the exact values your hypothesis depends on, with labels, at the point where you suspect things go wrong.

📄 targeted-log.js

const util = require("node:util");

const response = { status: 200, body: { data: { items: [{ id: 1, price: "499" }, { id: 2, price: null }] } } };

console.log("price types:", response.body.data.items.map((i) => `${i.id}:${typeof i.price}`));
console.log(util.inspect(response, { depth: null, colors: false, compact: 3 }));
console.log({ status: response.status, count: response.body.data.items.length });   // label values with an object

⌨️ Terminal

node targeted-log.js

🖥️ Output

price types: [ '1:string', '2:object' ]
{
  status: 200,
  body: {
    data: { items: [ { id: 1, price: '499' }, { id: 2, price: null } ] }
  }
}
{ status: 200, count: 2 }
  • Log types as well as values: "499" and 499 look the same in many outputs.
  • util.inspect(value, { depth: null }) prints nested objects completely (see the Console Methods lesson).
  • Wrapping values in an object, console.log({ status, count }), prints their names too.

Debug logging you can switch on

Instead of adding and deleting logs, keep useful debug output behind a switch. Node.js has a built-in helper, util.debuglog, that prints only when the section name is listed in the NODE_DEBUG environment variable:

📄 orders.js

const util = require("node:util");
const log = util.debuglog("orders");

log("loaded %d orders", 3);   // printed only with NODE_DEBUG=orders
console.log("done");

⌨️ Terminal

node orders.js
NODE_DEBUG=orders node orders.js

🖥️ Output (run twice; 12345 is the process ID and changes every run)

done
ORDERS 12345: loaded 3 orders
done

On Windows PowerShell set the variable first: $env:NODE_DEBUG="orders"; node orders.js. Libraries such as debug use the same idea with a DEBUG variable, and Playwright prints its internal logs with DEBUG=pw:api.


🐞 Breakpoints in VS Code

A breakpoint pauses the program at a line so you can inspect every variable, step through the code, and evaluate expressions, without editing the code.

  1. Open the file and click in the gutter left of a line number to add a red breakpoint dot.
  2. Open Run and Debug (Ctrl+Shift+D) and click Run and Debug, or press F5 and choose Node.js.
  3. When execution pauses, use the panels: Variables (all values in scope), Watch (expressions you add), Call Stack (who called this), and the Debug Console (run any expression in the paused context).
  4. Step with Continue (F5), Step Over (F10), Step Into (F11) and Step Out (Shift+F11).
Breakpoint typeHow to add (right-click the gutter)Use it when
Conditional breakpoint“Add Conditional Breakpoint”, for example item.price === nullA bug only happens for one item in a loop of hundreds
Hit countConditional breakpoint → Hit Count, for example 50Pause on the 50th iteration
Logpoint“Add Logpoint”, for example price={item.price}You want a log without editing the code
Exception breakpointsBreakpoints panel → “Caught/Uncaught Exceptions”Pause exactly where an error is thrown

💡 Tip: Turn on “Uncaught Exceptions” in the Breakpoints panel. The debugger then stops at the line that throws, with all local variables visible, which is often faster than reading the stack trace.

launch.json for repeatable debug sessions

Save a debug configuration so the whole team starts the debugger the same way (Run and Debug → create a launch.json file):

📄 .vscode/launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Debug current file",
      "program": "${file}",
      "skipFiles": ["<node_internals>/**"]
    },
    {
      "type": "node",
      "request": "launch",
      "name": "Debug npm test",
      "runtimeExecutable": "npm",
      "runtimeArgs": ["test"],
      "env": { "NODE_DEBUG": "orders" },
      "skipFiles": ["<node_internals>/**", "**/node_modules/**"]
    }
  ]
}

skipFiles stops the debugger from stepping into Node.js internals and libraries. VS Code also offers a JavaScript Debug Terminal (Command Palette → “Debug: JavaScript Debug Terminal”): any node or npm command run in it starts with the debugger attached.


🛰️ node –inspect and Chrome DevTools

Node.js can be debugged with Chrome’s DevTools too. Start the script with an inspector flag:

⌨️ Terminal

node --inspect-brk debug-me.js

🖥️ Output (the ID changes every run)

Debugger listening on ws://127.0.0.1:9229/3052d451-479b-40b1-b568-a582926a527c
For help, see: https://nodejs.org/learn/getting-started/debugging
  • --inspect starts the program and lets a debugger attach; --inspect-brk also pauses on the first line, so you have time to attach before anything runs.
  • In Chrome, open chrome://inspect and click inspect under your script (or “Open dedicated DevTools for Node”).
  • You get the full Sources panel: breakpoints, stepping, scope variables, the console, and the Memory and Performance profilers.
  • The inspector listens on 127.0.0.1 only by default. Never expose it on a public network: anyone who connects can run code in your process.

The terminal-only debugger node inspect file.js (commands cont, next, step, repl) is handy on servers without a GUI.


🌐 Debugging Code in the Browser

For JavaScript running in a web page, use the browser’s DevTools (F12) → Sources panel:

ToolWhat it does
Line breakpointsClick a line number in a script, exactly as in VS Code
debugger; statementPauses at that line whenever DevTools is open
XHR/fetch breakpointsPause when a request URL contains some text, such as /api/orders
DOM breakpointsRight-click an element in Elements → Break on → subtree modifications / attribute modifications / node removal
Event listener breakpointsPause on any click, keydown, submit… event
Pause on exceptionsThe pause icon in the Breakpoints pane, like VS Code’s exception breakpoints
Network panelInspect every request and response: status, headers, payload, timing

Source maps connect the bundled, minified code the browser runs to your original source files (or TypeScript). With source maps, breakpoints and stack traces show your real file names and lines. In Node.js, node --enable-source-maps applies them to stack traces of compiled code.

💡 Tip: A DOM breakpoint on “subtree modifications” is the quickest way to find which script keeps changing an element, for example a value that a test fills in and something else overwrites a moment later.


🎭 Debugging Playwright Tests

Playwright includes dedicated tools for failing tests. These are the ones you will use most:

⌨️ Terminal

# Run with the Playwright Inspector: step through actions, see locators highlighted
npx playwright test login.spec.ts --debug

# UI mode: watch mode, time-travel through every step, pick locators
npx playwright test --ui

# Record a trace for each test and open it after a failure
npx playwright test --trace on
npx playwright show-trace test-results/login-chromium/trace.zip

# Print Playwright's API logs (bash/zsh syntax)
DEBUG=pw:api npx playwright test login.spec.ts

📄 checkout.spec.ts (Playwright, for reference)

import { test, expect } from "@playwright/test";

test("checkout", async ({ page }) => {
  await page.goto("/cart");
  await page.pause();                         // opens the Inspector here, like a breakpoint
  await page.getByRole("button", { name: "Checkout" }).click();
  await expect(page).toHaveURL(/\/checkout/);
});
  • The trace viewer shows every action with a DOM snapshot before and after, the console, network requests and the source line, which makes CI-only failures debuggable after the fact.
  • VS Code’s Playwright extension adds a “Debug Test” button next to each test, so normal breakpoints work in test code.
  • The Playwright course covers these in detail: Playwright Debugging and Trace Viewer.

🧪 Tester Scenario: Isolate a Bug by Halving the Data

A total is wrong, and the input has hundreds of rows. Instead of reading them all, check halves until you find the bad row, a technique called bisection (the same idea as git bisect for finding the commit that introduced a bug):

📄 bisect.js

const rows = Array.from({ length: 200 }, (_, i) => ({ id: i + 1, price: 10 }));
rows[137].price = "10";                      // the hidden bug: a string price

const isGood = (subset) => subset.every((r) => typeof r.price === "number");

function bisect(list) {
  let lo = 0, hi = list.length, steps = 0;
  while (hi - lo > 1) {
    steps++;
    const mid = Math.floor((lo + hi) / 2);
    if (isGood(list.slice(lo, mid))) lo = mid;    // bug is in the second half
    else hi = mid;                              // bug is in the first half
  }
  return { row: list[lo], steps };
}

const total = rows.reduce((sum, r) => sum + r.price, 0);
console.log("total looks wrong:", typeof total, String(total).slice(0, 25) + "...");
console.log(bisect(rows));

⌨️ Terminal

node bisect.js

🖥️ Output

total looks wrong: string 1370101010101010101010101...
{ row: { id: 138, price: '10' }, steps: 7 }

Seven checks found the one bad row out of 200. The broken total itself is a clue: + with a string switched to string concatenation from that row on (see the Type Conversion lesson).

Checklist of common JavaScript bugs

SymptomUsual cause
Cannot read properties of undefinedMissing data, wrong property name, empty array, or a missing await (you have a Promise)
x is not a functionTypo, wrong import, a getter called with (), or this lost in a callback
Numbers join like "1020"A string from the UI or JSON was not converted
Test passes but should failMissing await before an assertion, swallowed error, or every on an empty list
Works locally, fails in CITiming, different data, environment variables, time zone or locale
Value changes unexpectedlyShared object or array mutated somewhere else (reference, not copy)

📝 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. Read this stack trace and say which function and line to look at first, and why.

TypeError: Cannot read properties of undefined (reading 'email')
    at formatUser (/app/helpers.js:12:21)
    at Array.map (<anonymous>)
    at renderUsers (/app/report.js:30:18)
    at main (/app/index.js:8:3)
Show answer

Start at formatUser in helpers.js, line 12, column 21: it is the top frame in your own code, where something was undefined when .email was read. The next frames show it ran inside an Array.map called from renderUsers, so one of the items passed to map (or a nested object inside it) was missing.

Q2. Print the type of every value in { id: "7", total: 1299, paid: "false", items: [] } to find suspicious types.

Show answer

📄 practice2.js

const order = { id: "7", total: 1299, paid: "false", items: [] };
for (const [key, value] of Object.entries(order)) {
  console.log(key.padEnd(6), Array.isArray(value) ? "array" : typeof value, JSON.stringify(value));
}

🖥️ Output

id     string "7"
total  number 1299
paid   string "false"
items  array []

id and paid are strings: "false" is truthy, a classic bug if the code does if (order.paid).

Q3. Add a debug log that prints only when the environment variable DEBUG_TEST is set to 1.

Show answer

📄 practice3.js

const debug = (...args) => {
  if (process.env.DEBUG_TEST === "1") console.log("[debug]", ...args);
};

debug("loaded 3 users");          // silent unless DEBUG_TEST=1
console.log("test finished");

🖥️ Output

test finished

Run DEBUG_TEST=1 node practice3.js (bash) or set $env:DEBUG_TEST="1" first in PowerShell to see the debug line.

Q4. Which VS Code feature would you use in each case? (a) Pause only when user.role === "admin". (b) Log a value at a line without editing the file. (c) Stop exactly where any error is thrown.

Show answer

(a) A conditional breakpoint with the expression user.role === "admin". (b) A logpoint. (c) The “Uncaught Exceptions” (or “Caught Exceptions”) option in the Breakpoints panel.

Q5. This async function loses the error. Find the bug and fix it so the caller’s catch runs.

async function save() {
  throw new Error("save failed");
}
async function main() {
  try {
    save();
    console.log("saved?");
  } catch (e) {
    console.log("caught:", e.message);
  }
}
main().catch(() => {});
Show answer

📄 practice5.js

async function save() {
  throw new Error("save failed");
}
async function main() {
  try {
    await save();
    console.log("saved?");
  } catch (e) {
    console.log("caught:", e.message);
  }
}
main();

🖥️ Output

caught: save failed

Without await, save() returns a rejected promise and the try block finishes immediately, so “saved?” is printed and the rejection is never caught there.

Q6. Use bisection to find the first test ID in 1–64 at which a (simulated) build starts failing, where builds from ID 41 onwards fail.

Show answer

📄 practice6.js

const fails = (id) => id >= 41;   // simulated: unknown to the searcher
let lo = 1, hi = 64, checks = 0;
while (lo < hi) {
  const mid = Math.floor((lo + hi) / 2);
  checks++;
  if (fails(mid)) hi = mid; else lo = mid + 1;
}
console.log(`first failing ID: ${lo} after ${checks} checks`);

🖥️ Output

first failing ID: 41 after 6 checks

🧠 MCQ Quiz: Debugging in VS Code and DevTools

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 the first step when debugging?
  2. In a stack trace, which line is the most recent call?
  3. What does a conditional breakpoint do?
  4. What is a logpoint?
  5. What does node --inspect-brk app.js do?
  6. Which VS Code key steps into a function call?
  7. Which Playwright command opens the Inspector to step through a test?
  8. What do source maps do?
  9. Why do async stack traces sometimes miss frames?
  10. What is the fastest way to find one bad row among 1,000?

💼 Interview Questions and Answers

Q1. Walk me through how you debug a failing automated test.

  1. Read the failure: error type, message, and the first stack frame in test or framework code.
  2. Reproduce it: run only that test locally (headed, same browser, same data); check whether it fails every time or intermittently.
  3. Inspect evidence: screenshot, video, trace (Playwright trace viewer), console and network logs.
  4. Form and test a hypothesis with breakpoints or targeted logs: wrong locator, timing, data, environment, or a real product bug.
  5. Fix the root cause (or raise a bug with evidence), then rerun several times, and in CI, to confirm it is stable.

Q2. What is the difference between console.log debugging and using a debugger?

Logging is quick and works anywhere (including CI), but you must decide in advance what to print and rerun for each new question. A debugger pauses execution so you can inspect every variable, the call stack and evaluate expressions live, step line by line, and use conditional breakpoints, without editing code. Use logs for CI and distributed timing issues; use the debugger for logic bugs you can reproduce locally.

Q3. A test passes locally but fails in CI. How do you approach it?

Collect artefacts from CI (trace, screenshots, logs, environment details). Compare environments: browser and Node.js versions, screen size, headless mode, time zone and locale, environment variables and test data, CPU speed (timing). Reproduce CI conditions locally (headless, same Docker image, slowed CPU, parallel workers). Typical causes are missing waits or assertions that are not web-first, shared state between parallel tests, and data or configuration differences.

Q4. How do you debug a Node.js script with Chrome DevTools?

Run it with node --inspect-brk script.js (pause on the first line) or --inspect (attach while running). Open chrome://inspect, click inspect under the target, then use the Sources panel to set breakpoints, step, inspect scope and evaluate code; the Memory and Performance tabs profile the process. Keep the inspector bound to localhost.


❓ Frequently Asked Questions

🤔 How do I debug JavaScript in VS Code without configuration?

Open the file and press F5, then choose Node.js, or open a JavaScript Debug Terminal and run your usual command. Breakpoints work immediately.

🤔 What is the debugger statement?

Writing debugger; in code pauses execution at that line whenever a debugger is attached (VS Code, Chrome DevTools, node inspect). Without a debugger it does nothing. Remove it before committing.

🤔 How can I debug a test that only fails sometimes?

Run it many times (Playwright --repeat-each=20), record traces on failure, and look for timing assumptions, shared state and test-order dependencies.

🤔 Do breakpoints work in TypeScript files?

Yes, when source maps are available. Playwright and modern tools generate them automatically.


🏁 Summary

  • Debug with a process: reproduce, read the error, isolate, test a hypothesis, fix the cause and add a check.
  • Read stack traces from the top and start at the first frame in your code; keep await consistent for useful async traces.
  • Use targeted, labelled logs and switchable debug logging; inspect types as well as values.
  • VS Code breakpoints, conditional breakpoints, logpoints, exception breakpoints and watches find logic bugs fast; node --inspect connects Chrome DevTools.
  • For browser code use the Sources panel and source maps; for Playwright use --debug, --ui, page.pause() and the trace viewer.

Next, continue with Lesson 46: Event Loop. This completes Module 9. Module 10 covers asynchronous JavaScript: the event loop, promises and async/await.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Getters, Setters, Private Fields and Private Methods (#)

Sometimes a property should be calculated when it is read (a cart’s total), checked when it is written (an email must contain @), or hidden from outside code completely (an API token). Getters, setters and private fields give classes exactly this control. In this lesson you will learn to write getters and setters, validate values, create read-only and computed properties, and keep internal state truly private with # fields and methods, the language features behind encapsulation.

📖 What You’ll Learn: getters with get, setters with set, computed and read-only properties, validation in setters, getters and setters in object literals, private fields with #, private methods, private static members, checking private membership with in, how private fields differ from the underscore convention and closures, and a secure API client example.


📤 Getters: Properties Computed on Read

Definition: a getter is a method that runs when a property is read. You define it with get name() { ... } and use it like a normal property, without parentheses.

📄 getter.js

class Cart {
  items = [];
  add(price, qty = 1) {
    this.items.push({ price, qty });
    return this;
  }
  get total() {                      // computed every time it is read
    return this.items.reduce((sum, i) => sum + i.price * i.qty, 0);
  }
  get isEmpty() {
    return this.items.length === 0;
  }
}

const cart = new Cart();
console.log(cart.isEmpty, cart.total);
cart.add(10, 3).add(899);
console.log(cart.isEmpty, cart.total);     // no () - it looks like a property
console.log(typeof cart.total);

⌨️ Terminal

node getter.js

🖥️ Output

true 0
false 929
number

A getter always returns the current value, so it never goes out of date the way a stored total property would if someone forgot to update it.

⚠️ Watch out: Calling a getter like a method fails: cart.total() throws TypeError: cart.total is not a function, because cart.total is already the number.


📥 Setters: Control What Is Written

Definition: a setter is a method that runs when a property is assigned, defined with set name(value) { ... }. It is the natural place to validate or normalise input. A setter usually stores the value in another (often private) property.

📄 setter.js

class User {
  #email = "";                         // private storage (explained below)

  get email() {
    return this.#email;
  }
  set email(value) {
    const clean = String(value).trim().toLowerCase();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(clean)) {
      throw new Error(`Invalid email: "${value}"`);
    }
    this.#email = clean;
  }
}

const u = new User();
u.email = "  Asha@SQATools.in ";      // setter runs: trimmed and lower-cased
console.log(u.email);

try {
  u.email = "not-an-email";
} catch (e) {
  console.log(e.message);
}
console.log(u.email);                 // unchanged after the failed assignment

⌨️ Terminal

node setter.js

🖥️ Output

asha@sqatools.in
Invalid email: "not-an-email"
asha@sqatools.in

🔒 Read-Only and Derived Properties

A getter without a setter creates a read-only property. In strict code (ES modules, class bodies, "use strict" files) assigning to it throws; in sloppy scripts the assignment is silently ignored:

📄 readonly.js

"use strict";   // ES modules and test files are strict too

class Temperature {
  constructor(celsius) {
    this.celsius = celsius;
  }
  get fahrenheit() {
    return this.celsius * 9 / 5 + 32;
  }
  set fahrenheit(f) {                 // a setter can update the underlying value
    this.celsius = (f - 32) * 5 / 9;
  }
  get kelvin() {                      // getter only: read-only
    return this.celsius + 273.15;
  }
}

const t = new Temperature(25);
console.log(t.fahrenheit, t.kelvin);
t.fahrenheit = 212;
console.log(t.celsius);
try {
  t.kelvin = 0;
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}

⌨️ Terminal

node readonly.js

🖥️ Output

77 298.15
100
TypeError: Cannot set property kelvin of #<Temperature> which has only a getter

Getters and setters live on the class prototype, so they do not appear in Object.keys or JSON.stringify of an instance. Add a toJSON() method if a computed value should be serialised.


📦 Getters and Setters in Object Literals

Getters and setters also work in plain objects, without a class:

📄 literal.js

const report = {
  passed: 18,
  failed: 2,
  get total() {
    return this.passed + this.failed;
  },
  get passRate() {
    return `${((this.passed / this.total) * 100).toFixed(1)}%`;
  },
  set result(text) {              // parse "17/20" into numbers
    const [p, t] = text.split("/").map(Number);
    this.passed = p;
    this.failed = t - p;
  },
};

console.log(report.total, report.passRate);
report.result = "17/20";
console.log(report.passed, report.failed, report.passRate);

⌨️ Terminal

node literal.js

🖥️ Output

20 90.0%
17 3 85.0%

🔐 Private Fields (#)

Definition: a private field is a class field whose name starts with #. It can only be accessed by code inside the class body. Outside code cannot read, write, list or even detect it; trying to access it is a syntax error. Private fields are enforced by the language (ES2022), not just by convention.

📄 private-fields.js

class ApiClient {
  #token;                             // private
  baseURL;                            // public

  constructor(baseURL, token) {
    this.baseURL = baseURL;
    this.#token = token;
  }

  headers() {
    return { authorization: `Bearer ${this.#token}` };   // inside the class: allowed
  }
}

const client = new ApiClient("https://api.qa", "secret-123");
console.log(client.headers());
console.log(client.token, Object.keys(client), JSON.stringify(client));
console.log(client);

⌨️ Terminal

node private-fields.js

🖥️ Output

{ authorization: 'Bearer secret-123' }
undefined [ 'baseURL' ] {"baseURL":"https://api.qa"}
ApiClient { baseURL: 'https://api.qa' }

The token never appears in Object.keys, JSON output or the property list, which is exactly what you want for credentials that might end up in test logs. Accessing it from outside does not even compile:

📄 private-outside.js

class Secret {
  #value = 42;
}
const s = new Secret();
console.log(s.#value);

⌨️ Terminal

node private-outside.js

🖥️ Output

/home/you/js-course/private-outside.js:5
console.log(s.#value);
             ^

SyntaxError: Private field '#value' must be declared in an enclosing class

Node.js v26.13.0

💡 Tip: Note: console.log(client) in Node.js does not print private fields, but Chrome DevTools does show them when you inspect an object. Privacy protects you from other code, not from someone debugging.


🛠️ Private Methods and Static Private Members

Methods, getters and static members can be private too. Private methods are perfect for internal helper steps that callers should not use directly:

📄 private-methods.js

class OrderService {
  static #instances = 0;               // private static field
  #orders = [];

  constructor() {
    OrderService.#instances++;
  }

  static get instances() {             // public read-only access to a private static
    return OrderService.#instances;
  }

  #validate(order) {                   // private method
    if (!order.id || order.total <= 0) throw new Error(`Invalid order: ${JSON.stringify(order)}`);
  }

  place(order) {
    this.#validate(order);
    this.#orders.push(order);
    return this.#orders.length;
  }
}

const svc = new OrderService();
new OrderService();
console.log(svc.place({ id: 1, total: 499 }), OrderService.instances);
try {
  svc.place({ id: 2, total: 0 });
} catch (e) {
  console.log(e.message);
}
console.log(typeof svc.validate, typeof svc["#validate"]);

⌨️ Terminal

node private-methods.js

🖥️ Output

1 2
Invalid order: {"id":2,"total":0}
undefined undefined

Checking for a private field with in

#field in obj (ES2022) checks whether an object has a given private field, which is a reliable way to test whether an object really is an instance of your class:

📄 private-in.js

class Token {
  #value;
  constructor(v) { this.#value = v; }
  static isToken(obj) {
    return #value in obj;
  }
}
console.log(Token.isToken(new Token("x")), Token.isToken({ value: "x" }));

⌨️ Terminal

node private-in.js

🖥️ Output

true false

⚖️ # Fields vs _underscore vs Closures

TechniqueTruly private?Notes
this._token (underscore)No: just a naming conventionVisible in keys, JSON and logs; anyone can change it
Closure variable in a factory functionYesMethods are recreated for each object
this.#token (private field)Yes, enforced by the languageWorks with classes and inheritance; subclasses cannot access parent # fields

📄 compare.js

class Legacy {
  constructor() { this._password = "hunter2"; }
}
console.log(JSON.stringify(new Legacy()));   // the "private" value leaks into JSON

class Modern {
  #password = "hunter2";
  check(p) { return p === this.#password; }
}
console.log(JSON.stringify(new Modern()), new Modern().check("hunter2"));

⌨️ Terminal

node compare.js

🖥️ Output

{"_password":"hunter2"}
{} true

⚠️ Watch out: Private fields are not inherited in the sense of being accessible: a subclass cannot read this.#parentField. If subclasses need access, expose a protected-style getter or method, or keep the value public.


🧪 Tester Scenario: A Safe, Validated Test Configuration

This configuration class validates every value on the way in, computes derived settings, and keeps the password private so it never appears in logs or reports:

📄 test-config.js

class TestConfig {
  #password;
  #retries = 0;
  env;

  constructor({ env, user, password, retries = 0 }) {
    if (!["qa", "staging", "prod"].includes(env)) throw new Error(`Unknown env "${env}"`);
    this.env = env;
    this.user = user;
    this.#password = password;
    this.retries = retries;              // goes through the setter
  }

  get baseURL() {
    return this.env === "prod" ? "https://www.example.com" : `https://${this.env}.example.com`;
  }
  get retries() {
    return this.#retries;
  }
  set retries(n) {
    if (!Number.isInteger(n) || n < 0 || n > 3) throw new RangeError(`retries must be 0-3, got ${n}`);
    this.#retries = n;
  }
  credentials() {
    return { user: this.user, password: this.#password };
  }
  toJSON() {                               // what reports and logs will show
    return { env: this.env, user: this.user, baseURL: this.baseURL, retries: this.retries, password: "***" };
  }
}

const config = new TestConfig({ env: "staging", user: "qa_bot", password: "S3cret!", retries: 2 });
console.log(JSON.stringify(config));
console.log(config.credentials().password.length, "characters (used for login, never logged)");

for (const bad of [{ env: "dev" }, { env: "qa", retries: 9 }]) {
  try {
    new TestConfig(bad);
  } catch (e) {
    console.log(`${e.name}: ${e.message}`);
  }
}

⌨️ Terminal

node test-config.js

🖥️ Output

{"env":"staging","user":"qa_bot","baseURL":"https://staging.example.com","retries":2,"password":"***"}
7 characters (used for login, never logged)
Error: Unknown env "dev"
RangeError: retries must be 0-3, got 9

📝 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. Write a class Circle with a radius property and getters area and diameter.

Show answer

📄 practice1.js

class Circle {
  constructor(radius) { this.radius = radius; }
  get area() { return +(Math.PI * this.radius ** 2).toFixed(2); }
  get diameter() { return this.radius * 2; }
}
const c = new Circle(3);
console.log(c.area, c.diameter);

🖥️ Output

28.27 6

Q2. Add a setter age to a Person class that rejects values below 0 or above 150 with an error.

Show answer

📄 practice2.js

class Person {
  #age = 0;
  get age() { return this.#age; }
  set age(v) {
    if (!Number.isInteger(v) || v < 0 || v > 150) throw new RangeError(`Invalid age: ${v}`);
    this.#age = v;
  }
}
const p = new Person();
p.age = 29;
console.log(p.age);
try { p.age = -5; } catch (e) { console.log(e.message); }

🖥️ Output

29
Invalid age: -5

Q3. Create a Counter class with a private #count, methods increment() and a read-only getter value. Show that counter.value = 100 does not change it.

Show answer

📄 practice3.js

class Counter {
  #count = 0;
  increment() { this.#count++; return this; }
  get value() { return this.#count; }
}
const c = new Counter().increment().increment();
try { c.value = 100; } catch (e) { console.log(e.constructor.name); }
console.log(c.value);

🖥️ Output

2

Q4. Write an object literal fullName helper with first, last, a getter full and a setter full that splits "Asha Rao" into first and last.

Show answer

📄 practice4.js

const person = {
  first: "",
  last: "",
  get full() { return `${this.first} ${this.last}`.trim(); },
  set full(text) { [this.first, this.last = ""] = text.split(" "); },
};
person.full = "Asha Rao";
console.log(person.first, "|", person.last, "|", person.full);

🖥️ Output

Asha | Rao | Asha Rao

Q5. Write a class Vault with a private method #encrypt(text) (reverse the text) and a public store(text) that returns the encrypted value. Show that #encrypt is not reachable from outside.

Show answer

📄 practice5.js

class Vault {
  #encrypt(text) { return [...text].reverse().join(""); }
  store(text) { return this.#encrypt(text); }
}
const v = new Vault();
console.log(v.store("secret"), typeof v.encrypt);

🖥️ Output

terces undefined

Q6. Explain the output: why does the token not appear?

class Session {
  #token = "abc";
  user = "asha";
}
console.log(JSON.stringify(new Session()), Object.keys(new Session()));
Show answer

📄 practice6.js

class Session {
  #token = "abc";
  user = "asha";
}
console.log(JSON.stringify(new Session()), Object.keys(new Session()));

🖥️ Output

{"user":"asha"} [ 'user' ]

Private fields are not normal properties: they are invisible to Object.keys, for...in and JSON.stringify. Only code inside the class can use them.


🧠 MCQ Quiz: Getters, Setters, Private Fields

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. How do you read a getter named total?
  2. When does a setter run?
  3. What happens when you assign to a getter-only property inside strict code?
  4. How do you declare a private field?
  5. What happens with obj.#secret outside the class?
  6. Do private fields appear in JSON.stringify output?
  7. Can a subclass access its parent’s #private field directly?
  8. What does #field in obj check?
  9. What is the weakness of the _underscore convention?
  10. Why put validation in a setter?

💼 Interview Questions and Answers

Q1. What are getters and setters, and why use them?

Getters (get x()) and setters (set x(v)) are accessor methods that look like normal properties to callers. Getters compute values on read (totals, derived URLs, formatted names) so they are never stale; setters validate or normalise values on write. They let a class change its internal representation without changing its public API.

Q2. How do you create private members in JavaScript?

Modern classes use # private fields, methods, getters and static members, which the language enforces: they cannot be accessed or even detected from outside the class body. Before ES2022, privacy was emulated with closures (factory functions or module scope) or WeakMaps keyed by instance; the underscore prefix is only a convention and provides no protection.

Q3. What is encapsulation, and how do private fields support it?

Encapsulation means hiding an object’s internal state and exposing only a controlled interface. With # fields the state cannot be changed from outside, so every change goes through methods or setters that can enforce rules (validation, invariants, logging). It reduces coupling: callers depend on the public methods, not on how data is stored.

Q4. Predict the output.

📄 predict.js

class Box {
  #items = [];
  get size() { return this.#items.length; }
  add(x) { this.#items.push(x); return this; }
}
const b = new Box().add(1).add(2);
b.size = 10;
console.log(b.size, Object.keys(b));

⌨️ Terminal

node predict.js

🖥️ Output

2 []

This file is not in strict mode outside the class, and assigning b.size = 10 happens outside the class body, so the assignment to a getter-only property is silently ignored. size still reports 2, and the instance has no own enumerable keys.


❓ Frequently Asked Questions

🤔 When should I use a getter instead of a method?

Use a getter for a cheap, side-effect-free value that feels like a property (cart.total, user.fullName). Use a method when the work is expensive, has side effects or needs arguments.

🤔 Are private fields supported everywhere?

Yes. Private fields and methods (ES2022) work in all current browsers and every supported Node.js version, and TypeScript supports them too.

🤔 What is the difference between TypeScript private and #private?

TypeScript’s private keyword is checked only at compile time and the property is public at runtime. #private is enforced by JavaScript itself at runtime.

🤔 Can getters be static?

Yes. static get name() defines a getter on the class itself, useful for read-only access to private static data.


🏁 Summary

  • Getters (get x()) compute values on read; setters (set x(v)) run on assignment and are ideal for validation.
  • A getter without a setter is read-only; accessors live on the prototype and are not serialised.
  • # fields and methods are truly private, enforced by the language and invisible to keys, JSON and outside code.
  • Static members can be private too, and #field in obj checks for genuine instances.
  • Use private fields for secrets and internal state, exposing only safe getters, methods and toJSON output.

Next, continue with Lesson 42: OOP Principles.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Inheritance with extends and super (Classes)

Inheritance lets one class build on another: a LoginPage and a CartPage can both inherit open(), waitForLoad() and a header component from a shared BasePage, and add only what is specific to them. In this lesson you will learn how extends and super work, how to override and extend methods, how static members and built-in classes such as Error are inherited, and when composition is a better choice than a deep class hierarchy.

📖 What You’ll Learn: what inheritance is, extends, calling the parent constructor with super(), the “must call super before this” rule, inherited methods and fields, overriding methods, calling the parent version with super.method(), inherited static members, instanceof with subclasses, extending built-ins such as Error and Array, abstract-style base classes, and composition versus inheritance.


🌳 What Is Inheritance?

Definition: inheritance means a class (the child, subclass or derived class) automatically gets the properties and methods of another class (the parent, superclass or base class). The child can add new members and change inherited ones. In JavaScript you write it with extends.

📄 extends.js

class Animal {
  constructor(name) {
    this.name = name;
  }
  describe() {
    return `${this.name} is an animal`;
  }
}

class Dog extends Animal {
  bark() {
    return `${this.name} says woof`;
  }
}

const rex = new Dog("Rex");
console.log(rex.describe());       // inherited from Animal
console.log(rex.bark());           // defined in Dog
console.log(rex instanceof Dog, rex instanceof Animal);

⌨️ Terminal

node extends.js

🖥️ Output

Rex is an animal
Rex says woof
true true

Dog has no constructor of its own, so JavaScript uses a default one that passes all arguments to the parent constructor.


🔼 super(): Calling the Parent Constructor

When a child class defines its own constructor, it must call super(...) to run the parent constructor before it uses this:

📄 super-constructor.js

class Employee {
  constructor(name, email) {
    this.name = name;
    this.email = email;
  }
}

class Tester extends Employee {
  constructor(name, email, tools = []) {
    super(name, email);        // the parent sets name and email
    this.tools = tools;        // then the child adds its own property
  }
}

const asha = new Tester("Asha", "asha@sqatools.in", ["Playwright", "Postman"]);
console.log(asha);

⌨️ Terminal

node super-constructor.js

🖥️ Output

Tester {
  name: 'Asha',
  email: 'asha@sqatools.in',
  tools: [ 'Playwright', 'Postman' ]
}

Using this before super() is an error, because the object is created by the parent constructor:

📄 super-first.js

class Base {}
class Broken extends Base {
  constructor() {
    this.x = 1;      // too early
    super();
  }
}
try {
  new Broken();
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}

⌨️ Terminal

node super-first.js

🖥️ Output

ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor

🔁 Overriding Methods and super.method()

Definition: overriding means a child class defines a method with the same name as a parent method, replacing it for child instances. Inside the override, super.method() calls the parent version, so you can extend its behaviour instead of rewriting it.

📄 override.js

class Report {
  constructor(title) {
    this.title = title;
  }
  header() {
    return `=== ${this.title} ===`;
  }
  render(lines) {
    return [this.header(), ...lines].join("\n");
  }
}

class CiReport extends Report {
  header() {                                  // override
    return `${super.header()} (CI build #4512)`;   // extend the parent version
  }
}

console.log(new Report("Smoke").render(["12 passed"]));
console.log(new CiReport("Smoke").render(["12 passed"]));

⌨️ Terminal

node override.js

🖥️ Output

=== Smoke ===
12 passed
=== Smoke === (CI build #4512)
12 passed

Notice that render is defined only in Report, yet it calls the child’s header() for a CiReport. Method lookup always starts from the actual object, which is the core of polymorphism (lesson 42).


📋 Inherited Fields and Static Members

Class fields and static members are inherited too. Static methods are called on the child class and can be overridden in the same way:

📄 statics.js

class BaseClient {
  static defaultTimeout = 30000;
  retries = 0;

  static create(baseURL) {
    return new this(baseURL);      // "this" is the class it was called on
  }
  constructor(baseURL) {
    this.baseURL = baseURL;
  }
}

class PaymentsClient extends BaseClient {
  static defaultTimeout = 60000;   // override the static field
  retries = 2;                     // override the field default
}

const base = BaseClient.create("https://api.qa");
const pay = PaymentsClient.create("https://pay.qa");
console.log(base.constructor.name, base.retries, BaseClient.defaultTimeout);
console.log(pay.constructor.name, pay.retries, PaymentsClient.defaultTimeout, pay instanceof BaseClient);

⌨️ Terminal

node statics.js

🖥️ Output

BaseClient 0 30000
PaymentsClient 2 60000 true

new this(...) inside a static method creates an instance of whichever class the method was called on, so the inherited create returns a PaymentsClient.


🔗 The Prototype Chain Behind extends

extends sets up two prototype links: instances of the child inherit from the parent’s prototype, and the child class itself inherits from the parent class (for static members). It is the same mechanism you saw in the Prototypes lesson:

📄 chain.js

class A { hello() { return "hello from A"; } }
class B extends A {}
const b = new B();

console.log(Object.getPrototypeOf(b) === B.prototype);
console.log(Object.getPrototypeOf(B.prototype) === A.prototype);   // instance chain
console.log(Object.getPrototypeOf(B) === A);                       // static chain
console.log(Object.hasOwn(B.prototype, "hello"), b.hello());

⌨️ Terminal

node chain.js

🖥️ Output

true
true
true
false hello from A

⚠️ Extending Built-ins: Custom Errors

You can extend built-in classes such as Error, Array and Map. The most useful case in testing is a custom error that carries extra context. Module 9 covers error handling in depth.

📄 extend-builtins.js

class ApiError extends Error {
  constructor(message, { status, url } = {}) {
    super(message);              // sets message and the stack trace
    this.name = "ApiError";
    this.status = status;
    this.url = url;
  }
}

function checkResponse(res) {
  if (res.status >= 400) {
    throw new ApiError(`Request failed with ${res.status}`, res);
  }
  return res;
}

try {
  checkResponse({ status: 503, url: "/api/orders" });
} catch (e) {
  console.log(e instanceof ApiError, e instanceof Error);
  console.log(`${e.name}: ${e.message} (${e.url})`);
}

class TagList extends Array {
  hasTag(tag) { return this.includes(tag); }
}
const tags = TagList.from(["smoke", "p1"]);
console.log(tags.hasTag("p1"), tags.filter((t) => t !== "p1") instanceof TagList);

⌨️ Terminal

node extend-builtins.js

🖥️ Output

true true
ApiError: Request failed with 503 (/api/orders)
true true

Array methods such as filter return instances of the subclass, so the result still has hasTag.


🧱 Abstract-Style Base Classes

JavaScript has no abstract keyword, but you can enforce the same rules: prevent creating the base class directly with new.target, and throw if a child forgets to implement a required method:

📄 abstract.js

class Shape {
  constructor() {
    if (new.target === Shape) throw new TypeError("Shape is abstract; create a subclass");
  }
  area() {
    throw new Error(`${this.constructor.name} must implement area()`);
  }
  describe() {
    return `${this.constructor.name} with area ${this.area().toFixed(2)}`;
  }
}

class Circle extends Shape {
  constructor(r) { super(); this.r = r; }
  area() { return Math.PI * this.r ** 2; }
}
class Square extends Shape {
  constructor(side) { super(); this.side = side; }   // forgot area()
}

console.log(new Circle(2).describe());
for (const attempt of [() => new Shape(), () => new Square(3).describe()]) {
  try { attempt(); } catch (e) { console.log(e.message); }
}

⌨️ Terminal

node abstract.js

🖥️ Output

Circle with area 12.57
Shape is abstract; create a subclass
Square must implement area()

🧩 Composition vs Inheritance

Inheritance models an “is a” relationship (a Tester is an Employee). Composition models a “has a” relationship: an object holds other objects and uses them. Deep inheritance trees become rigid; composition keeps pieces small and reusable.

📄 composition.js

// Composition: a page HAS a header and a cart widget
class Header {
  constructor(page) { this.page = page; }
  search(term) { return `${this.page}: search "${term}"`; }
}
class CartWidget {
  constructor(page) { this.page = page; }
  count() { return `${this.page}: read cart count`; }
}

class ProductPage {
  constructor() {
    this.header = new Header("ProductPage");
    this.cart = new CartWidget("ProductPage");
  }
}

const product = new ProductPage();
console.log(product.header.search("laptop"));
console.log(product.cart.count());

⌨️ Terminal

node composition.js

🖥️ Output

ProductPage: search "laptop"
ProductPage: read cart count

💡 Tip: A common, healthy design for test frameworks: one shallow BasePage for truly shared behaviour (open, wait, title), and components (header, footer, modal, table) composed into pages. Avoid chains like BasePage → AuthenticatedPage → AdminPage → AdminUsersPage.


🧪 Tester Scenario: A BasePage and Two Page Objects

📄 pages.js

class FakePage {
  log = [];
  goto(url) { this.log.push(`goto ${url}`); }
  fill(sel, v) { this.log.push(`fill ${sel}=${v}`); }
  click(sel) { this.log.push(`click ${sel}`); }
}

class BasePage {
  path = "/";
  constructor(page, baseURL = "https://qa.example.com") {
    this.page = page;
    this.baseURL = baseURL;
  }
  open() {
    this.page.goto(this.baseURL + this.path);
    return this;
  }
  logout() {
    this.page.click("#logout");
  }
}

class LoginPage extends BasePage {
  path = "/login";
  login(user, pass) {
    this.page.fill("#email", user);
    this.page.fill("#password", "***");
    this.page.click("button[type=submit]");
    return this;
  }
}

class CartPage extends BasePage {
  path = "/cart";
  open() {                         // extend the shared behaviour
    super.open();
    this.page.click("#accept-cookies");
    return this;
  }
  checkout() {
    this.page.click("#checkout");
  }
}

const page = new FakePage();
new LoginPage(page).open().login("asha@sqatools.in", "Secret@1");
new CartPage(page).open().checkout();
new CartPage(page).logout();          // inherited from BasePage
console.log(page.log.join("\n"));

⌨️ Terminal

node pages.js

🖥️ Output

goto https://qa.example.com/login
fill #email=asha@sqatools.in
fill #password=***
click button[type=submit]
goto https://qa.example.com/cart
click #accept-cookies
click #checkout
click #logout

Each page object declares only what is different: its path and its own actions. CartPage overrides open but reuses the base version with super.open().


📝 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. Create a class Vehicle with wheels and a method info(), and a subclass Bike that sets wheels to 2. Print new Bike().info().

Show answer

📄 practice1.js

class Vehicle {
  constructor(wheels) { this.wheels = wheels; }
  info() { return `${this.constructor.name} with ${this.wheels} wheels`; }
}
class Bike extends Vehicle {
  constructor() { super(2); }
}
console.log(new Bike().info());

🖥️ Output

Bike with 2 wheels

Q2. Override toString() in a subclass Admin of User so it adds " (admin)" to the parent result, using super.

Show answer

📄 practice2.js

class User {
  constructor(name) { this.name = name; }
  toString() { return `User ${this.name}`; }
}
class Admin extends User {
  toString() { return `${super.toString()} (admin)`; }
}
console.log(String(new User("Ravi")), "|", String(new Admin("Asha")));

🖥️ Output

User Ravi | User Asha (admin)

Q3. Write class ValidationError extends Error with a field property, throw it for an empty email, and print the name, message and field.

Show answer

📄 practice3.js

class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
  }
}
try {
  const email = "";
  if (!email) throw new ValidationError("email", "Email is required");
} catch (e) {
  console.log(e.name, "|", e.message, "|", e.field, "|", e instanceof Error);
}

🖥️ Output

ValidationError | Email is required | email | true

Q4. Predict the output, then run it.

class A {
  who() { return "A"; }
  hello() { return `hello from ${this.who()}`; }
}
class B extends A {
  who() { return "B"; }
}
console.log(new A().hello(), "|", new B().hello());
Show answer

📄 practice4.js

class A {
  who() { return "A"; }
  hello() { return `hello from ${this.who()}`; }
}
class B extends A {
  who() { return "B"; }
}
console.log(new A().hello(), "|", new B().hello());

🖥️ Output

hello from A | hello from B

hello is inherited, but this.who() is looked up on the actual object, so a B instance uses B‘s who.

Q5. Give Animal a static method create(...args) that returns new this(...args), and show that Cat.create("Tom") returns a Cat.

Show answer

📄 practice5.js

class Animal {
  constructor(name) { this.name = name; }
  static create(...args) { return new this(...args); }
}
class Cat extends Animal {}
const tom = Cat.create("Tom");
console.log(tom instanceof Cat, tom.constructor.name, tom.name);

🖥️ Output

true Cat Tom

Q6. Rewrite this inheritance as composition: class Car extends Engine is wrong because a car is not an engine. Make Car have an engine and delegate start() to it.

Show answer

📄 practice6.js

class Engine {
  start() { return "engine started"; }
}
class Car {
  constructor() { this.engine = new Engine(); }
  start() { return `car: ${this.engine.start()}`; }
}
console.log(new Car().start());

🖥️ Output

car: engine started

🧠 MCQ Quiz: Inheritance

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. Which keyword creates a subclass?
  2. What must a child constructor do before using this?
  3. How do you call the parent version of an overridden method?
  4. If a child class has no constructor, what happens?
  5. Is new Dog() instanceof Animal true when Dog extends Animal?
  6. Are static methods inherited by subclasses?
  7. What does new.target help you do?
  8. When you extend Error, what should the constructor call first?
  9. Which describes composition?
  10. In a parent method, which version of this.helper() runs for a child instance?

💼 Interview Questions and Answers

Q1. How does inheritance work in JavaScript classes?

class Child extends Parent links Child.prototype to Parent.prototype (for instance methods) and Child to Parent (for static members). A child constructor must call super(...) before using this. Methods can be overridden, and super.method() calls the parent implementation. Under the hood it is prototype-based inheritance.

Q2. What is the difference between overriding and overloading?

Overriding is redefining a parent method with the same name in a child class, which JavaScript supports. Overloading is defining several methods with the same name but different parameter lists, which JavaScript does not support: a later definition simply replaces the earlier one. Instead, use default parameters, rest parameters or an options object and check the arguments inside one method.

Q3. When should you prefer composition over inheritance?

When the relationship is “has a” rather than “is a”, when behaviour must be mixed and matched (a page may or may not have a search bar, a cart widget or a modal), or when a hierarchy is getting deeper than two levels. Composition keeps classes small and independent, and avoids fragile base classes where one change breaks many children. Use shallow inheritance for genuinely shared core behaviour.

Q4. Why does a custom error class call super(message) and set this.name?

📄 timeout-error.js

class TimeoutError extends Error {
  constructor(ms) {
    super(`Timed out after ${ms} ms`);
    this.name = "TimeoutError";
  }
}
const e = new TimeoutError(5000);
console.log(e.name, "-", e.message, "-", e.stack.split("\n")[0]);

⌨️ Terminal

node timeout-error.js

🖥️ Output

TimeoutError - Timed out after 5000 ms - TimeoutError: Timed out after 5000 ms

super(message) lets Error set message and capture the stack trace. Setting name makes the error type appear in logs and stack traces, and lets code distinguish errors by instanceof or name.


❓ Frequently Asked Questions

🤔 Does JavaScript support multiple inheritance?

No. A class can extend only one class. Use composition or mixins (functions that add methods to a class) to combine behaviour from several sources.

🤔 Can I extend a class from a library or a built-in?

Yes. You can extend built-ins like Error, Array, Map and EventEmitter, and classes exported by libraries.

🤔 What is the difference between super() and super.method()?

super(...) calls the parent constructor and is only allowed in a child constructor. super.method() calls a parent method and can be used in any method of the child.

🤔 How deep should a class hierarchy be?

Usually one or two levels. Deeper hierarchies are hard to understand and change; prefer composition instead.


🏁 Summary

  • class Child extends Parent inherits instance methods, fields and static members.
  • A child constructor must call super(...) before using this.
  • Override methods by redefining them, and extend them with super.method().
  • Extend built-ins such as Error for custom errors; use new.target for abstract-style base classes.
  • Prefer shallow hierarchies and composition (“has a”) over deep inheritance trees.

Next, continue with Lesson 41: Getters, Setters, Private Fields.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

OOP Principles in JavaScript: Encapsulation, Abstraction, Inheritance, Polymorphism

“Explain the four pillars of OOP” is one of the most common interview questions for testers and developers, and the answer matters in practice too: well-designed test frameworks use exactly these ideas to stay readable as they grow to hundreds of tests. In this lesson you will see encapsulation, abstraction, inheritance and polymorphism in JavaScript code, learn JavaScript-specific ideas such as duck typing and mixins, get a first look at the SOLID principles, and finish with a reporter design that uses all four pillars.

📖 What You’ll Learn: the four pillars of object-oriented programming, encapsulation with private fields, abstraction with simple public interfaces, inheritance with extends, polymorphism through method overriding and duck typing, mixins, composition, an introduction to SOLID, and a pluggable test reporter that applies everything.


🏛️ The Four Pillars of OOP

Definition: object-oriented programming (OOP) organises code around objects that combine data (properties) and behaviour (methods). Four principles describe how good object-oriented code is structured:

PillarIn one sentenceJavaScript tools
EncapsulationKeep an object’s data and the code that changes it together, and hide the internals#private fields, getters/setters, closures
AbstractionExpose a simple interface and hide the complex details of how it worksPublic methods with clear names; private helper methods
InheritanceLet a class reuse and extend another classextends, super, prototypes
PolymorphismUse different objects through the same interface, each behaving in its own wayMethod overriding, duck typing

The earlier lessons in this module taught the syntax: classes, inheritance and private fields. This lesson is about why and when to use them.


🔒 Encapsulation

Definition: encapsulation means bundling data with the methods that operate on it, and restricting direct access to the data so it can only change in controlled ways.

📄 encapsulation.js

class BankAccount {
  #balance = 0;                 // hidden state
  #history = [];

  deposit(amount) {
    if (amount <= 0) throw new Error("Deposit must be positive");
    this.#balance += amount;
    this.#history.push(`+${amount}`);
  }

  withdraw(amount) {
    if (amount > this.#balance) throw new Error("Insufficient funds");
    this.#balance -= amount;
    this.#history.push(`-${amount}`);
  }

  get balance() { return this.#balance; }        // read-only view
  get history() { return [...this.#history]; }  // a copy, so callers cannot change it
}

const acc = new BankAccount();
acc.deposit(500);
acc.withdraw(120);
console.log(acc.balance, acc.history);

acc.history.push("+1000000");   // only changes the copy
acc.balance = 1e9;               // ignored: getter only (sloppy mode outside the class)
console.log(acc.balance, acc.history);

⌨️ Terminal

node encapsulation.js

🖥️ Output

380 [ '+500', '-120' ]
380 [ '+500', '-120' ]

Every rule (no negative deposits, no overdrafts) is enforced in one place. No outside code can put the account into an invalid state, which is the real goal of encapsulation.


🎭 Abstraction

Definition: abstraction means exposing only what callers need (the “what”) and hiding how it is done (the “how”). Callers depend on a small, stable interface, so the internals can change without breaking them.

📄 abstraction.js

class EmailService {
  send(to, subject) {                          // the whole public interface
    this.#validate(to);
    const message = this.#build(to, subject);
    return this.#deliver(message);
  }

  #validate(to) {
    if (!to.includes("@")) throw new Error(`Bad address: ${to}`);
  }
  #build(to, subject) {
    return { to, subject, headers: { "x-mailer": "sqa-mailer/1.0" } };
  }
  #deliver(message) {                          // could switch from SMTP to an API without callers noticing
    return `queued "${message.subject}" for ${message.to}`;
  }
}

const mail = new EmailService();
console.log(mail.send("asha@sqatools.in", "Nightly report"));
console.log(Object.getOwnPropertyNames(EmailService.prototype));   // only send is public

⌨️ Terminal

node abstraction.js

🖥️ Output

queued "Nightly report" for asha@sqatools.in
[ 'constructor', 'send' ]

💡 Tip: Page objects are abstraction in action: a test calls loginPage.login(user) and does not care which selectors, waits or clicks happen inside. When the login form changes, only the page object changes.


🌳 Inheritance

Definition: inheritance lets a class reuse the code of a more general class and add or change behaviour. Use it for genuine “is a” relationships and keep hierarchies shallow.

📄 inheritance.js

class Notification {
  constructor(recipient) { this.recipient = recipient; }
  format(text) { return `To ${this.recipient}: ${text}`; }
  send(text) { return `[${this.constructor.name}] ${this.format(text)}`; }
}

class SmsNotification extends Notification {
  format(text) { return super.format(text).slice(0, 40); }   // SMS has a length limit
}

class SlackNotification extends Notification {
  format(text) { return `${super.format(text)} :white_check_mark:`; }
}

console.log(new SmsNotification("+91 98765 43210").send("Build 4512 passed all 1,204 tests in 18 minutes"));
console.log(new SlackNotification("#qa-alerts").send("Build 4512 passed"));

⌨️ Terminal

node inheritance.js

🖥️ Output

[SmsNotification] To +91 98765 43210: Build 4512 passed al
[SlackNotification] To #qa-alerts: Build 4512 passed :white_check_mark:

Both subclasses reuse send from the parent and change only the part that differs.


🔀 Polymorphism

Definition: polymorphism (“many forms”) means code can work with objects of different types through the same interface, and each object responds in its own way. The calling code does not need if/else or switch on the type.

📄 polymorphism.js

class Shape { area() { return 0; } }
class Circle extends Shape {
  constructor(r) { super(); this.r = r; }
  area() { return Math.PI * this.r ** 2; }
}
class Rect extends Shape {
  constructor(w, h) { super(); this.w = w; this.h = h; }
  area() { return this.w * this.h; }
}

const shapes = [new Circle(1), new Rect(2, 3), new Circle(2)];
for (const s of shapes) {
  console.log(s.constructor.name.padEnd(7), s.area().toFixed(2));   // same call, different behaviour
}
console.log("total:", shapes.reduce((sum, s) => sum + s.area(), 0).toFixed(2));

⌨️ Terminal

node polymorphism.js

🖥️ Output

Circle  3.14
Rect    6.00
Circle  12.57
total: 21.71

Duck typing

JavaScript does not require a shared parent class for polymorphism. If an object has the method you call, it works: “if it walks like a duck and quacks like a duck, it is a duck”. This is called duck typing.

📄 duck-typing.js

const consoleLogger = { log: (m) => `console: ${m}` };
const fileLogger = { log: (m) => `file: ${m}` };
class JsonLogger { log(m) { return JSON.stringify({ level: "info", m }); } }

function runWithLogger(logger) {
  return logger.log("test started");     // only needs a log method
}

for (const logger of [consoleLogger, fileLogger, new JsonLogger()]) {
  console.log(runWithLogger(logger));
}

try {
  runWithLogger({ write: () => "wrong shape" });
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}

⌨️ Terminal

node duck-typing.js

🖥️ Output

console: test started
file: test started
{"level":"info","m":"test started"}
TypeError: logger.log is not a function

Playwright reporters work this way: any object with methods such as onTestEnd and onEnd can be a reporter, without extending a framework class.


🧩 Mixins and Composition

JavaScript classes can extend only one parent. To share behaviour across unrelated classes, use composition (an object holds helpers, see the Inheritance lesson) or a mixin: a function that takes a class and returns a subclass with extra methods.

📄 mixins.js

const Timestamped = (Base) => class extends Base {
  stamp() { return `${this.constructor.name} at 2026-11-23T10:00:00Z`; }
};
const Serializable = (Base) => class extends Base {
  serialize() { return JSON.stringify(this); }
};

class TestResult {
  constructor(name, passed) { this.name = name; this.passed = passed; }
}

class RichResult extends Serializable(Timestamped(TestResult)) {}

const r = new RichResult("login", true);
console.log(r.serialize());
console.log(r.stamp(), r instanceof TestResult);

⌨️ Terminal

node mixins.js

🖥️ Output

{"name":"login","passed":true}
RichResult at 2026-11-23T10:00:00Z true

⚠️ Watch out: Stacking many mixins makes it hard to see where a method comes from. Prefer composition for most cases, and keep mixins small and focused.


🧱 A First Look at SOLID

SOLID is a set of five design principles that build on the four pillars. Test framework code benefits from them as much as application code:

PrincipleMeaningTest-framework example
Single responsibilityA class should have one reason to changeA page object handles one page; an API client handles one service
Open/closedOpen for extension, closed for modificationAdd a new reporter without editing the runner
Liskov substitutionSubclasses must work wherever the parent worksAny BasePage subclass supports open()
Interface segregationPrefer small, focused interfacesSeparate Clickable and Typeable component helpers
Dependency inversionDepend on abstractions, inject dependenciesPass page or an API client into constructors instead of creating them inside

The Playwright course covers these in depth in SOLID Principles with Playwright.


🧪 Tester Scenario: A Pluggable Test Reporter

This design uses all four pillars. The runner (abstraction) hides how tests are executed and keeps results private (encapsulation). Reporters share a base class (inheritance) and the runner calls each one through the same methods (polymorphism), so adding a new output format never requires changing the runner (open/closed principle).

📄 reporter.js

class Reporter {
  onTestEnd(result) {}
  onEnd(summary) {}
}

class ConsoleReporter extends Reporter {
  onTestEnd(r) { console.log(`  ${r.passed ? "✓" : "✗"} ${r.name}`); }
  onEnd(s) { console.log(`  ${s.passed}/${s.total} passed`); }
}

class JsonReporter extends Reporter {
  #results = [];
  onTestEnd(r) { this.#results.push(r); }
  onEnd(s) { console.log("  json:", JSON.stringify({ ...s, failures: this.#results.filter((r) => !r.passed).map((r) => r.name) })); }
}

const slackReporter = {                           // duck-typed: no base class needed
  onTestEnd() {},
  onEnd: (s) => console.log(`  slack: ${s.failed === 0 ? "all green" : `${s.failed} failing`}`),
};

class Runner {
  #tests = [];
  #reporters;
  constructor(reporters) { this.#reporters = reporters; }        // dependency injection
  add(name, fn) { this.#tests.push({ name, fn }); return this; }
  run() {
    let passed = 0;
    for (const { name, fn } of this.#tests) {
      let ok = true;
      try { fn(); } catch { ok = false; }
      if (ok) passed++;
      this.#reporters.forEach((rep) => rep.onTestEnd({ name, passed: ok }));
    }
    const summary = { total: this.#tests.length, passed, failed: this.#tests.length - passed };
    this.#reporters.forEach((rep) => rep.onEnd(summary));
  }
}

new Runner([new ConsoleReporter(), new JsonReporter(), slackReporter])
  .add("login works", () => {})
  .add("cart total", () => { if (10 + 20 !== 30) throw new Error(); })
  .add("checkout", () => { throw new Error("500 from payment API"); })
  .run();

⌨️ Terminal

node reporter.js

🖥️ Output

  ✓ login works
  ✓ cart total
  ✗ checkout
  2/3 passed
  json: {"total":3,"passed":2,"failed":1,"failures":["checkout"]}
  slack: 1 failing

Playwright’s real reporter API follows the same idea: you list reporters in playwright.config, and each receives the same events.


📝 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. Write a class Thermostat that encapsulates a private temperature, allows changes only through increase() and decrease(), and never goes below 10 or above 30.

Show answer

📄 practice1.js

class Thermostat {
  #temp = 20;
  increase() { this.#temp = Math.min(30, this.#temp + 1); return this; }
  decrease() { this.#temp = Math.max(10, this.#temp - 1); return this; }
  get temperature() { return this.#temp; }
}
const t = new Thermostat();
for (let i = 0; i < 15; i++) t.increase();
console.log(t.temperature);
for (let i = 0; i < 30; i++) t.decrease();
console.log(t.temperature);

🖥️ Output

30
10

Q2. Create Employee with pay(), and subclasses FullTime (monthly salary) and Contractor (hours × rate) that override it. Print the total payroll for a mixed list.

Show answer

📄 practice2.js

class Employee {
  constructor(name) { this.name = name; }
  pay() { return 0; }
}
class FullTime extends Employee {
  constructor(name, salary) { super(name); this.salary = salary; }
  pay() { return this.salary; }
}
class Contractor extends Employee {
  constructor(name, hours, rate) { super(name); this.hours = hours; this.rate = rate; }
  pay() { return this.hours * this.rate; }
}
const staff = [new FullTime("Asha", 90000), new Contractor("Ravi", 120, 600), new FullTime("Meera", 75000)];
console.log(staff.reduce((sum, e) => sum + e.pay(), 0));

🖥️ Output

237000

Q3. Use duck typing: write describeAll(items) that prints item.describe() for every item that has a describe method and skips the others.

Show answer

📄 practice3.js

function describeAll(items) {
  for (const item of items) {
    if (typeof item?.describe === "function") console.log(item.describe());
  }
}
describeAll([
  { describe: () => "a plain object" },
  new (class Book { describe() { return "a Book instance"; } })(),
  { name: "no describe method" },
  null,
]);

🖥️ Output

a plain object
a Book instance

Q4. Write a mixin Countable that adds a static created counter incremented in the constructor, and apply it to a class Order.

Show answer

📄 practice4.js

const Countable = (Base) => class extends Base {
  static created = 0;
  constructor(...args) {
    super(...args);
    this.constructor.created++;
  }
};
class Order extends Countable(class {}) {}
new Order(); new Order(); new Order();
console.log(Order.created);

🖥️ Output

3

Q5. Which OOP pillar does each describe? (a) a page object hides selectors behind login(); (b) #token cannot be read outside the class; (c) AdminPage extends BasePage; (d) the runner calls onEnd() on any reporter.

Show answer

(a) Abstraction, (b) Encapsulation, (c) Inheritance, (d) Polymorphism.

Q6. Refactor this switch into polymorphism: each payment method should be an object with a fee(amount) method.

function fee(method, amount) {
  switch (method) {
    case "card": return amount * 0.02;
    case "upi": return 0;
    case "wallet": return amount * 0.01;
  }
}
Show answer

📄 practice6.js

const methods = {
  card: { fee: (amount) => amount * 0.02 },
  upi: { fee: () => 0 },
  wallet: { fee: (amount) => amount * 0.01 },
};
for (const [name, method] of Object.entries(methods)) {
  console.log(name, method.fee(1000));
}

🖥️ Output

card 20
upi 0
wallet 10

Adding a new payment method now means adding one object, without touching existing code (open/closed principle).


🧠 MCQ Quiz: OOP Principles

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. Which pillar is about hiding internal state and controlling changes to it?
  2. Which pillar lets the same method call behave differently for different objects?
  3. A page object exposes login(user) and hides its selectors. Which pillar is that mainly?
  4. What is duck typing?
  5. How many classes can a JavaScript class extend directly?
  6. What is a mixin in JavaScript?
  7. What does the “O” in SOLID stand for?
  8. Why return a copy from a getter like get history()?
  9. What is dependency injection?
  10. Which is the best sign you should use composition instead of inheritance?

💼 Interview Questions and Answers

Q1. Explain the four pillars of OOP with JavaScript examples.

  • Encapsulation: a BankAccount keeps #balance private and changes it only through deposit/withdraw, which validate input.
  • Abstraction: a LoginPage.login(user) method hides selectors, waits and clicks behind one intent-based call.
  • Inheritance: class CartPage extends BasePage reuses open() and navigation helpers.
  • Polymorphism: a test runner calls reporter.onEnd(summary) on console, JSON and HTML reporters, and each produces its own output.

Q2. What is the difference between abstraction and encapsulation?

Abstraction is about design: deciding what a caller needs to know and offering a simple interface (what the object does). Encapsulation is about protection: bundling data with its methods and restricting access to the data (how the object keeps its state valid). Private helper methods and fields support both: they hide complexity (abstraction) and protect state (encapsulation).

Q3. How is polymorphism achieved in JavaScript, given it has no interfaces?

Through method overriding in class hierarchies (a subclass redefines a method), and through duck typing: any object with the expected methods can be used, whatever its class. TypeScript adds compile-time interface checks, but at runtime JavaScript simply calls the method if it exists. Guard optional capabilities with checks like typeof obj.method === "function".

Q4. How do OOP principles show up in a Playwright test framework?

Page objects and components encapsulate selectors and expose intent-based methods (abstraction, encapsulation); a shallow BasePage shares navigation and waits (inheritance); fixtures inject page and API clients into page objects (dependency inversion); and custom reporters or data providers are interchangeable objects with the same methods (polymorphism). The result is tests that read like specifications and change in one place when the UI changes.


❓ Frequently Asked Questions

🤔 Is JavaScript an object-oriented language?

Yes, but it is multi-paradigm. It supports OOP through objects, prototypes and classes, and also supports functional and procedural styles. Many projects mix them.

🤔 Do I need classes to use OOP in JavaScript?

No. Objects, closures and factory functions can provide encapsulation and polymorphism. Classes are a convenient, widely understood syntax for it.

🤔 What is the difference between OOP and functional programming?

OOP organises code around objects that hold state and behaviour. Functional programming organises code around pure functions and immutable data. Module 13 covers functional programming.

🤔 Which OOP question is asked most in QA interviews?

Explaining the four pillars with examples from a test framework (usually the Page Object Model), and the difference between overloading and overriding.


🏁 Summary

  • Encapsulation: keep state private and change it only through validated methods.
  • Abstraction: offer a small, intent-based public interface and hide the details.
  • Inheritance: reuse and extend shared behaviour with extends, keeping hierarchies shallow.
  • Polymorphism: call the same method on different objects; JavaScript supports it through overriding and duck typing.
  • Mixins, composition and SOLID principles keep object-oriented test frameworks flexible as they grow.

Next, continue with Lesson 43: Exception Handling. This completes Module 8. Module 9 covers errors and debugging, starting with exception handling.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Classes: Constructor, Methods, Fields and Static Members

A class is a blueprint for creating many objects with the same shape and behaviour: many test cases, many users, many pages. Classes are the backbone of the Page Object Model used in almost every Playwright, Selenium and WebdriverIO framework. In this lesson you will learn how to write a class with a constructor, methods and fields, create objects with new, use static members for shared helpers, and avoid the common class mistakes, ending with a small page object.

📖 What You’ll Learn: class syntax, the constructor, creating instances with new, instance methods, class fields, method chaining, static methods and fields, static blocks, class expressions, this inside classes and callbacks, classes versus factory functions, and building a page object class.


🏗️ Class Syntax and the Constructor

Definition: a class is a template for creating objects. Each object created from it is an instance. The special constructor method runs once when an instance is created with new, and usually sets the instance’s properties.

📄 class.js

class User {
  constructor(name, role = "tester") {
    this.name = name;          // this = the new instance
    this.role = role;
    this.createdAt = "2026-11-23";
  }
}

const asha = new User("Asha");
const ravi = new User("Ravi", "admin");

console.log(asha);
console.log(ravi.role, asha instanceof User, typeof User);

⌨️ Terminal

node class.js

🖥️ Output

User { name: 'Asha', role: 'tester', createdAt: '2026-11-23' }
admin true function
  • Class names use PascalCase: User, LoginPage, ApiClient.
  • A class can have only one constructor. If you omit it, an empty one is used.
  • Class bodies always run in strict mode.

Unlike constructor functions, classes must be called with new, and they are not hoisted for use before their definition:

📄 no-new.js

class Report {}
try {
  Report();
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}

⌨️ Terminal

node no-new.js

🖥️ Output

TypeError: Class constructor Report cannot be invoked without 'new'

🛠️ Instance Methods

Methods are written inside the class body without the function keyword. They are stored once on the prototype and shared by all instances (see the Prototypes lesson).

📄 methods.js

class Cart {
  constructor() {
    this.items = [];
  }

  add(name, price, qty = 1) {
    this.items.push({ name, price, qty });
    return this;                 // return this to allow chaining
  }

  remove(name) {
    this.items = this.items.filter((i) => i.name !== name);
    return this;
  }

  total() {
    return this.items.reduce((sum, i) => sum + i.price * i.qty, 0);
  }

  get count() {                  // a getter, covered in lesson 41
    return this.items.length;
  }
}

const cart = new Cart().add("Pen", 10, 3).add("Lamp", 899).add("Mug", 199).remove("Mug");
console.log(cart.total(), cart.count);
console.log(Object.keys(cart), typeof Cart.prototype.add);

⌨️ Terminal

node methods.js

🖥️ Output

929 2
[ 'items' ] function

📋 Class Fields

Class fields (ES2022) declare instance properties directly in the class body, with optional initial values. Each instance gets its own copy. They make the shape of an object visible at a glance:

📄 fields.js

class TestRun {
  status = "pending";             // field with a default value
  results = [];                   // each instance gets its own array
  startedAt;                      // declared, initially undefined

  constructor(suite) {
    this.suite = suite;
    this.startedAt = new Date(Date.UTC(2026, 10, 23, 10)).toISOString();
  }

  record(test, passed) {
    this.results.push({ test, passed });
    this.status = this.results.every((r) => r.passed) ? "passing" : "failing";
  }
}

const a = new TestRun("smoke");
const b = new TestRun("regression");
a.record("login", true);
b.record("cart", false);
console.log(a.status, a.results.length, "|", b.status, b.results.length);
console.log(a);

⌨️ Terminal

node fields.js

🖥️ Output

passing 1 | failing 1
TestRun {
  status: 'passing',
  results: [ { test: 'login', passed: true } ],
  startedAt: '2026-11-23T10:00:00.000Z',
  suite: 'smoke'
}

💡 Tip: Field initialisers run for every new instance, before the constructor body. So results = [] gives every instance a separate array, unlike a value shared on the prototype.


🏷️ Static Methods and Fields

Definition: a static member belongs to the class itself, not to its instances. Call it on the class (ClassName.method()). Static members are used for helpers, factory methods, constants and counters that relate to the class as a whole.

📄 static.js

class User {
  static count = 0;                       // static field: shared by the class
  static ROLES = ["viewer", "tester", "admin"];

  constructor(name, role) {
    if (!User.ROLES.includes(role)) throw new Error(`Invalid role: ${role}`);
    this.name = name;
    this.role = role;
    User.count++;
  }

  static fromEmail(email) {               // static factory method
    const name = email.split("@")[0];
    return new User(name, "viewer");
  }

  static compareByName(a, b) {
    return a.name.localeCompare(b.name);
  }
}

const users = [new User("ravi", "admin"), User.fromEmail("asha@sqatools.in"), new User("meera", "tester")];
console.log(User.count, users.toSorted(User.compareByName).map((u) => u.name));
console.log(typeof users[0].fromEmail);    // not available on instances

try {
  new User("x", "superuser");
} catch (e) {
  console.log(e.message);
}

⌨️ Terminal

node static.js

🖥️ Output

3 [ 'asha', 'meera', 'ravi' ]
undefined
Invalid role: superuser

Math.max, Array.from, Object.keys and Date.now are all static methods of built-in classes.

Static initialisation blocks

A static { ... } block (ES2022) runs once when the class is defined, for setup that needs more than a single expression:

📄 static-block.js

class Config {
  static values;
  static {
    const env = process.env.TEST_ENV ?? "qa";
    Config.values = { env, baseURL: `https://${env}.example.com` };
  }
}
console.log(Config.values);

⌨️ Terminal

node static-block.js

🖥️ Output

{ env: 'qa', baseURL: 'https://qa.example.com' }

🎯 this Inside Classes

Inside a method, this is the instance the method was called on. If you pass a method somewhere as a callback, it loses that connection, and because classes are strict, this becomes undefined:

📄 this.js

class Logger {
  prefix = "[test]";
  log(message) {
    return `${this.prefix} ${message}`;
  }
  logArrow = (message) => `${this.prefix} ${message}`;   // arrow field keeps this
}

const logger = new Logger();
const messages = ["start", "end"];

try {
  messages.map(logger.log);
} catch (e) {
  console.log("method as callback:", e.message);
}
console.log(messages.map((m) => logger.log(m)));   // fix 1: arrow wrapper
console.log(messages.map(logger.log.bind(logger))); // fix 2: bind
console.log(messages.map(logger.logArrow));          // fix 3: arrow-function field

⌨️ Terminal

node this.js

🖥️ Output

method as callback: Cannot read properties of undefined (reading 'prefix')
[ '[test] start', '[test] end' ]
[ '[test] start', '[test] end' ]
[ '[test] start', '[test] end' ]

The this, call, apply and bind lesson explains these rules in full.


🧾 Class Expressions and toString

Like functions, classes can be created as expressions and passed around as values. Defining toString() controls how an instance looks when converted to a string:

📄 expression.js

const Shape = class {
  constructor(name) { this.name = name; }
  toString() { return `Shape(${this.name})`; }
};

const s = new Shape("square");
console.log(`${s}`, String(s));

function createModel(fields) {          // a class created at runtime
  return class {
    constructor(data) {
      for (const f of fields) this[f] = data[f] ?? null;
    }
  };
}
const Order = createModel(["id", "total"]);
console.log(new Order({ id: 7 }));

⌨️ Terminal

node expression.js

🖥️ Output

Shape(square) Shape(square)
{ id: 7, total: null }

⚖️ Classes vs Factory Functions

A factory function is a normal function that returns a new object (often using closures for private state). Both styles are common:

ClassFactory function
Create withnew User()createUser()
Shared methodsOn the prototype (memory efficient)Usually recreated per object
Private state#private fieldsClosures
instanceofWorksDoes not apply
InheritanceextendsComposition / spreading objects
this pitfallsYes, when passing methodsFew, if closures are used

Test frameworks lean towards classes for page objects and API clients, and towards factory functions for test-data builders. Pick one style per job and stay consistent.


🧪 Tester Scenario: A Page Object Class

In the Page Object Model, each page of the application is a class that knows its URL and elements and offers methods for user actions. Tests call those methods instead of repeating selectors. This simulation uses a fake page object so it runs in Node.js; with Playwright the methods would await page.goto(), page.fill() and so on.

📄 login-page.js

class FakePage {                           // stands in for Playwright's page
  actions = [];
  goto(url) { this.actions.push(`goto ${url}`); }
  fill(selector, value) { this.actions.push(`fill ${selector} = ${value}`); }
  click(selector) { this.actions.push(`click ${selector}`); }
}

class LoginPage {
  static URL = "/login";
  selectors = { email: "#email", password: "#password", submit: "button[type=submit]" };

  constructor(page, baseURL) {
    this.page = page;
    this.baseURL = baseURL;
  }

  open() {
    this.page.goto(this.baseURL + LoginPage.URL);
    return this;
  }

  login(email, password) {
    this.page.fill(this.selectors.email, email);
    this.page.fill(this.selectors.password, "*".repeat(password.length));   // never log real passwords
    this.page.click(this.selectors.submit);
    return this;
  }
}

const page = new FakePage();
new LoginPage(page, "https://qa.example.com").open().login("asha@sqatools.in", "Secret@123");
console.log(page.actions.join("\n"));

⌨️ Terminal

node login-page.js

🖥️ Output

goto https://qa.example.com/login
fill #email = asha@sqatools.in
fill #password = **********
click button[type=submit]
  • Selectors live in one place: when the UI changes, only the page class changes, not every test.
  • Methods describe user intent (login), so tests read like test cases.
  • The page object is passed in (dependency injection), which makes the class easy to test with a fake, as here.

📝 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. Write a class Rectangle with width and height, and methods area() and perimeter(). Print both for a 4 × 3 rectangle.

Show answer

📄 practice1.js

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
  area() { return this.width * this.height; }
  perimeter() { return 2 * (this.width + this.height); }
}
const r = new Rectangle(4, 3);
console.log(r.area(), r.perimeter());

🖥️ Output

12 14

Q2. Write a class Counter with a field value = 0 and chainable methods inc(), dec() and reset().

Show answer

📄 practice2.js

class Counter {
  value = 0;
  inc() { this.value++; return this; }
  dec() { this.value--; return this; }
  reset() { this.value = 0; return this; }
}
const c = new Counter().inc().inc().inc().dec();
console.log(c.value, c.reset().value);

🖥️ Output

2 0

Q3. Add a static method Temperature.fromFahrenheit(f) to a class that stores Celsius, and print the Celsius value for 98.6 °F rounded to one decimal.

Show answer

📄 practice3.js

class Temperature {
  constructor(celsius) { this.celsius = celsius; }
  static fromFahrenheit(f) { return new Temperature(((f - 32) * 5) / 9); }
}
console.log(Temperature.fromFahrenheit(98.6).celsius.toFixed(1));

🖥️ Output

37.0

Q4. Write a class BankAccount whose withdraw(amount) throws an error when the amount is more than the balance. Show both a successful and a failed withdrawal.

Show answer

📄 practice4.js

class BankAccount {
  constructor(owner, balance = 0) {
    this.owner = owner;
    this.balance = balance;
  }
  deposit(amount) { this.balance += amount; return this.balance; }
  withdraw(amount) {
    if (amount > this.balance) throw new Error(`Insufficient funds: balance ${this.balance}, requested ${amount}`);
    this.balance -= amount;
    return this.balance;
  }
}
const acc = new BankAccount("Asha", 500);
console.log(acc.withdraw(200));
try { acc.withdraw(1000); } catch (e) { console.log(e.message); }

🖥️ Output

300
Insufficient funds: balance 300, requested 1000

Q5. Count how many Ticket objects have been created using a static field, and give each ticket an ID like "TCK-1".

Show answer

📄 practice5.js

class Ticket {
  static created = 0;
  constructor(title) {
    Ticket.created++;
    this.id = `TCK-${Ticket.created}`;
    this.title = title;
  }
}
const t1 = new Ticket("Login fails");
const t2 = new Ticket("Cart total wrong");
console.log(t1.id, t2.id, Ticket.created);

🖥️ Output

TCK-1 TCK-2 2

Q6. This code throws “Cannot read properties of undefined”. Fix it so it prints [ "Hi Asha", "Hi Ravi" ].

class Greeter {
  greeting = "Hi";
  greet(name) { return `${this.greeting} ${name}`; }
}
const g = new Greeter();
console.log(["Asha", "Ravi"].map(g.greet));
Show answer

📄 practice6.js

class Greeter {
  greeting = "Hi";
  greet(name) { return `${this.greeting} ${name}`; }
}
const g = new Greeter();
console.log(["Asha", "Ravi"].map((name) => g.greet(name)));

🖥️ Output

[ 'Hi Asha', 'Hi Ravi' ]

Passing g.greet detaches the method from g. Wrap it in an arrow function, use g.greet.bind(g), or define greet as an arrow-function field.


🧠 MCQ Quiz: Classes

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 runs when you call new User("Asha")?
  2. What happens if you call a class without new?
  3. Where are class methods stored?
  4. How do you call a static method?
  5. What does a class field like items = [] give each instance?
  6. Which mode does code inside a class body run in?
  7. Why might list.map(obj.method) throw?
  8. What is the main purpose of a Page Object class?
  9. What is typeof class {}?
  10. What does returning this from methods allow?

💼 Interview Questions and Answers

Q1. What is the difference between a class and an object?

A class is a blueprint: it defines the properties and methods that its objects will have. An object (instance) is a concrete value created from that blueprint with new, with its own data. In JavaScript a class is itself a function object, and instances are linked to the class’s prototype.

Q2. What is the difference between static and instance methods?

Instance methods are called on an object (user.save()) and use its data through this. Static methods are called on the class (User.fromEmail()) and do not need an instance; they are used for factories, utilities, constants and counters. Inside a static method, this refers to the class.

Q3. Why are class fields useful, and how do they differ from properties set in the constructor?

Class fields declare the instance shape in one visible place and can have default values; they run before the constructor body for each instance. Properties set in the constructor can depend on constructor arguments. Both create own properties on the instance. Arrow-function fields also bind this permanently, which is handy for callbacks, at the cost of one function per instance.

Q4. How do classes help in test automation frameworks?

They organise code by responsibility: page objects (selectors and user actions per page), API clients (endpoints and authentication), and fixtures or helpers. Constructors receive dependencies such as Playwright’s page or request, methods expose intent-based actions, and static members hold shared constants. This removes duplication and localises changes when the UI or API changes.


❓ Frequently Asked Questions

🤔 Can a class have more than one constructor?

No. Use default parameters, an options object, or static factory methods (User.fromEmail, User.fromJSON) for different ways of creating instances.

🤔 Are classes hoisted?

Class declarations are hoisted but stay in the temporal dead zone, so using a class before its definition throws a ReferenceError.

🤔 Should every helper be a class?

No. Use a class when you need several instances with state and behaviour (pages, clients, models). Plain functions are better for stateless helpers.

🤔 How do I print a class instance nicely?

Define a toString() method for string conversion, or a toJSON() method to control JSON.stringify output.


🏁 Summary

  • A class is a blueprint; new ClassName() runs the constructor and returns an instance.
  • Methods are shared on the prototype; class fields declare per-instance properties with defaults.
  • Static members belong to the class: use them for factories, constants and counters.
  • Classes are strict, require new, and lose this when methods are passed as callbacks.
  • Page Object classes keep selectors and actions in one place and make tests readable.

Next, continue with Lesson 40: Inheritance.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Prototypes and Constructor Functions Explained

Every JavaScript object has a hidden link to another object, its prototype, and it can use that object’s properties and methods as if they were its own. This is how [1, 2].map works even though you never defined map, and it is what JavaScript classes are built on. In this lesson you will learn how prototypes and the prototype chain work, how to create objects with Object.create and constructor functions, why methods belong on the prototype, and how this knowledge explains classes, instanceof and some confusing errors.

📖 What You’ll Learn: what a prototype is, the prototype chain and property lookup, Object.getPrototypeOf and Object.create, own versus inherited properties, constructor functions and the new keyword, putting methods on Function.prototype, instanceof, built-in prototypes, why you should not modify them, and how classes are syntax over prototypes.


🧬 What Is a Prototype?

Definition: a prototype is an object that another object inherits properties from. Every object has an internal link (written [[Prototype]] in the specification) to its prototype, or to null at the end. When you read a property that the object does not have, JavaScript looks for it on the prototype.

📄 prototype.js

const user = { name: "Asha" };

console.log(user.name);                 // own property
console.log(user.toString());           // not defined on user... found on its prototype
console.log(Object.getPrototypeOf(user) === Object.prototype);
console.log(Object.hasOwn(user, "toString"), "toString" in user);

⌨️ Terminal

node prototype.js

🖥️ Output

Asha
[object Object]
true
false true

user has only one own property, name. toString comes from Object.prototype, the prototype of every plain object.


⛓️ The Prototype Chain

Definition: a prototype can have its own prototype, forming a prototype chain. Property lookup walks up the chain until it finds the property or reaches null, in which case the result is undefined.

📄 chain.js

const scores = [91, 78];

const p1 = Object.getPrototypeOf(scores);     // Array.prototype
const p2 = Object.getPrototypeOf(p1);         // Object.prototype
const p3 = Object.getPrototypeOf(p2);         // null: end of the chain

console.log(p1 === Array.prototype, p2 === Object.prototype, p3);
console.log(typeof scores.map, typeof scores.hasOwnProperty, scores.fly);
// scores -> Array.prototype (map, push, ...) -> Object.prototype (toString, hasOwnProperty, ...) -> null

⌨️ Terminal

node chain.js

🖥️ Output

true true null
function function undefined
ValueIts prototype chain
{}Object.prototype → null
[]Array.prototype → Object.prototype → null
function () {}Function.prototype → Object.prototype → null
"text" (when a method is called)String.prototype → Object.prototype → null

Writing a property always creates or changes an own property; it never changes the prototype. An own property with the same name shadows the inherited one:

📄 shadow.js

const base = { greet() { return "hello from base"; } };
const child = Object.create(base);

console.log(child.greet());
child.greet = () => "hello from child";   // own property shadows the inherited one
console.log(child.greet(), "|", base.greet());

⌨️ Terminal

node shadow.js

🖥️ Output

hello from base
hello from child | hello from base

🛠️ Object.create: Choose the Prototype

Object.create(proto) creates a new, empty object whose prototype is proto. It is the most direct way to set up inheritance between plain objects:

📄 object-create.js

const animal = {
  describe() {
    return `${this.name} says ${this.sound}`;
  },
};

const dog = Object.create(animal);
dog.name = "Rex";
dog.sound = "woof";

console.log(dog.describe());
console.log(Object.getPrototypeOf(dog) === animal);
console.log(Object.keys(dog));          // describe is inherited, not an own key

const bare = Object.create(null);       // no prototype at all
bare.key = "value";
console.log(typeof bare.toString);

⌨️ Terminal

node object-create.js

🖥️ Output

Rex says woof
true
[ 'name', 'sound' ]
undefined

Object.create(null) creates an object with no prototype, which is a clean dictionary with no inherited keys like toString or constructor.


🏗️ Constructor Functions and new

Before classes (ES2015), objects of the same “type” were created with constructor functions: regular functions called with new. By convention their names start with a capital letter.

📄 constructor.js

function TestCase(name, priority) {
  this.name = name;
  this.priority = priority;
  this.status = "pending";
}

const login = new TestCase("login", "P1");
const search = new TestCase("search", "P2");
console.log(login, search.name);

⌨️ Terminal

node constructor.js

🖥️ Output

TestCase { name: 'login', priority: 'P1', status: 'pending' } search

When you call a function with new, JavaScript:

  1. Creates a new empty object.
  2. Sets that object’s prototype to the function’s prototype property (TestCase.prototype).
  3. Runs the function with this pointing to the new object.
  4. Returns the new object (unless the function explicitly returns a different object).

⚠️ Watch out: Forgetting new calls the constructor as a plain function: this is undefined in strict mode (TypeError) or the global object in sloppy mode (properties leak onto the global object), and the call returns undefined. Classes prevent this by throwing if you forget new.

📄 forgot-new.js

"use strict";
function TestCase(name) {
  this.name = name;
}
try {
  const t = TestCase("login");   // forgot new
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}

⌨️ Terminal

node forgot-new.js

🖥️ Output

TypeError: Cannot set properties of undefined (setting 'name')

📎 Methods Belong on the Prototype

If a constructor assigns a method with this.run = function () {...}, every object gets its own copy of the function. Putting the method on Constructor.prototype stores it once, and every object finds it through the prototype chain:

📄 prototype-methods.js

function TestCase(name) {
  this.name = name;
  this.status = "pending";
}

TestCase.prototype.run = function (passed) {
  this.status = passed ? "passed" : "failed";
  return this;
};
TestCase.prototype.toString = function () {
  return `[${this.status.toUpperCase()}] ${this.name}`;
};

const a = new TestCase("login").run(true);
const b = new TestCase("cart").run(false);
console.log(String(a), "|", String(b));
console.log(a.run === b.run);                       // one shared function
console.log(Object.hasOwn(a, "run"), Object.getPrototypeOf(a) === TestCase.prototype);

⌨️ Terminal

node prototype-methods.js

🖥️ Output

[PASSED] login | [FAILED] cart
true
false true
TermWhat it is
Fn.prototypeA property of a constructor function: the object that instances created with new Fn() will inherit from
Object.getPrototypeOf(obj)The actual prototype of an object (the modern, standard way to read it)
obj.__proto__Legacy accessor for the same thing; avoid it in new code
Fn.prototype.constructorPoints back to Fn

🔎 instanceof and Checking Prototypes

obj instanceof Fn checks whether Fn.prototype appears anywhere in obj‘s prototype chain:

📄 instanceof.js

function Page(url) { this.url = url; }
const home = new Page("/");

console.log(home instanceof Page, home instanceof Object, home instanceof Array);
console.log(Page.prototype.isPrototypeOf(home));
console.log(home.constructor === Page, home.constructor.name);
console.log([] instanceof Array, Array.isArray([]));

⌨️ Terminal

node instanceof.js

🖥️ Output

true true false
true
true Page
true true

💡 Tip: For arrays prefer Array.isArray: instanceof Array can be false for arrays from another frame or realm (for example an iframe, or data passed from page.evaluate in some setups).


⚠️ Built-in Prototypes: Look, Do Not Touch

Because all arrays share Array.prototype, adding a method there makes it appear on every array in the program, including in libraries you did not write:

📄 monkey-patch.js

Array.prototype.last = function () {   // monkey patching: do not do this in real code
  return this[this.length - 1];
};
console.log([1, 2, 3].last());

const list = ["a", "b"];
for (const key in list) console.log("for...in sees:", key);   // the patch leaks into for...in

delete Array.prototype.last;
console.log(typeof [].last, [1, 2, 3].at(-1));                 // use the standard at() instead

⌨️ Terminal

node monkey-patch.js

🖥️ Output

3
for...in sees: 0
for...in sees: 1
for...in sees: last
undefined 3

⚠️ Watch out: Modifying built-in prototypes (“monkey patching”) can break other code and future JavaScript versions that add a method with the same name. Write a helper function instead, such as const last = (arr) => arr.at(-1).


🏛️ Classes Are Built on Prototypes

The class syntax (next lesson) is a clearer way to write constructor functions and prototype methods. Under the hood it creates exactly the same structure:

📄 class-prototype.js

class TestCase {
  constructor(name) {
    this.name = name;
  }
  run() {
    return `running ${this.name}`;
  }
}

const t = new TestCase("login");
console.log(typeof TestCase);                                   // classes are functions
console.log(Object.getPrototypeOf(t) === TestCase.prototype);   // same prototype link
console.log(Object.hasOwn(TestCase.prototype, "run"));          // methods live on the prototype
console.log(Object.keys(t), t.run());

⌨️ Terminal

node class-prototype.js

🖥️ Output

function
true
true
[ 'name' ] running login

🧪 Tester Scenario: Shared Behaviour for Page Objects

A shared base object can provide common helpers to many page objects through the prototype chain. This prototype-based version shows what classes and extends do for you later:

📄 page-prototype.js

const basePage = {
  open() {
    return `open ${this.baseURL}${this.path}`;
  },
  title() {
    return `${this.name} | SQA Tools`;
  },
};

function createPage(name, path) {
  const page = Object.create(basePage);
  page.name = name;
  page.path = path;
  page.baseURL = "https://qa.example.com";
  return page;
}

const login = createPage("Login", "/login");
const cart = createPage("Cart", "/cart");
login.submit = function (user) { return `${this.name}: submit ${user}`; };   // page-specific method

console.log(login.open(), "|", cart.open());
console.log(cart.title());
console.log(login.submit("asha"), "|", typeof cart.submit);
console.log(Object.getPrototypeOf(login) === Object.getPrototypeOf(cart));

⌨️ Terminal

node page-prototype.js

🖥️ Output

open https://qa.example.com/login | open https://qa.example.com/cart
Cart | SQA Tools
Login: submit asha | undefined
true

📝 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. Create const base = { kind: "base" } and const child = Object.create(base). Show that child.kind is “base”, that it is not an own property, and that setting child.kind does not change base.

Show answer

📄 practice1.js

const base = { kind: "base" };
const child = Object.create(base);
console.log(child.kind, Object.hasOwn(child, "kind"));
child.kind = "child";
console.log(child.kind, base.kind, Object.hasOwn(child, "kind"));

🖥️ Output

base false
child base true

Q2. Print the full prototype chain of the string object new String("qa") by walking Object.getPrototypeOf until null.

Show answer

📄 practice2.js

let obj = new String("qa");
const chain = [];
while ((obj = Object.getPrototypeOf(obj)) !== null) {
  chain.push(obj.constructor.name + ".prototype");
}
console.log(chain.join(" -> ") + " -> null");

🖥️ Output

String.prototype -> Object.prototype -> null

Q3. Write a constructor function Product(name, price) with a prototype method withTax(rate) that returns the price including tax. Create two products and show they share the method.

Show answer

📄 practice3.js

function Product(name, price) {
  this.name = name;
  this.price = price;
}
Product.prototype.withTax = function (rate) {
  return +(this.price * (1 + rate)).toFixed(2);
};
const pen = new Product("Pen", 10);
const lamp = new Product("Lamp", 899);
console.log(pen.withTax(0.18), lamp.withTax(0.18), pen.withTax === lamp.withTax);

🖥️ Output

11.8 1060.82 true

Q4. Check whether [], {} and new Date() are instances of Object, and whether Object.create(null) is.

Show answer

📄 practice4.js

console.log([] instanceof Object, {} instanceof Object, new Date() instanceof Object);
console.log(Object.create(null) instanceof Object);

🖥️ Output

true true true
false

An object created with Object.create(null) has no prototype chain, so Object.prototype is not in it.

Q5. Without modifying Array.prototype, write a helper sum(arr) and use it on [4, 5, 6].

Show answer

📄 practice5.js

const sum = (arr) => arr.reduce((total, n) => total + n, 0);
console.log(sum([4, 5, 6]), typeof [].sum);

🖥️ Output

15 undefined

Q6. Explain what new does by writing a function myNew(Fn, ...args) that creates an object the same way, and test it with a Point(x, y) constructor.

Show answer

📄 practice6.js

function myNew(Fn, ...args) {
  const obj = Object.create(Fn.prototype);   // 1 + 2: new object linked to the prototype
  const result = Fn.apply(obj, args);       // 3: run the constructor with this = obj
  return result !== null && typeof result === "object" ? result : obj;   // 4
}

function Point(x, y) { this.x = x; this.y = y; }
Point.prototype.sum = function () { return this.x + this.y; };

const p = myNew(Point, 2, 3);
console.log(p, p.sum(), p instanceof Point);

🖥️ Output

Point { x: 2, y: 3 } 5 true

🧠 MCQ Quiz: Prototypes

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 happens when you read a property an object does not have?
  2. What is at the end of every prototype chain?
  3. What does Object.create(proto) do?
  4. Where should shared methods of a constructor function be defined?
  5. What does obj instanceof Fn check?
  6. Which is the modern way to read an object’s prototype?
  7. What happens if you assign child.x = 1 when x is inherited?
  8. What is typeof class A {}?
  9. Why is adding methods to Array.prototype a bad idea?
  10. What does Object.create(null).toString give?

💼 Interview Questions and Answers

Q1. What is prototypal inheritance?

In JavaScript, objects inherit directly from other objects. Each object has a link to a prototype object; when a property is not found on the object, the engine looks it up along this prototype chain. Constructor functions and classes set up these links automatically (instances link to Constructor.prototype), and Object.create sets them explicitly.

Q2. What is the difference between __proto__ and prototype?

prototype is a property of functions (constructors and classes): it is the object that instances created with new will inherit from. __proto__ (better: Object.getPrototypeOf(obj)) is the actual prototype link of any object. For an instance, Object.getPrototypeOf(instance) === Constructor.prototype.

📄 proto-vs-prototype.js

function Car() {}
const c = new Car();
console.log(Object.getPrototypeOf(c) === Car.prototype, c.prototype, typeof Car.prototype);

⌨️ Terminal

node proto-vs-prototype.js

🖥️ Output

true undefined object

Q3. What does the new keyword do?

It creates a new object, links its prototype to the constructor’s prototype property, calls the constructor with this bound to the new object, and returns that object unless the constructor returns another object. Classes require new; calling a class without it throws a TypeError.

Q4. Are JavaScript classes “real” classes like in Java?

No. class is mostly syntax over constructor functions and prototypes: methods are stored on the prototype, and inheritance is a prototype chain. Classes do add real features, such as mandatory new, strict mode, super, and private #fields, but objects still inherit from objects at runtime, and you can inspect or change those links.


❓ Frequently Asked Questions

🤔 Do I need to learn prototypes if I use classes?

You can write classes without thinking about prototypes, but understanding them explains instanceof, method sharing, inheritance and errors such as “x is not a function” on an object you expected to have that method.

🤔 What is the difference between own and inherited properties?

Own properties are stored on the object itself and appear in Object.keys and JSON. Inherited properties come from the prototype chain and are found by property lookup and in.

🤔 Is Object.setPrototypeOf safe to use?

It works, but changing the prototype of an existing object is slow in most engines. Set the prototype when creating the object with Object.create or a class instead.

🤔 Why do primitives like strings have methods?

When you call a method on a primitive, JavaScript temporarily wraps it in an object (String, Number, Boolean) whose prototype provides the method.


🏁 Summary

  • Every object has a prototype link; missing properties are looked up along the prototype chain, ending at null.
  • Object.create(proto) creates an object with a chosen prototype; writing a property always creates an own property.
  • Constructor functions called with new create objects linked to Fn.prototype; shared methods belong there.
  • instanceof checks the prototype chain; read prototypes with Object.getPrototypeOf.
  • Classes are syntax over the same prototype mechanism; never modify built-in prototypes.

Next, continue with Lesson 39: Classes.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in