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

JavaScript Iterators and Generators: Symbol.iterator, yield and Async Generators

Why does for...of work on arrays, strings, Maps and Sets, but not on plain objects? The answer is the iteration protocol, and once you understand it you can make your own objects loopable. Generators, functions written with function* and yield, are the easy way to create iterators: they produce values one at a time, on demand. In this lesson you will learn both, then use them for lazy sequences, unique test data and paginated API results with async generators.

📖 What You’ll Learn: what iterables and iterators are, the iteration protocol and next(), Symbol.iterator, making a custom object iterable, generator functions with function* and yield, generator objects and their states, lazy and infinite sequences, yield*, passing values into generators, iterator helpers (map, filter, take, toArray), async generators and for await…of, and practical test-data and pagination examples.


🔁 Iterables and Iterators

Definitions: an iterable is any object that can be looped over with for...of, spread (...) or destructuring. An iterator is the object that actually produces the values, one at a time, through a next() method. Each call to next() returns { value, done }.

📄 protocol.js

const browsers = ["chromium", "firefox"];
const it = browsers[Symbol.iterator]();   // ask the array for an iterator

console.log(it.next());
console.log(it.next());
console.log(it.next());                   // finished

// for...of does exactly this behind the scenes
for (const b of browsers) console.log("for...of:", b);

⌨️ Terminal

node protocol.js

🖥️ Output

{ value: 'chromium', done: false }
{ value: 'firefox', done: false }
{ value: undefined, done: true }
for...of: chromium
for...of: firefox
Built-in iterablesWhat you get
ArrayEach element
StringEach character (by code point)
Map[key, value] pairs
SetEach value
arguments, NodeList, matchAll results, entries()/keys()/values()Their items
Plain objectNot iterable (use Object.entries)

📄 not-iterable.js

try {
  for (const x of { a: 1 }) console.log(x);
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}

⌨️ Terminal

node not-iterable.js

🖥️ Output

TypeError: {(intermediate value)} is not iterable

🔑 Making an Object Iterable with Symbol.iterator

To make your own object work with for...of, give it a method under the special key Symbol.iterator that returns an iterator:

📄 custom-iterable.js

const testRange = {
  from: 1,
  to: 4,
  [Symbol.iterator]() {
    let current = this.from;
    const last = this.to;
    return {
      next() {
        return current <= last
          ? { value: `test-${current++}`, done: false }
          : { value: undefined, done: true };
      },
    };
  },
};

for (const id of testRange) console.log(id);
console.log([...testRange]);
const [first, second] = testRange;
console.log(first, second);

⌨️ Terminal

node custom-iterable.js

🖥️ Output

test-1
test-2
test-3
test-4
[ 'test-1', 'test-2', 'test-3', 'test-4' ]
test-1 test-2

Writing next() by hand is verbose and easy to get wrong. Generators do the same job with far less code.


⚙️ Generator Functions: function* and yield

Definition: a generator function, written function*, can pause in the middle and resume later. Each yield value hands one value to the caller and pauses. Calling a generator function does not run its body; it returns a generator object, which is both an iterator and an iterable.

📄 generator.js

function* steps() {
  console.log("  (starting)");
  yield "open page";
  console.log("  (resumed after step 1)");
  yield "log in";
  yield "check dashboard";
  return "done";              // the return value is not part of for...of
}

const gen = steps();          // nothing printed yet: the body has not started
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());      // finished generators keep returning done: true

console.log([...steps()]);    // a fresh generator, collected into an array

⌨️ Terminal

node generator.js

🖥️ Output

  (starting)
{ value: 'open page', done: false }
  (resumed after step 1)
{ value: 'log in', done: false }
{ value: 'check dashboard', done: false }
{ value: 'done', done: true }
{ value: undefined, done: true }
  (starting)
  (resumed after step 1)
[ 'open page', 'log in', 'check dashboard' ]
  • The body runs only when next() is called, and only up to the next yield.
  • Local variables keep their values between pauses.
  • The return value appears once with done: true; for...of and spread ignore it.
  • A generator object can be iterated only once. Call the function again for a new sequence.

The custom iterable from the previous section, rewritten as a generator:

📄 generator-iterable.js

const testRange = {
  from: 1,
  to: 4,
  *[Symbol.iterator]() {          // generator method
    for (let i = this.from; i <= this.to; i++) yield `test-${i}`;
  },
};
console.log([...testRange]);

⌨️ Terminal

node generator-iterable.js

🖥️ Output

[ 'test-1', 'test-2', 'test-3', 'test-4' ]

♾️ Lazy and Infinite Sequences

Because generators produce values only when asked, they can describe sequences that would be too large, or even infinite, to build as an array. You take only what you need:

📄 infinite.js

function* idGenerator(prefix = "user") {
  let n = 1;
  while (true) {                     // infinite, but lazy
    yield `${prefix}-${String(n++).padStart(4, "0")}`;
  }
}

const ids = idGenerator();
console.log(ids.next().value, ids.next().value, ids.next().value);

function* take(iterable, count) {
  for (const item of iterable) {
    if (count-- <= 0) return;
    yield item;
  }
}
console.log([...take(idGenerator("order"), 3)]);

⌨️ Terminal

node infinite.js

🖥️ Output

user-0001 user-0002 user-0003
[ 'order-0001', 'order-0002', 'order-0003' ]

⚠️ Watch out: Never spread or Array.from an infinite generator directly ([...idGenerator()]): it never ends and the program hangs or runs out of memory. Always limit it with take, a break, or the iterator helpers below.


🧰 Iterator Helpers: map, filter, take, toArray

ES2025 added iterator helpers: array-like methods directly on iterators, which stay lazy. They work on generators and on built-in iterators such as map.values() (Node.js 22+):

📄 helpers.js

function* naturals() {
  let n = 1;
  while (true) yield n++;
}

const firstEvenSquares = naturals()
  .filter((n) => n % 2 === 0)
  .map((n) => n * n)
  .take(5)
  .toArray();
console.log(firstEvenSquares);

const scores = new Map([["asha", 91], ["ravi", 58], ["meera", 85]]);
console.log(scores.values().filter((s) => s >= 60).toArray());
console.log(naturals().drop(10).take(3).toArray());
console.log(naturals().some((n) => n > 100), naturals().find((n) => n % 7 === 0));

⌨️ Terminal

node helpers.js

🖥️ Output

[ 4, 16, 36, 64, 100 ]
[ 91, 85 ]
[ 11, 12, 13 ]
true 7

Only five numbers were squared even though naturals() is infinite, because each helper pulls one value at a time.


🔗 yield* and Passing Values In

yield* delegates to another iterable, yielding all of its values:

📄 delegate.js

function* smokeSuite() {
  yield "login";
  yield "search";
}
function* regressionSuite() {
  yield* smokeSuite();          // include every smoke test
  yield* ["refund", "export"];  // any iterable works
  yield "audit log";
}
console.log([...regressionSuite()]);

⌨️ Terminal

node delegate.js

🖥️ Output

[ 'login', 'search', 'refund', 'export', 'audit log' ]

next(value) sends a value into the generator: it becomes the result of the paused yield expression. This two-way communication is what early async libraries used before async/await existed:

📄 two-way.js

function* conversation() {
  const name = yield "What is your name?";
  const role = yield `Hi ${name}, what is your role?`;
  return `${name} is a ${role}`;
}

const chat = conversation();
console.log(chat.next().value);          // first next() starts the generator
console.log(chat.next("Asha").value);
console.log(chat.next("tester").value);

⌨️ Terminal

node two-way.js

🖥️ Output

What is your name?
Hi Asha, what is your role?
Asha is a tester

⏳ Async Generators and for await…of

Definition: an async generator (async function*) can await inside its body and yields values asynchronously. You consume it with for await...of. This is ideal for data that arrives in pieces, such as paginated API results or lines of a large file.

📄 async-generator.js

// Simulated API: 7 orders, 3 per page
const ALL = Array.from({ length: 7 }, (_, i) => ({ id: 100 + i }));
const fakeFetchPage = (page) =>
  new Promise((resolve) => setTimeout(() => {
    const items = ALL.slice((page - 1) * 3, page * 3);
    resolve({ items, hasMore: page * 3 < ALL.length });
  }, 5));

async function* allOrders() {
  let page = 1;
  while (true) {
    const { items, hasMore } = await fakeFetchPage(page);
    console.log(`  fetched page ${page} (${items.length} items)`);
    yield* items;
    if (!hasMore) return;
    page++;
  }
}

async function main() {
  const ids = [];
  for await (const order of allOrders()) {
    ids.push(order.id);
    if (ids.length === 5) break;      // stop early: page 3 is never fetched
  }
  console.log(ids);
}
main();

⌨️ Terminal

node async-generator.js

🖥️ Output

  fetched page 1 (3 items)
  fetched page 2 (3 items)
[ 100, 101, 102, 103, 104 ]

The caller loops over orders as if they were one list, while the generator fetches pages only when needed. Breaking out after five items means the third page is never requested. Promises and async/await are explained fully in Module 10.


🧪 Tester Scenario: A Test-Data Factory

Generators make test-data factories that never run out and never repeat. This one produces unique users, cycles through roles, and can be limited with iterator helpers:

📄 factory.js

function* cycle(values) {
  while (true) yield* values;
}

function* userFactory(runId) {
  const roles = cycle(["tester", "admin", "viewer"]);
  let n = 1;
  while (true) {
    yield {
      username: `${runId}_user${n}`,
      email: `qa+${runId}-${n}@sqatools.in`,
      role: roles.next().value,
    };
    n++;
  }
}

const users = userFactory("run42");
const firstThree = users.take(3).toArray();
console.table(firstThree);

const admins = userFactory("run43").filter((u) => u.role === "admin").take(2).toArray();
console.log(admins.map((u) => u.username));

⌨️ Terminal

node factory.js

🖥️ Output

┌─────────┬───────────────┬──────────────────────────┬──────────┐
│ (index) │ username      │ email                    │ role     │
├─────────┼───────────────┼──────────────────────────┼──────────┤
│ 0       │ 'run42_user1' │ 'qa+run42-1@sqatools.in' │ 'tester' │
│ 1       │ 'run42_user2' │ 'qa+run42-2@sqatools.in' │ 'admin'  │
│ 2       │ 'run42_user3' │ 'qa+run42-3@sqatools.in' │ 'viewer' │
└─────────┴───────────────┴──────────────────────────┴──────────┘
[ 'run43_user2', 'run43_user5' ]
  • cycle repeats a list forever, here giving a predictable rotation of roles.
  • Every user is unique within a run because the counter only goes up, and the run ID separates different runs.
  • Nothing is created until it is needed, so the factory costs nothing until a test asks for a user.

📝 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. Use an array’s iterator directly: call next() on ["a", "b"][Symbol.iterator]() three times and print each result.

Show answer

📄 practice1.js

const it = ["a", "b"][Symbol.iterator]();
console.log(it.next(), it.next(), it.next());

🖥️ Output

{ value: 'a', done: false } { value: 'b', done: false } { value: undefined, done: true }

Q2. Write a generator countdown(n) that yields n, n-1, … 1 and then "Liftoff". Print all values with spread.

Show answer

📄 practice2.js

function* countdown(n) {
  for (let i = n; i >= 1; i--) yield i;
  yield "Liftoff";
}
console.log([...countdown(5)]);

🖥️ Output

[ 5, 4, 3, 2, 1, 'Liftoff' ]

Q3. Write an infinite generator of Fibonacci numbers and print the first 10 using take and toArray.

Show answer

📄 practice3.js

function* fibonacci() {
  let [a, b] = [0, 1];
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}
console.log(fibonacci().take(10).toArray());

🖥️ Output

[
  0, 1,  1,  2,  3,
  5, 8, 13, 21, 34
]

Q4. Make a playlist object with a songs array that is iterable and yields "1. Song name" strings.

Show answer

📄 practice4.js

const playlist = {
  songs: ["Intro", "Main Theme", "Outro"],
  *[Symbol.iterator]() {
    for (const [i, s] of this.songs.entries()) yield `${i + 1}. ${s}`;
  },
};
for (const line of playlist) console.log(line);

🖥️ Output

1. Intro
2. Main Theme
3. Outro

Q5. Write a generator chunks(array, size) that yields the array in groups of size. Test with [1..7] and size 3.

Show answer

📄 practice5.js

function* chunks(array, size) {
  for (let i = 0; i < array.length; i += size) {
    yield array.slice(i, i + size);
  }
}
console.log([...chunks([1, 2, 3, 4, 5, 6, 7], 3)]);

🖥️ Output

[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7 ] ]

Chunking is useful for sending test data to an API in batches.

Q6. Use iterator helpers to get the first 3 multiples of 7 that are greater than 50, from an infinite generator of natural numbers.

Show answer

📄 practice6.js

function* naturals() {
  let n = 1;
  while (true) yield n++;
}
console.log(naturals().filter((n) => n > 50 && n % 7 === 0).take(3).toArray());

🖥️ Output

[ 56, 63, 70 ]

🧠 MCQ Quiz: Iterators and Generators

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 an iterator’s next() method return?
  2. Which of these is NOT iterable with for…of?
  3. What makes an object iterable?
  4. What happens when you call a generator function?
  5. What does yield do?
  6. What does [...gen()] do with a generator’s return value?
  7. What is the danger of [...infiniteGenerator()]?
  8. What does yield* other do?
  9. How do you consume an async generator?
  10. What does naturals().take(3).toArray() return if naturals yields 1, 2, 3, …?

💼 Interview Questions and Answers

Q1. What is the difference between an iterable and an iterator?

An iterable is an object with a [Symbol.iterator]() method; calling that method returns an iterator. An iterator is an object with a next() method that returns { value, done }. for...of, spread and destructuring ask the iterable for a fresh iterator and call next() until done is true. Generator objects are both: their [Symbol.iterator]() returns themselves.

Q2. What are generators useful for in real projects?

  • Lazy sequences: generating data on demand instead of building large arrays.
  • Infinite streams: unique IDs, test data, retry delays.
  • Custom iteration for data structures (trees, paginated results).
  • Async generators for streaming APIs, pagination and reading large files line by line.
  • Historically, coroutine-style async code (libraries such as co and redux-saga).

Q3. Predict the output.

📄 predict.js

function* g() {
  const x = yield 1;
  console.log("received", x);
  yield x * 2;
}
const it = g();
console.log(it.next(5).value);
console.log(it.next(10).value);
console.log(it.next().done);

⌨️ Terminal

node predict.js

🖥️ Output

1
received 10
20
true

The first next(5) starts the generator; the 5 is discarded because no yield is waiting yet, and it yields 1. next(10) resumes with x = 10, logs “received 10” and yields 20. The last call finishes the generator, so done is true.

Q4. How would you iterate over all items of a paginated API in a test?

Write an async generator that requests page after page, yields the items of each page, and stops when the API reports no more pages. The test then uses for await (const item of allItems()), can stop early with break, and never needs to know about pages. Add a page limit as a safety net so a buggy API cannot cause an endless loop.


❓ Frequently Asked Questions

🤔 Are generators slow?

They have a small overhead per value compared with a plain loop. For test data and I/O-bound work this is irrelevant; the benefit is clear, lazy code.

🤔 Can arrow functions be generators?

No. There is no arrow syntax for generators; use function* or a generator method *name() {}.

🤔 What is the difference between return and yield in a generator?

yield produces a value and pauses; the generator can continue. return ends the generator; its value appears once with done: true and is ignored by for...of.

🤔 Do iterator helpers work in browsers?

They are part of ES2025 and supported in current Chrome, Edge, Firefox and Safari, and in Node.js 22 and later.


🏁 Summary

  • Iterables have [Symbol.iterator](); iterators have next() returning { value, done }; for...of uses both.
  • Plain objects are not iterable; make your own objects iterable with a Symbol.iterator method.
  • Generators (function*) pause at each yield, which makes custom iterators and lazy or infinite sequences easy.
  • Iterator helpers (map, filter, take, toArray) work lazily on any iterator.
  • Async generators with for await...of stream data such as paginated API results.

Next, continue with Lesson 38: Prototypes. This completes Module 7. Module 8 covers object-oriented JavaScript: prototypes, classes and inheritance.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript JSON: parse, stringify, Files and Deep Copy with structuredClone

JSON (JavaScript Object Notation) is the language that APIs, configuration files and test data speak. Every REST response you check, every package.json and every data-driven test file is JSON. In this lesson you will learn the JSON rules, convert between JSON text and JavaScript objects with JSON.parse and JSON.stringify, control the output with replacers, revivers and indentation, read and write JSON files in Node.js, handle the errors you will meet, and make deep copies safely.

📖 What You’ll Learn: JSON syntax and how it differs from JavaScript objects, JSON.stringify with indentation, replacer and toJSON, what stringify drops or changes (undefined, functions, dates, NaN, BigInt), JSON.parse with a reviver, parse errors, circular references, reading and writing JSON files with fs, deep copying with JSON versus structuredClone, and comparing API responses.


📄 What Is JSON?

Definition: JSON is a text format for structured data. It looks like JavaScript object and array literals, but it is just a string with stricter rules. Almost every programming language can read and write it.

📄 user.json

{
  "id": 7,
  "name": "Asha Rao",
  "active": true,
  "roles": ["tester", "admin"],
  "manager": null,
  "address": { "city": "Pune", "pin": "411001" }
}
JSON ruleJavaScript object literal
Keys must be in double quotesQuotes are optional
Strings must use double quotesSingle, double or back-ticks
No trailing commasTrailing commas allowed
No commentsComments allowed
Values: string, number, boolean, null, object, arrayAlso undefined, functions, Date, Map, NaN, BigInt…

JSON has exactly six value types. Everything else must be converted to one of them before it can be stored as JSON.


➡️ JSON.stringify: Object to JSON Text

JSON.stringify(value, replacer, space) converts a JavaScript value into a JSON string. Use the third argument to indent the output for humans:

📄 stringify.js

const order = { id: 501, items: ["pen", "book"], paid: true, coupon: null };

const compact = JSON.stringify(order);
console.log(compact, typeof compact);

console.log(JSON.stringify(order, null, 2));   // 2-space indentation
console.log(JSON.stringify([1, "two", false]));
console.log(JSON.stringify("text"), JSON.stringify(42));

⌨️ Terminal

node stringify.js

🖥️ Output

{"id":501,"items":["pen","book"],"paid":true,"coupon":null} string
{
  "id": 501,
  "items": [
    "pen",
    "book"
  ],
  "paid": true,
  "coupon": null
}
[1,"two",false]
"text" 42

What stringify changes or drops

📄 stringify-rules.js

const data = {
  name: "Asha",
  nickname: undefined,           // dropped
  greet() { return "hi"; },      // dropped
  joined: new Date(Date.UTC(2026, 10, 23)),   // becomes an ISO string
  score: NaN,                    // becomes null
  limit: Infinity,               // becomes null
  tags: new Set(["a", "b"]),     // becomes {}
  list: [undefined, () => 1],    // inside arrays: become null
};
console.log(JSON.stringify(data));

try {
  JSON.stringify({ id: 10n });
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}

⌨️ Terminal

node stringify-rules.js

🖥️ Output

{"name":"Asha","joined":"2026-11-23T00:00:00.000Z","score":null,"limit":null,"tags":{},"list":[null,null]}
TypeError: Do not know how to serialize a BigInt

⚠️ Watch out: These silent conversions cause real test bugs: a field set to undefined disappears from the request body, a Set is sent as {}, and a date becomes a string that must be parsed again on the other side. Convert values deliberately before sending them ([...set], date.toISOString(), String(bigint)).


🎛️ Replacer and toJSON: Control the Output

The second argument of stringify can be an array of keys to keep, or a replacer function called for every key and value. Return undefined to drop a property.

📄 replacer.js

const user = { id: 7, name: "Asha", password: "Secret@1", token: "abc", tags: new Set(["qa"]) };

console.log(JSON.stringify(user, ["id", "name"]));          // allow-list

const safe = JSON.stringify(user, (key, value) => {
  if (["password", "token"].includes(key)) return "***";      // mask secrets
  if (value instanceof Set) return [...value];                 // convert Sets
  return value;
});
console.log(safe);

⌨️ Terminal

node replacer.js

🖥️ Output

{"id":7,"name":"Asha"}
{"id":7,"name":"Asha","password":"***","token":"***","tags":["qa"]}

An object can also define a toJSON() method; stringify uses its return value instead of the object. This is how Date turns itself into an ISO string.

📄 tojson.js

class Money {
  constructor(amount, currency) { this.amount = amount; this.currency = currency; }
  toJSON() { return `${this.amount.toFixed(2)} ${this.currency}`; }
}
console.log(JSON.stringify({ total: new Money(1299.5, "INR") }));

⌨️ Terminal

node tojson.js

🖥️ Output

{"total":"1299.50 INR"}

⬅️ JSON.parse: JSON Text to Object

JSON.parse(text, reviver) turns a JSON string into JavaScript values. This is what await response.json() does for you in Playwright and fetch.

📄 parse.js

const text = '{"id":501,"items":["pen","book"],"paid":true,"placedAt":"2026-11-23T10:30:00.000Z"}';
const order = JSON.parse(text);

console.log(order.items[1], order.paid, typeof order);
console.log(typeof order.placedAt);   // dates stay strings

const withDates = JSON.parse(text, (key, value) =>
  typeof value === "string" && /^\d{4}-\d{2}-\d{2}T/.test(value) ? new Date(value) : value
);
console.log(withDates.placedAt instanceof Date, withDates.placedAt.getUTCHours());

⌨️ Terminal

node parse.js

🖥️ Output

book true object
string
true 10

The reviver function sees every key and value after parsing and can replace them, here turning ISO date strings back into Date objects.

Parse errors

Invalid JSON throws a SyntaxError. Common causes are single quotes, trailing commas, unquoted keys, and trying to parse something that is not JSON at all, such as an HTML error page:

📄 parse-errors.js

const samples = [
  "{'id': 1}",
  '{"id": 1,}',
  "{id: 1}",
  "<!DOCTYPE html><html>502 Bad Gateway</html>",
  "",
];
for (const s of samples) {
  try {
    JSON.parse(s);
  } catch (e) {
    console.log(`${e.name}: ${e.message}`);
  }
}

⌨️ Terminal

node parse-errors.js

🖥️ Output

SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)
SyntaxError: Expected double-quoted property name in JSON at position 9 (line 1 column 10)
SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
SyntaxError: Unexpected end of JSON input

💡 Tip: When an API test fails with “Unexpected token <“, the server returned HTML (an error page or a login redirect) instead of JSON. Log the status code and the raw text before parsing; in Playwright, check response.status() and await response.text().


🔁 Circular References

An object that refers to itself (directly or through other objects) cannot be turned into JSON, because the output would be infinite:

📄 circular.js

const parent = { name: "suite" };
const child = { name: "test", parent };
parent.children = [child];      // parent -> child -> parent ...

try {
  JSON.stringify(parent);
} catch (e) {
  console.log(e.message.split("\n")[0]);
}

const seen = new WeakSet();
console.log(JSON.stringify(parent, (key, value) => {
  if (typeof value === "object" && value !== null) {
    if (seen.has(value)) return "[Circular]";
    seen.add(value);
  }
  return value;
}));

⌨️ Terminal

node circular.js

🖥️ Output

Converting circular structure to JSON
{"name":"suite","children":[{"name":"test","parent":"[Circular]"}]}

Logging libraries and test reporters use a replacer like this one so that a circular object can still be printed.


📁 Reading and Writing JSON Files in Node.js

Test data and configuration often live in .json files. In Node.js, read the file as text with the fs module and parse it; write by stringifying with indentation:

📄 json-files.js

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

const users = [
  { username: "standard_user", password: "pass1", expected: "success" },
  { username: "locked_user", password: "pass2", expected: "locked" },
];

fs.writeFileSync("users.json", JSON.stringify(users, null, 2) + "\n");
console.log("written:", fs.readFileSync("users.json", "utf8").split("\n").length - 1, "lines");

const loaded = JSON.parse(fs.readFileSync("users.json", "utf8"));
for (const u of loaded) {
  console.log(`${u.username.padEnd(14)} -> expect ${u.expected}`);
}

⌨️ Terminal

node json-files.js

🖥️ Output

written: 12 lines
standard_user  -> expect success
locked_user    -> expect locked
  • Always pass "utf8" so you get a string instead of a Buffer.
  • In CommonJS you can also require("./users.json"); in ES modules use import users from "./users.json" with { type: "json" } (import attributes). Both cache the file, so use fs when the file can change during a run.
  • The Module 11 lesson on the file system covers async file reading and paths in depth.

🧬 Deep Copy: JSON Round-Trip vs structuredClone

JSON.parse(JSON.stringify(obj)) was the classic way to deep-copy an object. It works only for plain JSON-safe data. structuredClone(obj) (available everywhere since 2022) is the modern, safer choice:

📄 deep-copy.js

const original = {
  name: "Asha",
  joined: new Date(Date.UTC(2026, 0, 15)),
  tags: new Set(["qa"]),
  meta: { score: NaN, note: undefined },
};

const viaJson = JSON.parse(JSON.stringify(original));
const viaClone = structuredClone(original);

console.log("JSON  :", viaJson);
console.log("clone :", viaClone);
console.log(viaClone.joined instanceof Date, viaClone.tags instanceof Set, viaClone.meta !== original.meta);

⌨️ Terminal

node deep-copy.js

🖥️ Output

JSON  : {
  name: 'Asha',
  joined: '2026-01-15T00:00:00.000Z',
  tags: {},
  meta: { score: null }
}
clone : {
  name: 'Asha',
  joined: 2026-01-15T00:00:00.000Z,
  tags: Set(1) { 'qa' },
  meta: { score: NaN, note: undefined }
}
true true true
JSON round-tripstructuredClone
DatesBecome stringsStay Date objects
Map / SetBecome {}Copied correctly
undefined, NaN, InfinityLost or become nullKept
Circular referencesThrowCopied correctly
Functions, class methodsDroppedThrow DataCloneError (functions) / prototype lost

🧪 Tester Scenario: Compare an API Response with a Fixture

A typical API test loads an expected response from a JSON fixture, ignores fields that change on every call (IDs, timestamps), and compares the rest:

📄 fixture.js

const { isDeepStrictEqual } = require("node:util");

const fixtureText = `{
  "name": "Asha",
  "role": "tester",
  "permissions": ["read", "write"],
  "id": 0,
  "createdAt": ""
}`;
const responseText = '{"id":9123,"name":"Asha","role":"tester","permissions":["read","write"],"createdAt":"2026-11-23T10:31:07Z"}';

const IGNORE = ["id", "createdAt"];
const strip = (obj) => JSON.parse(JSON.stringify(obj, (k, v) => (IGNORE.includes(k) ? undefined : v)));

const expected = strip(JSON.parse(fixtureText));
const actual = strip(JSON.parse(responseText));

console.log("matches fixture:", isDeepStrictEqual(actual, expected));
console.log("dynamic fields present:", Number.isInteger(JSON.parse(responseText).id), !Number.isNaN(Date.parse(JSON.parse(responseText).createdAt)));

⌨️ Terminal

node fixture.js

🖥️ Output

matches fixture: true
dynamic fields present: true true
  • The replacer returns undefined for ignored keys, which removes them before comparing.
  • Dynamic fields are not ignored completely: the test still checks their type and format.
  • In Playwright, expect(body).toMatchObject(expected) and expect.any(Number) express the same idea.

📝 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. Convert { name: "Lamp", price: 899, tags: ["home"] } to a JSON string with 4-space indentation and print it.

Show answer

📄 practice1.js

const product = { name: "Lamp", price: 899, tags: ["home"] };
console.log(JSON.stringify(product, null, 4));

🖥️ Output

{
    "name": "Lamp",
    "price": 899,
    "tags": [
        "home"
    ]
}

Q2. Parse '{"total": 1299.5, "items": 3}' and print the average price per item rounded to 2 decimals.

Show answer

📄 practice2.js

const data = JSON.parse('{"total": 1299.5, "items": 3}');
console.log((data.total / data.items).toFixed(2));

🖥️ Output

433.17

Q3. Write safeParse(text) that returns { ok: true, data } on success and { ok: false, error } on a parse error.

Show answer

📄 practice3.js

function safeParse(text) {
  try {
    return { ok: true, data: JSON.parse(text) };
  } catch (e) {
    return { ok: false, error: e.message };
  }
}
console.log(safeParse('{"a":1}'));
console.log(safeParse("{a:1}"));

🖥️ Output

{ ok: true, data: { a: 1 } }
{
  ok: false,
  error: "Expected property name or '}' in JSON at position 1 (line 1 column 2)"
}

Q4. Stringify a user object but mask the email so only the first letter and domain show, for example a***@sqatools.in.

Show answer

📄 practice4.js

const user = { name: "Asha", email: "asha@sqatools.in" };
const json = JSON.stringify(user, (key, value) =>
  key === "email" ? value[0] + "***" + value.slice(value.indexOf("@")) : value
);
console.log(json);

🖥️ Output

{"name":"Asha","email":"a***@sqatools.in"}

Q5. Predict the output of JSON.stringify({ a: undefined, b: null, c: [undefined], d: NaN }), then run it.

Show answer

📄 practice5.js

console.log(JSON.stringify({ a: undefined, b: null, c: [undefined], d: NaN }));

🖥️ Output

{"b":null,"c":[null],"d":null}

a is dropped, null is kept, undefined inside an array becomes null, and NaN becomes null.

Q6. Write a JSON file config.json with { "env": "qa", "retries": 2 }, read it back, increase retries by 1 and save it again. Print the final file content.

Show answer

📄 practice6.js

const fs = require("node:fs");
fs.writeFileSync("config.json", JSON.stringify({ env: "qa", retries: 2 }, null, 2));
const config = JSON.parse(fs.readFileSync("config.json", "utf8"));
config.retries += 1;
fs.writeFileSync("config.json", JSON.stringify(config, null, 2));
console.log(fs.readFileSync("config.json", "utf8"));

🖥️ Output

{
  "env": "qa",
  "retries": 3
}

🧠 MCQ Quiz: JSON and Deep Copy

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 is valid JSON?
  2. What does JSON.stringify({ a: 1 }) return?
  3. What happens to a property whose value is undefined in JSON.stringify?
  4. What does a Date become after JSON.stringify and JSON.parse?
  5. What error does JSON.parse("{a:1}") throw?
  6. What does the third argument of JSON.stringify control?
  7. Why does JSON.stringify(obj) throw “Converting circular structure to JSON”?
  8. Which method creates a deep copy that keeps Dates, Maps and Sets?
  9. An API test fails with “Unexpected token ‘<‘” while parsing JSON. What is the likely cause?
  10. What does JSON.stringify(10n) do?

💼 Interview Questions and Answers

Q1. What is the difference between JSON and a JavaScript object?

JSON is a language-independent text format; a JavaScript object is an in-memory value. JSON requires double-quoted keys and strings, has no comments or trailing commas, and supports only strings, numbers, booleans, null, objects and arrays. JSON.stringify serialises an object to JSON text and JSON.parse deserialises JSON text into objects.

Q2. What gets lost when you deep-copy with JSON.parse(JSON.stringify(obj))?

undefined properties and functions are dropped; NaN and Infinity become null; Date objects become strings; Map, Set and class instances become plain objects; BigInt throws; circular references throw. structuredClone handles most of these correctly.

Q3. How would you hide sensitive fields when logging a request body?

📄 redact.js

const SENSITIVE = new Set(["password", "token", "authorization", "cardNumber"]);
const redact = (obj) => JSON.stringify(obj, (k, v) => (SENSITIVE.has(k) ? "[REDACTED]" : v), 2);
console.log(redact({ user: "asha", password: "x", headers: { authorization: "Bearer abc" } }));

⌨️ Terminal

node redact.js

🖥️ Output

{
  "user": "asha",
  "password": "[REDACTED]",
  "headers": {
    "authorization": "[REDACTED]"
  }
}

A replacer function runs for every key at every depth, so nested secrets are redacted too.

Q4. How do you compare an API response against expected JSON when some fields are dynamic?

Remove or normalise the dynamic fields (IDs, timestamps, request IDs) before comparing, for example with a replacer or by destructuring them out, and assert their format separately (integer, ISO date, UUID). Compare the rest with deep equality (toEqual, toMatchObject, isDeepStrictEqual). For larger contracts, validate against a JSON Schema with a library such as Ajv.


❓ Frequently Asked Questions

🤔 How do I pretty-print JSON in JavaScript?

Use JSON.stringify(obj, null, 2). The third argument is the number of spaces (or a string such as "\t") used for indentation.

🤔 How do I read a JSON file in Node.js?

Use JSON.parse(fs.readFileSync("file.json", "utf8")), or the async fs.promises.readFile. In ES modules you can also use an import with { type: "json" }.

🤔 Why are my dates strings after JSON.parse?

JSON has no date type, so dates are stored as strings. Convert them with new Date(value) or a reviver function.

🤔 Can JSON have comments?

No. If you need comments in configuration, use a format that allows them (JSONC, YAML, or a JavaScript/TypeScript config file such as playwright.config.ts).


🏁 Summary

  • JSON is text with strict rules: double quotes, no trailing commas, no comments, six value types.
  • JSON.stringify(value, replacer, space) creates JSON; it drops undefined and functions and converts dates to strings.
  • JSON.parse(text, reviver) reads JSON and throws SyntaxError on invalid input, such as HTML error pages.
  • Read and write JSON files with fs plus parse/stringify; use replacers to redact secrets and handle circular data.
  • Use structuredClone for deep copies; the JSON round-trip loses dates, Maps, Sets and special values.

Next, continue with Lesson 36: Map, Set, WeakMap, WeakSet.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Map, Set, WeakMap and WeakSet Explained with Examples

Objects and arrays cover most needs, but two jobs come up again and again where they are clumsy: storing values by a key that is not a simple string, and keeping a collection of unique values. JavaScript has dedicated collections for these, Map and Set, plus memory-friendly versions, WeakMap and WeakSet. In this lesson you will learn all four, when to choose them over plain objects and arrays, and the new set operations (union, intersection, difference) that make comparing expected and actual data in tests a one-liner.

📖 What You’ll Learn: creating and using Map, Map versus plain objects, iterating a Map, counting and grouping with Map, creating and using Set, removing duplicates, set operations (union, intersection, difference, symmetricDifference, isSubsetOf), WeakMap and WeakSet and garbage collection, converting between collections, and comparing expected and actual values in tests.


🗺️ Map: Key–Value Pairs with Any Key Type

Definition: a Map is a collection of key–value pairs where the keys can be any value: strings, numbers, booleans, objects or functions. It remembers insertion order and has a size.

📄 map.js

const statusText = new Map([
  [200, "OK"],
  [404, "Not Found"],
]);

statusText.set(500, "Server Error");      // add or update
console.log(statusText.get(404));         // read
console.log(statusText.get(418));         // missing key: undefined
console.log(statusText.has(200), statusText.size);

statusText.delete(404);
console.log([...statusText.keys()], [...statusText.values()]);

console.log(new Map().set("a", 1).set("b", 2));   // set returns the map, so calls chain

⌨️ Terminal

node map.js

🖥️ Output

Not Found
undefined
true 3
[ 200, 500 ] [ 'OK', 'Server Error' ]
Map(2) { 'a' => 1, 'b' => 2 }
Map method / propertyDoes
new Map(entries)Create, optionally from [key, value] pairs
set(key, value)Add or update; returns the map
get(key)Read; undefined if missing
has(key) / delete(key)Check / remove (both return booleans)
sizeNumber of entries
clear()Remove everything
keys(), values(), entries(), forEach()Iterate in insertion order

Objects as keys

A plain object converts every key to a string, so two different objects collide on the key "[object Object]". A Map keeps them apart:

📄 object-keys.js

const pageA = { url: "/login" };
const pageB = { url: "/cart" };

const asObject = {};
asObject[pageA] = "visited A";
asObject[pageB] = "visited B";
console.log(asObject);                       // one key: "[object Object]"

const asMap = new Map();
asMap.set(pageA, "visited A").set(pageB, "visited B");
console.log(asMap.get(pageA), "|", asMap.get(pageB), "|", asMap.size);

⌨️ Terminal

node object-keys.js

🖥️ Output

{ '[object Object]': 'visited B' }
visited A | visited B | 2

⚖️ Map vs Plain Object

MapPlain object
Key typesAny valueStrings and symbols only
OrderInsertion orderInteger-like keys first, then insertion order
Sizemap.sizeObject.keys(obj).length
IterationDirectly iterable (for...of)Needs Object.entries
Accidental keysNoneInherited keys like toString, __proto__
JSONNot supported directly (convert first)Native
Best forDynamic keys, frequent add/remove, counting, cachesFixed records, config, JSON data

📄 map-vs-object.js

const counts = {};
for (const word of ["constructor", "toString", "qa"]) {
  counts[word] = (counts[word] || 0) + 1;
}
console.log(counts);      // inherited methods break the counting!

const safeCounts = new Map();
for (const word of ["constructor", "toString", "qa"]) {
  safeCounts.set(word, (safeCounts.get(word) ?? 0) + 1);
}
console.log(safeCounts);

⌨️ Terminal

node map-vs-object.js

🖥️ Output

{
  constructor: 'function Object() { [native code] }1',
  toString: 'function toString() { [native code] }1',
  qa: 1
}
Map(3) { 'constructor' => 1, 'toString' => 1, 'qa' => 1 }

Counting with a plain object went wrong because counts.constructor and counts.toString already exist (inherited functions). A Map has no such hidden keys.


🔁 Iterating, Counting and Converting Maps

📄 iterate-map.js

const durations = new Map([
  ["login", 820],
  ["search", 1430],
  ["cart", 610],
]);

for (const [test, ms] of durations) {
  console.log(`${test.padEnd(7)} ${ms} ms`);
}

const slowest = [...durations].reduce((a, b) => (b[1] > a[1] ? b : a));
console.log("slowest:", slowest);

const asObject = Object.fromEntries(durations);          // Map -> object (e.g. for JSON)
const backToMap = new Map(Object.entries(asObject));     // object -> Map
console.log(JSON.stringify(asObject), backToMap.get("cart"));

const sortedByTime = new Map([...durations].sort((a, b) => a[1] - b[1]));
console.log([...sortedByTime.keys()]);

⌨️ Terminal

node iterate-map.js

🖥️ Output

login   820 ms
search  1430 ms
cart    610 ms
slowest: [ 'search', 1430 ]
{"login":820,"search":1430,"cart":610} 610
[ 'cart', 'login', 'search' ]

Map.groupBy(items, fn) (ES2024) groups an array into a Map, the Map version of Object.groupBy:

📄 map-groupby.js

const results = [{ t: "a", ok: true }, { t: "b", ok: false }, { t: "c", ok: true }];
const grouped = Map.groupBy(results, (r) => r.ok);    // boolean keys are fine in a Map
console.log(grouped.get(true).map((r) => r.t), grouped.get(false).map((r) => r.t));

⌨️ Terminal

node map-groupby.js

🖥️ Output

[ 'a', 'c' ] [ 'b' ]

🎯 Set: A Collection of Unique Values

Definition: a Set stores unique values of any type. Adding a value that is already there does nothing. Like Map, it keeps insertion order and has size.

📄 set.js

const tags = new Set(["smoke", "login", "smoke"]);
console.log(tags, tags.size);

tags.add("regression").add("login");    // "login" is already there
console.log(tags.has("regression"), tags.has("api"));
tags.delete("smoke");
console.log([...tags]);

const ids = [3, 1, 3, 2, 1, 2];
console.log([...new Set(ids)]);          // remove duplicates
console.log(new Set("mississippi").size); // unique letters

⌨️ Terminal

node set.js

🖥️ Output

Set(2) { 'smoke', 'login' } 2
true false
[ 'login', 'regression' ]
[ 3, 1, 2 ]
4

⚠️ Watch out: Sets compare objects by reference, like ===. Two separate objects with the same contents are both kept: new Set([{ id: 1 }, { id: 1 }]).size is 2. To deduplicate objects, use a Map keyed by an ID.

📄 set-objects.js

const users = [{ id: 1, n: "Asha" }, { id: 2, n: "Ravi" }, { id: 1, n: "Asha" }];
console.log(new Set(users).size);
const unique = [...new Map(users.map((u) => [u.id, u])).values()];
console.log(unique);

⌨️ Terminal

node set-objects.js

🖥️ Output

3
[ { id: 1, n: 'Asha' }, { id: 2, n: 'Ravi' } ]

🔀 Set Operations: Union, Intersection, Difference

ES2025 added set-algebra methods to Set. They return new Sets (or booleans) and leave the originals unchanged. They are available in Node.js 22+ and current browsers:

📄 set-ops.js

const expected = new Set(["Home", "Tutorials", "Practice", "Blog", "Contact"]);
const actual = new Set(["Home", "Tutorials", "Blog", "Jobs"]);

console.log("in both:", [...expected.intersection(actual)]);
console.log("missing:", [...expected.difference(actual)]);
console.log("unexpected:", [...actual.difference(expected)]);
console.log("all:", [...expected.union(actual)]);
console.log("in exactly one:", [...expected.symmetricDifference(actual)]);
console.log(new Set(["Home"]).isSubsetOf(expected), expected.isSupersetOf(actual), expected.isDisjointFrom(new Set(["Login"])));

⌨️ Terminal

node set-ops.js

🖥️ Output

in both: [ 'Home', 'Tutorials', 'Blog' ]
missing: [ 'Practice', 'Contact' ]
unexpected: [ 'Jobs' ]
all: [ 'Home', 'Tutorials', 'Practice', 'Blog', 'Contact', 'Jobs' ]
in exactly one: [ 'Practice', 'Contact', 'Jobs' ]
true false true
MethodReturns
a.union(b)Everything in a or b
a.intersection(b)Only items in both
a.difference(b)Items in a but not in b
a.symmetricDifference(b)Items in exactly one of them
a.isSubsetOf(b) / isSupersetOf / isDisjointFromBooleans

💡 Tip: In older environments, write the same operations with filter: [...a].filter((x) => b.has(x)) for intersection and [...a].filter((x) => !b.has(x)) for difference. set.has is fast, which is why converting an array to a Set first speeds up repeated lookups.


🪶 WeakMap and WeakSet

Definition: a WeakMap is like a Map whose keys must be objects and are held weakly: if nothing else in the program references a key object, it can be garbage-collected, and its entry disappears automatically. A WeakSet is the same idea for a set of objects.

  • Keys (WeakMap) and values (WeakSet) must be objects (or non-registered symbols), not primitives.
  • They are not iterable and have no size, because entries can vanish at any time.
  • Available methods: WeakMap get, set, has, delete; WeakSet add, has, delete.

📄 weak.js

// Attach extra data to objects you do not own, without changing them or leaking memory
const renderCount = new WeakMap();

function render(component) {
  renderCount.set(component, (renderCount.get(component) ?? 0) + 1);
}

const header = { name: "Header" };
render(header);
render(header);
console.log(renderCount.get(header), Object.keys(header));   // the object itself is unchanged

// Track which objects were already processed
const processed = new WeakSet();
function processOnce(obj) {
  if (processed.has(obj)) return "skipped";
  processed.add(obj);
  return "processed";
}
const req = { id: 1 };
console.log(processOnce(req), processOnce(req));

try {
  new WeakMap().set("text", 1);
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}

⌨️ Terminal

node weak.js

🖥️ Output

2 [ 'name' ]
processed skipped
TypeError: Invalid value used as weak map key

Typical uses: caching results per object (memoisation), storing private data for objects, and tracking visited objects in recursive algorithms (the circular-JSON replacer in the JSON lesson uses a WeakSet).


🧪 Tester Scenario: Check Navigation Links and Count Errors

Two common checks: comparing the links on a page with the expected list, and counting error types in a log. Sets make the first precise, and a Map makes the second safe:

📄 links.js

const expectedLinks = new Set(["/", "/tutorials/", "/practice/", "/blogs/", "/contact/"]);
const foundOnPage = ["/", "/tutorials/", "/blogs/", "/blogs/", "/jobs/"];   // as read from the page

const found = new Set(foundOnPage);
const missing = [...expectedLinks.difference(found)];
const unexpected = [...found.difference(expectedLinks)];
const duplicates = foundOnPage.filter((link, i) => foundOnPage.indexOf(link) !== i);

console.log({ missing, unexpected, duplicates });
console.log(missing.length === 0 && unexpected.length === 0 ? "PASS" : "FAIL");

const log = ["TimeoutError", "AssertionError", "TimeoutError", "NetworkError", "TimeoutError"];
const errorCounts = new Map();
for (const e of log) errorCounts.set(e, (errorCounts.get(e) ?? 0) + 1);
const topError = [...errorCounts].sort((a, b) => b[1] - a[1])[0];
console.log(errorCounts, "most common:", topError);

⌨️ Terminal

node links.js

🖥️ Output

{
  missing: [ '/practice/', '/contact/' ],
  unexpected: [ '/jobs/' ],
  duplicates: [ '/blogs/' ]
}
FAIL
Map(3) {
  'TimeoutError' => 3,
  'AssertionError' => 1,
  'NetworkError' => 1
} most common: [ 'TimeoutError', 3 ]

Reporting which links are missing and which are unexpected gives a far better failure message than “arrays are not equal”.


📝 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 Map of country codes to names (IN, US, JP), then print the name for US, the size, and whether FR exists.

Show answer

📄 practice1.js

const countries = new Map([["IN", "India"], ["US", "United States"], ["JP", "Japan"]]);
console.log(countries.get("US"), countries.size, countries.has("FR"));

🖥️ Output

United States 3 false

Q2. Count how many times each word appears in "to be or not to be" using a Map.

Show answer

📄 practice2.js

const counts = new Map();
for (const word of "to be or not to be".split(" ")) {
  counts.set(word, (counts.get(word) ?? 0) + 1);
}
console.log(counts);

🖥️ Output

Map(4) { 'to' => 2, 'be' => 2, 'or' => 1, 'not' => 1 }

Q3. Remove duplicates from ["qa", "dev", "qa", "ops", "dev"] and print how many unique values there are.

Show answer

📄 practice3.js

const teams = ["qa", "dev", "qa", "ops", "dev"];
const unique = [...new Set(teams)];
console.log(unique, unique.length);

🖥️ Output

[ 'qa', 'dev', 'ops' ] 3

Q4. Find the common elements of [1, 2, 3, 4] and [3, 4, 5], and the elements only in the first array, using Set methods.

Show answer

📄 practice4.js

const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5]);
console.log([...a.intersection(b)], [...a.difference(b)]);

🖥️ Output

[ 3, 4 ] [ 1, 2 ]

Q5. Convert the Map new Map([["env", "qa"], ["retries", 2]]) to a JSON string.

Show answer

📄 practice5.js

const settings = new Map([["env", "qa"], ["retries", 2]]);
console.log(JSON.stringify(settings));                       // a Map becomes {}
console.log(JSON.stringify(Object.fromEntries(settings)));  // convert first

🖥️ Output

{}
{"env":"qa","retries":2}

Q6. Check that every required permission ["read", "write"] is included in a user’s permissions ["read", "write", "delete"].

Show answer

📄 practice6.js

const required = new Set(["read", "write"]);
const granted = new Set(["read", "write", "delete"]);
console.log(required.isSubsetOf(granted));

🖥️ Output

true

🧠 MCQ Quiz: Map, Set, WeakMap, WeakSet

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 key types can a Map have?
  2. How do you get the number of entries in a Map?
  3. What does new Set([1, 1, 2]).size return?
  4. What does map.get("missing") return?
  5. How many items are in new Set([{ id: 1 }, { id: 1 }])?
  6. What does a.difference(b) return for Sets?
  7. Why can’t you iterate a WeakMap?
  8. What happens with new WeakSet().add("text")?
  9. What does JSON.stringify(new Map([["a", 1]])) return?
  10. When is a Map a better choice than a plain object?

💼 Interview Questions and Answers

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

A Map accepts keys of any type, keeps insertion order, has a size property, is directly iterable and has no inherited keys that can collide with your data. Objects only use string and symbol keys, inherit properties from Object.prototype, and need Object.keys/entries to iterate, but they are native to JSON and ideal for fixed records. Use a Map for dynamic key–value collections and an object for structured records.

Q2. How do you remove duplicates from an array?

For primitives, [...new Set(arr)]. For objects, deduplicate by a key: [...new Map(arr.map((o) => [o.id, o])).values()] (keeps the last occurrence of each id), or a filter with a Set of seen ids to keep the first.

📄 dedupe-first.js

const rows = [{ id: 1, v: "a" }, { id: 2, v: "b" }, { id: 1, v: "c" }];
const seen = new Set();
const firstOnly = rows.filter((r) => !seen.has(r.id) && seen.add(r.id));
console.log(firstOnly);

⌨️ Terminal

node dedupe-first.js

🖥️ Output

[ { id: 1, v: 'a' }, { id: 2, v: 'b' } ]

Q3. What are WeakMap and WeakSet used for?

They associate data with objects without preventing those objects from being garbage-collected: per-object caches, private data for class instances, and “already visited” tracking in graph or tree traversal. Because entries can disappear, they cannot be iterated and have no size, and keys must be objects.

Q4. How would you compare the expected and actual list of items on a page?

Convert both lists to Sets and compute expected.difference(actual) (missing items) and actual.difference(expected) (unexpected items); report both in the failure message. If order or duplicates matter, also compare the arrays themselves or check for duplicates separately, because Sets ignore both.


❓ Frequently Asked Questions

🤔 Is a Map faster than an object?

For frequent additions and deletions and large dynamic collections, Maps are usually faster. For small fixed records the difference does not matter.

🤔 Can I use Set methods like union in Node.js?

Yes. union, intersection, difference, symmetricDifference, isSubsetOf, isSupersetOf and isDisjointFrom are part of ES2025 and work in Node.js 22 and later.

🤔 How do I convert a Set to an array?

Use spread [...set] or Array.from(set). Then all array methods such as map and sort are available.

🤔 Does a Set keep the order of items?

Yes. Sets and Maps iterate in insertion order.


🏁 Summary

  • A Map stores key–value pairs with keys of any type, in insertion order, with get/set/has/delete and size.
  • Use Maps for dynamic keys, counting and caches; use objects for fixed records and JSON.
  • A Set stores unique values; [...new Set(arr)] removes duplicate primitives.
  • ES2025 Set methods (union, intersection, difference…) make expected-vs-actual comparisons simple.
  • WeakMap and WeakSet hold object keys weakly, so entries vanish with their objects; they are not iterable.

Next, continue with Lesson 37: Iterators and Generators.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Object Methods: keys, entries, assign, freeze and More

The global Object has a toolbox of static methods for working with any object: listing its keys, turning it into an array and back, merging objects, freezing configuration so nobody can change it, and controlling individual properties. In this lesson you will learn the methods you will actually use, how to combine them to transform objects (filter, rename, map values), and how to protect shared test configuration from accidental changes.

📖 What You’ll Learn: Object.keys, values and entries, Object.fromEntries, transforming objects with entries, Object.assign versus spread, Object.freeze, seal and preventExtensions and their differences, deep freeze, Object.hasOwn, property descriptors and Object.defineProperty, getOwnPropertyNames, Object.groupBy, and pick and omit helpers for test data.


🔑 Object.keys, Object.values and Object.entries

These three methods turn an object into an array, so all the array methods become available:

📄 keys-values.js

const stock = { pen: 120, notebook: 0, lamp: 7, mug: 0 };

console.log(Object.keys(stock));      // ["pen", "notebook", ...]
console.log(Object.values(stock));    // [120, 0, 7, 0]
console.log(Object.entries(stock));   // [["pen", 120], ...]

const outOfStock = Object.entries(stock).filter(([, qty]) => qty === 0).map(([item]) => item);
console.log("out of stock:", outOfStock);
console.log("total units:", Object.values(stock).reduce((a, b) => a + b, 0));
console.log("product count:", Object.keys(stock).length);

⌨️ Terminal

node keys-values.js

🖥️ Output

[ 'pen', 'notebook', 'lamp', 'mug' ]
[ 120, 0, 7, 0 ]
[ [ 'pen', 120 ], [ 'notebook', 0 ], [ 'lamp', 7 ], [ 'mug', 0 ] ]
out of stock: [ 'notebook', 'mug' ]
total units: 127
product count: 4
  • They return only the object’s own enumerable string keys (no inherited properties, no symbols).
  • Order: integer-like keys in ascending order first, then other string keys in insertion order.
  • ([, qty]) => skips the first element of each entry with destructuring.

🔄 Object.fromEntries: Arrays Back to Objects

Object.fromEntries(entries) is the reverse of Object.entries. It builds an object from [key, value] pairs, from any iterable of pairs, including a Map or URLSearchParams.

📄 from-entries.js

console.log(Object.fromEntries([["env", "qa"], ["workers", 4]]));

const params = new URLSearchParams("q=laptop&page=2&sort=price");
console.log(Object.fromEntries(params));

const headers = new Map([["content-type", "application/json"], ["x-request-id", "abc"]]);
console.log(Object.fromEntries(headers));

⌨️ Terminal

node from-entries.js

🖥️ Output

{ env: 'qa', workers: 4 }
{ q: 'laptop', page: '2', sort: 'price' }
{ 'content-type': 'application/json', 'x-request-id': 'abc' }

The transform pattern: entries → array method → fromEntries

Because objects have no map or filter, convert to entries, transform, and convert back:

📄 transform.js

const prices = { pen: 10, notebook: 45, lamp: 899 };

const withTax = Object.fromEntries(Object.entries(prices).map(([k, v]) => [k, +(v * 1.18).toFixed(2)]));
const expensive = Object.fromEntries(Object.entries(prices).filter(([, v]) => v > 40));
const upperKeys = Object.fromEntries(Object.entries(prices).map(([k, v]) => [k.toUpperCase(), v]));

console.log(withTax);
console.log(expensive);
console.log(upperKeys);

⌨️ Terminal

node transform.js

🖥️ Output

{ pen: 11.8, notebook: 53.1, lamp: 1060.82 }
{ notebook: 45, lamp: 899 }
{ PEN: 10, NOTEBOOK: 45, LAMP: 899 }

🧩 Object.assign vs Spread

Object.assign(target, ...sources) copies properties from the sources into the target and returns the target. It mutates the target. Spread creates a new object instead.

📄 assign.js

const defaults = { browser: "chromium", retries: 0 };
const overrides = { retries: 2 };

const merged1 = Object.assign({}, defaults, overrides);   // safe: empty target
const merged2 = { ...defaults, ...overrides };             // same result
console.log(merged1, merged2);

Object.assign(defaults, overrides);                        // mutates defaults!
console.log(defaults);

⌨️ Terminal

node assign.js

🖥️ Output

{ browser: 'chromium', retries: 2 } { browser: 'chromium', retries: 2 }
{ browser: 'chromium', retries: 2 }

💡 Tip: Prefer spread for merging into a new object. Use Object.assign(this, options) when you deliberately want to copy options onto an existing object, for example in a class constructor.


🧊 freeze, seal and preventExtensions

Three levels of protection for an object:

MethodAdd propertiesDelete propertiesChange values
Object.preventExtensions(o)NoYesYes
Object.seal(o)NoNoYes
Object.freeze(o)NoNoNo

📄 freeze.js

"use strict";

const sealed = Object.seal({ env: "qa" });
sealed.env = "staging";                  // allowed
try { sealed.newKey = 1; } catch (e) { console.log("seal:", e.message); }

const frozen = Object.freeze({ env: "qa" });
try { frozen.env = "prod"; } catch (e) { console.log("freeze:", e.message); }
console.log(sealed.env, frozen.env, Object.isFrozen(frozen), Object.isSealed(sealed));

⌨️ Terminal

node freeze.js

🖥️ Output

seal: Cannot add property newKey, object is not extensible
freeze: Cannot assign to read only property 'env' of object '#<Object>'
staging qa true true

In strict mode (ES modules, classes, "use strict") a forbidden change throws a TypeError. In sloppy mode it is silently ignored, which hides bugs.

freeze is shallow

📄 deep-freeze.js

const config = Object.freeze({ env: "qa", urls: { api: "https://api.qa" } });
config.urls.api = "https://evil.example";   // nested object is NOT frozen
console.log(config.urls.api);

function deepFreeze(obj) {
  for (const value of Object.values(obj)) {
    if (value && typeof value === "object") deepFreeze(value);
  }
  return Object.freeze(obj);
}
const safe = deepFreeze({ env: "qa", urls: { api: "https://api.qa" } });
safe.urls.api = "https://evil.example";
console.log(safe.urls.api, Object.isFrozen(safe.urls));

⌨️ Terminal

node deep-freeze.js

🖥️ Output

https://evil.example
https://api.qa true

💡 Tip: Deep-freeze shared test configuration and base test data. Any test that tries to change them then fails immediately in strict code, instead of silently affecting other tests.


✅ Object.hasOwn and Property Checks

📄 hasown.js

const response = { id: 1, error: undefined };

console.log(Object.hasOwn(response, "error"));      // exists, even though undefined
console.log(Object.hasOwn(response, "toString"));   // inherited: false
console.log("toString" in response);                 // in sees inherited

const dict = Object.create(null);                    // object without a prototype
dict.key = "value";
console.log(Object.hasOwn(dict, "key"), typeof dict.hasOwnProperty);

⌨️ Terminal

node hasown.js

🖥️ Output

true
false
true
true undefined

Object.hasOwn (ES2022) replaces the older obj.hasOwnProperty(key), which fails on objects created with Object.create(null) because they have no hasOwnProperty method.


🔬 Property Descriptors and Object.defineProperty

Definition: every property has a hidden descriptor with flags: writable (can the value change?), enumerable (does it show up in Object.keys and loops?) and configurable (can it be deleted or redefined?). Normal assignments create properties with all three set to true.

📄 descriptors.js

const user = { name: "Asha" };
console.log(Object.getOwnPropertyDescriptor(user, "name"));

Object.defineProperty(user, "id", { value: 7, writable: false, enumerable: false });
Object.defineProperty(user, "password", { value: "secret", enumerable: false });

user.id = 99;                               // ignored: not writable
console.log(user.id);
console.log(Object.keys(user));             // hidden properties are not listed
console.log(JSON.stringify(user));          // and not serialised
console.log(Object.getOwnPropertyNames(user));   // but they exist

⌨️ Terminal

node descriptors.js

🖥️ Output

{ value: 'Asha', writable: true, enumerable: true, configurable: true }
7
[ 'name' ]
{"name":"Asha"}
[ 'name', 'id', 'password' ]

You will rarely call defineProperty yourself, but it explains why some properties do not show up in logs or JSON, and how frameworks create read-only and computed properties. Getters and setters are covered in Module 8.


🗂️ Object.groupBy

Object.groupBy(items, callback) (ES2024) groups the items of an array (or any iterable) into an object whose keys are the callback’s return values:

📄 groupby.js

const tests = [
  { name: "login", status: "passed", browser: "chromium" },
  { name: "search", status: "failed", browser: "firefox" },
  { name: "cart", status: "passed", browser: "firefox" },
];

const byStatus = Object.groupBy(tests, (t) => t.status);
console.log(Object.fromEntries(Object.entries(byStatus).map(([k, v]) => [k, v.map((t) => t.name)])));

const byBrowser = Object.groupBy(tests, ({ browser }) => browser);
console.log(Object.keys(byBrowser), byBrowser.firefox.length);

⌨️ Terminal

node groupby.js

🖥️ Output

{ passed: [ 'login', 'cart' ], failed: [ 'search' ] }
[ 'chromium', 'firefox' ] 2

🧪 Tester Scenario: pick, omit and Compare Configurations

Small helpers built from the methods in this lesson cover many everyday test tasks: choosing fields to assert, removing secrets before logging, and showing what differs between two environments.

📄 pick-omit.js

const pick = (obj, keys) => Object.fromEntries(Object.entries(obj).filter(([k]) => keys.includes(k)));
const omit = (obj, keys) => Object.fromEntries(Object.entries(obj).filter(([k]) => !keys.includes(k)));

const user = { id: 7, name: "Asha", email: "asha@sqatools.in", password: "Secret@1", token: "eyJhbGci..." };
console.log("assert on:", pick(user, ["id", "email"]));
console.log("safe to log:", omit(user, ["password", "token"]));

function diffConfig(a, b) {
  const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
  return [...keys]
    .filter((k) => !Object.is(a[k], b[k]))
    .map((k) => `${k}: ${JSON.stringify(a[k])} -> ${JSON.stringify(b[k])}`);
}

const qa = { baseURL: "https://qa.example.com", retries: 1, workers: 4, video: "off" };
const prod = { baseURL: "https://www.example.com", retries: 2, workers: 4, trace: "on" };
console.log(diffConfig(qa, prod));

⌨️ Terminal

node pick-omit.js

🖥️ Output

assert on: { id: 7, email: 'asha@sqatools.in' }
safe to log: { id: 7, name: 'Asha', email: 'asha@sqatools.in' }
[
  'baseURL: "https://qa.example.com" -> "https://www.example.com"',
  'retries: 1 -> 2',
  'video: "off" -> undefined',
  'trace: undefined -> "on"'
]

📝 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 how many keys { a: 1, b: 2, c: 3, d: 4 } has and the sum of its values.

Show answer

📄 practice1.js

const obj = { a: 1, b: 2, c: 3, d: 4 };
console.log(Object.keys(obj).length, Object.values(obj).reduce((s, v) => s + v, 0));

🖥️ Output

4 10

Q2. Swap keys and values: turn { chromium: "Blink", firefox: "Gecko" } into { Blink: "chromium", Gecko: "firefox" }.

Show answer

📄 practice2.js

const engines = { chromium: "Blink", firefox: "Gecko" };
console.log(Object.fromEntries(Object.entries(engines).map(([k, v]) => [v, k])));

🖥️ Output

{ Blink: 'chromium', Gecko: 'firefox' }

Q3. Remove every property whose value is null or undefined from { a: 1, b: null, c: "x", d: undefined, e: 0 }.

Show answer

📄 practice3.js

const obj = { a: 1, b: null, c: "x", d: undefined, e: 0 };
console.log(Object.fromEntries(Object.entries(obj).filter(([, v]) => v != null)));

🖥️ Output

{ a: 1, c: 'x', e: 0 }

Q4. Freeze a config object and show (in strict mode) that changing it throws.

Show answer

📄 practice4.js

"use strict";
const config = Object.freeze({ timeout: 30000 });
try {
  config.timeout = 1;
} catch (e) {
  console.log(e.constructor.name, "-", e.message);
}
console.log(config.timeout);

🖥️ Output

TypeError - Cannot assign to read only property 'timeout' of object '#<Object>'
30000

Q5. Convert the query string "?env=qa&debug=true&workers=2" into an object, then convert workers to a number and debug to a boolean.

Show answer

📄 practice5.js

const raw = Object.fromEntries(new URLSearchParams("?env=qa&debug=true&workers=2"));
const parsed = { ...raw, debug: raw.debug === "true", workers: Number(raw.workers) };
console.log(raw, parsed);

🖥️ Output

{ env: 'qa', debug: 'true', workers: '2' } { env: 'qa', debug: true, workers: 2 }

Q6. Write renameKeys(obj, map) that renames keys using a mapping such as { fname: "firstName" }, keeping other keys as they are.

Show answer

📄 practice6.js

const renameKeys = (obj, map) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [map[k] ?? k, v]));
console.log(renameKeys({ fname: "Asha", lname: "Rao", age: 29 }, { fname: "firstName", lname: "lastName" }));

🖥️ Output

{ firstName: 'Asha', lastName: 'Rao', age: 29 }

🧠 MCQ Quiz: Object Methods

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 Object.keys({ x: 1, y: 2 }) return?
  2. Which method builds an object from [key, value] pairs?
  3. What does Object.assign(target, source) return?
  4. After Object.seal(o), what is still allowed?
  5. Does Object.freeze freeze nested objects?
  6. In sloppy mode, what happens when you assign to a frozen property?
  7. Why prefer Object.hasOwn over obj.hasOwnProperty?
  8. A property defined with enumerable: false…
  9. What does Object.groupBy([1, 2, 3, 4], (n) => n % 2 ? "odd" : "even") produce?
  10. How do you “map” over an object’s values?

💼 Interview Questions and Answers

Q1. What is the difference between Object.freeze and Object.seal?

Both prevent adding and deleting properties. seal still allows changing the values of existing properties; freeze also makes every existing property read-only. Both are shallow: nested objects remain mutable unless frozen too. Violations throw in strict mode and are silently ignored otherwise.

Q2. How do you deep clone and deep freeze an object?

Deep clone: structuredClone(obj) (handles nested objects, arrays, dates, Maps and Sets; not functions or class prototypes). Deep freeze: a recursive function that calls Object.freeze on every nested object, as shown in this lesson. Libraries such as Immer provide immutable updates at scale.

Q3. How do you iterate over an object and transform it?

Use Object.entries(obj) to get [key, value] pairs, transform them with array methods (map, filter), and rebuild with Object.fromEntries. For example, removing null values: Object.fromEntries(Object.entries(obj).filter(([, v]) => v != null)).

Q4. Why might a property be missing from console output or JSON even though you can read it?

It may be non-enumerable (defined with enumerable: false), a getter on the prototype (class getters are not own properties), or a symbol key. Object.keys, for...in and JSON.stringify skip them. Object.getOwnPropertyNames, Object.getOwnPropertySymbols and Reflect.ownKeys list them.

📄 getter.js

class Point {
  constructor(x) { this.x = x; }
  get double() { return this.x * 2; }
}
const p = new Point(4);
console.log(p.double, Object.keys(p), JSON.stringify(p));

⌨️ Terminal

node getter.js

🖥️ Output

8 [ 'x' ] {"x":4}

❓ Frequently Asked Questions

🤔 What is the difference between Object.keys and for…in?

Object.keys returns only the object’s own enumerable keys as an array. for...in also visits inherited enumerable keys.

🤔 How do I merge two objects?

Use spread: { ...a, ...b } (b wins on conflicts). For nested objects, merge each level you care about, or use a deep-merge utility.

🤔 How do I make an object immutable?

Use Object.freeze for one level, and a recursive deep freeze for nested data. In strict mode, attempts to change it throw errors.

🤔 Is Object.groupBy available everywhere?

It is part of ES2024 and works in Node.js 21+ and current browsers. For older environments, use reduce.


🏁 Summary

  • Object.keys, values and entries turn objects into arrays; Object.fromEntries turns pairs back into objects.
  • Transform objects with the entries → map/filter → fromEntries pattern.
  • Object.assign mutates its target; spread creates a new object.
  • preventExtensions < seal < freeze in strictness, and all are shallow.
  • Descriptors control whether properties are writable, enumerable and configurable; Object.hasOwn checks own properties safely.

Next, continue with Lesson 35: JSON and Deep Copy.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Array Sorting and Searching: sort, toSorted, Comparators and Binary Search

Sorting looks simple until [10, 9, 1].sort() returns [1, 10, 9]. JavaScript’s default sort compares items as text, which surprises everyone the first time. Testers sort and search all the time: checking that a table is sorted by price, finding the newest order, picking the slowest test. In this lesson you will learn how sorting really works, how to write comparator functions for numbers, strings, dates and objects, how to sort by several keys, and how to search arrays efficiently.

📖 What You’ll Learn: how the default sort works and why it breaks numbers, comparator functions, ascending and descending order, sorting strings with localeCompare and Intl.Collator, sorting dates, sorting objects by one or more keys, sort stability, sort versus toSorted, checking whether an array is sorted, linear search methods, and binary search on sorted data.


🔤 How the Default sort() Works

Definition: arr.sort() sorts the array in place (it mutates the array) and returns the same array. Without a compare function, it converts every item to a string and sorts by UTF-16 code units, which is alphabetical order for simple text.

📄 default-sort.js

console.log(["webkit", "chromium", "firefox"].sort());   // strings: fine
console.log([10, 9, 1, 100, 25].sort());                // numbers as text: wrong!
console.log(["b", "B", "a", "A"].sort());               // uppercase before lowercase
console.log([true, false, null, undefined, 3].sort());  // undefined always goes last

⌨️ Terminal

node default-sort.js

🖥️ Output

[ 'chromium', 'firefox', 'webkit' ]
[ 1, 10, 100, 25, 9 ]
[ 'A', 'B', 'a', 'b' ]
[ 3, false, null, true, undefined ]

Compared as text, "100" comes before "25" because "1" comes before "2". For anything other than simple strings, always pass a compare function.


⚖️ Comparator Functions

Definition: a comparator is a function (a, b) => number that tells sort the order of two items:

Comparator returnsMeaning
A negative numbera comes before b
A positive numberb comes before a
0Keep their current order

📄 numbers.js

const scores = [10, 9, 1, 100, 25];

console.log(scores.toSorted((a, b) => a - b));   // ascending
console.log(scores.toSorted((a, b) => b - a));   // descending
console.log(scores);                              // toSorted kept the original

⌨️ Terminal

node numbers.js

🖥️ Output

[ 1, 9, 10, 25, 100 ]
[ 100, 25, 10, 9, 1 ]
[ 10, 9, 1, 100, 25 ]

a - b is negative when a is smaller, so smaller numbers come first. Swap to b - a for descending order.

⚠️ Watch out: A comparator must return a number. Returning a boolean such as (a, b) => a > b is a common bug: false becomes 0 and true becomes 1, never negative, so the result depends on the engine and is often wrong.

📄 boolean-bug.js

const values = [3, 1, 2, 5, 4];
console.log(values.toSorted((a, b) => a > b));         // boolean comparator: not reliable
console.log(values.toSorted((a, b) => a - b));         // correct

⌨️ Terminal

node boolean-bug.js

🖥️ Output

[ 3, 1, 2, 5, 4 ]
[ 1, 2, 3, 4, 5 ]

🔠 Sorting Strings Correctly

The default order puts "Zebra" before "apple" and handles accents poorly. Use localeCompare, or an Intl.Collator for speed when sorting many items:

📄 strings.js

const names = ["ravi", "Asha", "émile", "Bala", "zoya", "Ölaf"];

console.log(names.toSorted());
console.log(names.toSorted((a, b) => a.localeCompare(b)));
console.log(names.toSorted((a, b) => b.localeCompare(a)));   // Z to A

const collator = new Intl.Collator("en", { sensitivity: "base", numeric: true });
console.log(["file10.txt", "file2.txt", "file1.txt"].toSorted(collator.compare));

⌨️ Terminal

node strings.js

🖥️ Output

[ 'Asha', 'Bala', 'ravi', 'zoya', 'Ölaf', 'émile' ]
[ 'Asha', 'Bala', 'émile', 'Ölaf', 'ravi', 'zoya' ]
[ 'zoya', 'ravi', 'Ölaf', 'émile', 'Bala', 'Asha' ]
[ 'file1.txt', 'file2.txt', 'file10.txt' ]

numeric: true gives “natural” order, so file2 comes before file10, the way file explorers show them.


📅 Sorting Dates

Subtracting two Date objects gives the difference in milliseconds, which works as a comparator. ISO date strings (YYYY-MM-DD) also sort correctly as text.

📄 dates.js

const orders = [
  { id: 1, placed: "2026-11-20T09:15:00Z" },
  { id: 2, placed: "2026-11-23T14:02:00Z" },
  { id: 3, placed: "2026-10-31T18:40:00Z" },
];

const newestFirst = orders.toSorted((a, b) => new Date(b.placed) - new Date(a.placed));
console.log(newestFirst.map((o) => o.id));

const oldestFirst = orders.toSorted((a, b) => a.placed.localeCompare(b.placed));   // ISO strings
console.log(oldestFirst.map((o) => o.id));

⌨️ Terminal

node dates.js

🖥️ Output

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

⚠️ Watch out: Text dates in other formats, such as "23/11/2026", do not sort correctly as strings. Parse them into Date objects or ISO strings first.


🗂️ Sorting Objects by One or More Keys

📄 objects.js

const tests = [
  { name: "login", suite: "auth", ms: 820 },
  { name: "pay card", suite: "pay", ms: 2210 },
  { name: "logout", suite: "auth", ms: 310 },
  { name: "pay upi", suite: "pay", ms: 2210 },
  { name: "add item", suite: "cart", ms: 1430 },
];

// One key
const slowestFirst = tests.toSorted((a, b) => b.ms - a.ms);
console.log(slowestFirst.map((t) => `${t.name}:${t.ms}`));

// Two keys: suite A-Z, then duration ascending within each suite
const bySuiteThenTime = tests.toSorted((a, b) => a.suite.localeCompare(b.suite) || a.ms - b.ms);
console.log(bySuiteThenTime.map((t) => `${t.suite}/${t.name}:${t.ms}`));

⌨️ Terminal

node objects.js

🖥️ Output

[
  'pay card:2210',
  'pay upi:2210',
  'add item:1430',
  'login:820',
  'logout:310'
]
[
  'auth/logout:310',
  'auth/login:820',
  'cart/add item:1430',
  'pay/pay card:2210',
  'pay/pay upi:2210'
]

a.suite.localeCompare(b.suite) || a.ms - b.ms works because when the suites are equal, localeCompare returns 0 (falsy), so || moves on to the second comparison.

A small helper makes multi-key sorting readable and reusable:

📄 by-helper.js

const by = (...keys) => (a, b) => {
  for (const key of keys) {
    const desc = key.startsWith("-");
    const k = desc ? key.slice(1) : key;
    const cmp = typeof a[k] === "number" ? a[k] - b[k] : String(a[k]).localeCompare(String(b[k]));
    if (cmp !== 0) return desc ? -cmp : cmp;
  }
  return 0;
};

const products = [
  { name: "Pen", category: "office", price: 10 },
  { name: "Lamp", category: "home", price: 899 },
  { name: "Stapler", category: "office", price: 150 },
  { name: "Mug", category: "home", price: 199 },
];
console.log(products.toSorted(by("category", "-price")).map((p) => `${p.category}:${p.name}:${p.price}`));

⌨️ Terminal

node by-helper.js

🖥️ Output

[
  'home:Lamp:899',
  'home:Mug:199',
  'office:Stapler:150',
  'office:Pen:10'
]

🧷 Stability and sort vs toSorted

Definition: a sort is stable if items that compare as equal keep their original order. Since ES2019, Array.prototype.sort is guaranteed to be stable, so sorting by a second key after a first sort keeps the first order among ties.

📄 stable.js

const results = [
  { test: "a", status: "failed" },
  { test: "b", status: "passed" },
  { test: "c", status: "failed" },
  { test: "d", status: "passed" },
];
const failedFirst = results.toSorted((x, y) => (x.status === "failed" ? 0 : 1) - (y.status === "failed" ? 0 : 1));
console.log(failedFirst.map((r) => r.test));   // a before c, b before d: original order kept

⌨️ Terminal

node stable.js

🖥️ Output

[ 'a', 'c', 'b', 'd' ]
sort(fn)toSorted(fn) (ES2023)
Changes the original arrayYesNo
ReturnsThe same arrayA new sorted array
Use whenYou own the array and want to change itShared data, test fixtures, function inputs

✅ Checking Whether an Array Is Sorted

A UI test often checks that a column is sorted after clicking its header. Compare each item with the next one, or compare with a sorted copy:

📄 is-sorted.js

const isSorted = (arr, compare) => arr.every((item, i) => i === 0 || compare(arr[i - 1], item) <= 0);

const pricesAsc = [10, 45, 45, 199, 899];
const pricesBroken = [10, 199, 45, 899];
console.log(isSorted(pricesAsc, (a, b) => a - b), isSorted(pricesBroken, (a, b) => a - b));

const namesOnPage = ["Asha", "bala", "Ravi", "zoya"];
const expected = namesOnPage.toSorted((a, b) => a.localeCompare(b));
console.log(JSON.stringify(namesOnPage) === JSON.stringify(expected));

⌨️ Terminal

node is-sorted.js

🖥️ Output

true false
true

💡 Tip: Use the same comparison rules as the application (case-insensitive? natural numbers? locale?). A test that sorts with the default sort() will report false failures for correctly sorted, case-insensitive columns.


🔍 Searching Arrays

NeedMethodReturns
Is a value present?includes(value)Boolean
Where is a value?indexOf(value) / lastIndexOfIndex or -1
First item matching a rulefind(fn) / findLast(fn)Item or undefined
Index of first item matching a rulefindIndex(fn) / findLastIndex(fn)Index or -1
Does any / every item match?some(fn) / every(fn)Boolean
All items matching a rulefilter(fn)Array

These are linear searches: they check items one by one, which is fine for typical data. For large sorted arrays, binary search is much faster: it halves the search range at every step.

📄 binary-search.js

function binarySearch(sorted, target) {
  let low = 0;
  let high = sorted.length - 1;
  let steps = 0;
  while (low <= high) {
    steps++;
    const mid = Math.floor((low + high) / 2);
    if (sorted[mid] === target) return { index: mid, steps };
    if (sorted[mid] < target) low = mid + 1;
    else high = mid - 1;
  }
  return { index: -1, steps };
}

const ids = Array.from({ length: 1_000_000 }, (_, i) => i * 2);   // sorted even numbers
console.log(binarySearch(ids, 777_778));
console.log(binarySearch(ids, 777_777));                            // odd: not present
console.log("indexOf finds it too:", ids.indexOf(777_778));

⌨️ Terminal

node binary-search.js

🖥️ Output

{ index: 388889, steps: 20 }
{ index: -1, steps: 20 }
indexOf finds it too: 388889

Binary search needed about 20 steps for a million items, where a linear search might check up to a million. It only works when the array is sorted by the same rule you search with.


🧪 Tester Scenario: Verify Sorting After Clicking a Column

The values below simulate the price column of a product table read from a page before and after clicking “Sort by price ↓”. The check parses the text, then verifies the order and that no rows were lost:

📄 verify-sort.js

const before = ["₹1,299.00", "₹45.50", "₹899.00", "₹10.00", "₹45.50"];
const after = ["₹1,299.00", "₹899.00", "₹45.50", "₹45.50", "₹10.00"];

const toNumber = (text) => Number(text.replace(/[^\d.]/g, ""));
const afterNums = after.map(toNumber);

const descending = afterNums.every((p, i) => i === 0 || afterNums[i - 1] >= p);
const sameItems = JSON.stringify(before.map(toNumber).toSorted((a, b) => b - a)) === JSON.stringify(afterNums);

console.log("sorted descending:", descending);
console.log("same rows, nothing lost:", sameItems);
console.log("highest:", afterNums[0], "lowest:", afterNums.at(-1));

⌨️ Terminal

node verify-sort.js

🖥️ Output

sorted descending: true
same rows, nothing lost: true
highest: 1299 lowest: 10

Checking that the multiset of values is unchanged catches a real class of bugs: sorting implementations that drop, duplicate or re-fetch rows.


📝 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. Sort [40, 100, 1, 5, 25, 10] in ascending and descending order without changing the original array.

Show answer

📄 practice1.js

const nums = [40, 100, 1, 5, 25, 10];
console.log(nums.toSorted((a, b) => a - b), nums.toSorted((a, b) => b - a), nums);

🖥️ Output

[ 1, 5, 10, 25, 40, 100 ] [ 100, 40, 25, 10, 5, 1 ] [ 40, 100, 1, 5, 25, 10 ]

Q2. Sort ["banana", "Apple", "cherry", "apple"] alphabetically, ignoring case.

Show answer

📄 practice2.js

const fruits = ["banana", "Apple", "cherry", "apple"];
console.log(fruits.toSorted((a, b) => a.localeCompare(b, "en", { sensitivity: "base" })));

🖥️ Output

[ 'Apple', 'apple', 'banana', 'cherry' ]

Q3. Sort users by age (youngest first) and, for equal ages, by name.

const users = [
  { name: "Ravi", age: 30 },
  { name: "Asha", age: 25 },
  { name: "Bala", age: 30 },
];
Show answer

📄 practice3.js

const users = [
  { name: "Ravi", age: 30 },
  { name: "Asha", age: 25 },
  { name: "Bala", age: 30 },
];
console.log(users.toSorted((a, b) => a.age - b.age || a.name.localeCompare(b.name)).map((u) => u.name));

🖥️ Output

[ 'Asha', 'Bala', 'Ravi' ]

Q4. Find the 3 slowest tests from [{ t: "a", ms: 400 }, { t: "b", ms: 2200 }, { t: "c", ms: 900 }, { t: "d", ms: 3100 }, { t: "e", ms: 150 }].

Show answer

📄 practice4.js

const tests = [{ t: "a", ms: 400 }, { t: "b", ms: 2200 }, { t: "c", ms: 900 }, { t: "d", ms: 3100 }, { t: "e", ms: 150 }];
console.log(tests.toSorted((x, y) => y.ms - x.ms).slice(0, 3).map((x) => x.t));

🖥️ Output

[ 'd', 'b', 'c' ]

Q5. Write isSortedDesc(arr) that returns true if numbers never increase. Test [9, 7, 7, 2] and [9, 3, 5].

Show answer

📄 practice5.js

const isSortedDesc = (arr) => arr.every((v, i) => i === 0 || arr[i - 1] >= v);
console.log(isSortedDesc([9, 7, 7, 2]), isSortedDesc([9, 3, 5]));

🖥️ Output

true false

Q6. Sort the date strings ["23/11/2026", "05/01/2026", "30/06/2025"] from oldest to newest.

Show answer

📄 practice6.js

const dates = ["23/11/2026", "05/01/2026", "30/06/2025"];
const toIso = (d) => d.split("/").reverse().join("-");
console.log(dates.toSorted((a, b) => toIso(a).localeCompare(toIso(b))));

🖥️ Output

[ '30/06/2025', '05/01/2026', '23/11/2026' ]

Converting DD/MM/YYYY to YYYY-MM-DD makes simple string comparison correct.


🧠 MCQ Quiz: Sorting and Searching Arrays

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 [10, 9, 1].sort() return?
  2. Which comparator sorts numbers in ascending order?
  3. What does a comparator returning 0 mean?
  4. Does sort change the original array?
  5. Why is (a, b) => a > b a bad comparator?
  6. How do you sort strings so that “apple” and “Zebra” are in natural alphabetical order?
  7. How do you sort by name, then by age for equal names?
  8. Since which edition is Array.prototype.sort guaranteed to be stable?
  9. When can you use binary search?
  10. Where does sort() put undefined values?

💼 Interview Questions and Answers

Q1. Why does [1, 10, 2].sort() not sort numerically, and how do you fix it?

Without a compare function, sort converts elements to strings and compares UTF-16 code units, so “10” comes before “2”. Pass a numeric comparator: arr.sort((a, b) => a - b) for ascending or (a, b) => b - a for descending, or use toSorted to avoid mutating the array.

Q2. How do you sort an array of objects by multiple fields?

Write a comparator that compares the first field and falls back to the next only when the first is equal: (a, b) => a.lastName.localeCompare(b.lastName) || a.firstName.localeCompare(b.firstName) || a.age - b.age. Because sort is stable (ES2019+), you can also sort by the least important key first and the most important key last.

Q3. How would you test that a table column is sorted correctly?

  1. Read the column values (for example allTextContents()) and normalise them: trim, parse numbers and dates.
  2. Build the expected order with the same rules as the application (direction, case sensitivity, locale, natural number order).
  3. Assert the actual array equals the expected sorted copy, or that every adjacent pair is in order.
  4. Also assert the count and the set of values are unchanged, so missing or duplicated rows are caught.
  5. Test ties, empty values and pagination (sorted across pages, not just within one page).

Q4. What is the time complexity of sorting and of binary search?

Engine sorts are O(n log n) on average (V8 uses TimSort). Linear search methods (indexOf, find, includes) are O(n). Binary search on a sorted array is O(log n): a million items need about 20 comparisons. Sorting once and then running many binary searches pays off only when you search many times.


❓ Frequently Asked Questions

🤔 How do I sort an array in descending order?

For numbers use arr.toSorted((a, b) => b - a); for strings use (a, b) => b.localeCompare(a). Or sort ascending and call toReversed().

🤔 How do I sort without changing the original array?

Use toSorted(compareFn) (ES2023), or copy first: [...arr].sort(compareFn).

🤔 How do I shuffle an array randomly?

Do not use sort(() => Math.random() - 0.5); it is biased. Use the Fisher–Yates algorithm: loop from the end and swap each item with a random earlier one.

🤔 Is localeCompare slow for big arrays?

It can be when called thousands of times. Create one Intl.Collator and pass collator.compare as the comparator.


🏁 Summary

  • The default sort() compares items as strings, so always pass a comparator for numbers, dates and objects.
  • A comparator returns negative (a first), positive (b first) or 0 (keep order); use a - b for numbers and localeCompare for text.
  • Chain comparisons with || to sort by several keys; sort is stable since ES2019.
  • sort mutates; toSorted returns a new array, which is safer for shared data.
  • Use linear search methods for everyday searches and binary search for large sorted arrays.

Next, continue with Lesson 33: Objects. This completes Module 6. Module 7 continues with objects and collections.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Destructuring and Spread Syntax for Arrays and Objects

Destructuring pulls values out of arrays and objects into variables in one line, and spread copies and merges them. Together they make code shorter and clearer, and you see them everywhere in modern JavaScript: const { page } = ... in every Playwright test, { ...defaults, ...overrides } for test configuration, and [first, ...rest] for table rows. In this lesson you will learn every form of destructuring and spread, with defaults, renaming, nesting and the traps to avoid.

📖 What You’ll Learn: array destructuring, skipping items, defaults, the rest pattern, swapping variables, object destructuring, renaming, defaults for missing properties, nested destructuring, destructuring in function parameters and loops, spread for arrays (copy, merge, insert), spread for objects (copy, merge, override), shallow-copy limits, and practical test-data patterns.


📦 Array Destructuring

Definition: destructuring is a syntax that unpacks values from arrays (by position) or objects (by name) into separate variables.

📄 array.js

const point = [10, 20, 30];

// Without destructuring
const x1 = point[0];
const y1 = point[1];

// With destructuring
const [x, y, z] = point;
console.log(x1, y1, "|", x, y, z);

const [first, , third] = ["a", "b", "c"];   // skip an item with an empty slot
console.log(first, third);

const [one, two, extra] = [1, 2];           // missing items are undefined
console.log(one, two, extra);

⌨️ Terminal

node array.js

🖥️ Output

10 20 | 10 20 30
a c
1 2 undefined

Default values

📄 array-defaults.js

const [env = "qa", browser = "chromium", workers = 2] = ["staging"];
console.log(env, browser, workers);

const [a = 1] = [null];      // defaults apply only to undefined
console.log(a);

⌨️ Terminal

node array-defaults.js

🖥️ Output

staging chromium 2
null

The rest pattern

...name as the last item collects the remaining elements into a new array:

📄 array-rest.js

const [header, ...rows] = [
  ["Name", "Role"],
  ["Asha", "Tester"],
  ["Ravi", "Developer"],
];
console.log(header);
console.log(rows);

const [winner, ...others] = ["chromium", "firefox", "webkit"];
console.log(winner, others);

⌨️ Terminal

node array-rest.js

🖥️ Output

[ 'Name', 'Role' ]
[ [ 'Asha', 'Tester' ], [ 'Ravi', 'Developer' ] ]
chromium [ 'firefox', 'webkit' ]

Swapping variables

📄 swap.js

let left = "login";
let right = "logout";
[left, right] = [right, left];
console.log(left, right);

⌨️ Terminal

node swap.js

🖥️ Output

logout login

🗂️ Object Destructuring

Object destructuring takes properties by name, so order does not matter:

📄 object.js

const user = { id: 7, name: "Asha", role: "tester", city: "Pune" };

const { name, role } = user;
console.log(name, role);

const { city, id } = user;           // any order
console.log(id, city);

const { email } = user;              // missing property: undefined
console.log(email);

⌨️ Terminal

node object.js

🖥️ Output

Asha tester
7 Pune
undefined

Renaming and defaults

{ property: newName } stores the value under a different variable name, and = value sets a default for missing (undefined) properties. You can combine both:

📄 rename.js

const response = { status: 200, data: { items: [] }, headers: { "content-type": "application/json" } };

const { status: code, data: body } = response;
console.log(code, body);

const { timeout = 30000, retries: maxRetries = 2 } = { retries: 0 };
console.log(timeout, maxRetries);      // 0 is kept: defaults only replace undefined

const { "content-type": contentType } = response.headers;   // property names with dashes
console.log(contentType);

⌨️ Terminal

node rename.js

🖥️ Output

200 { items: [] }
30000 0
application/json

Rest in objects

📄 object-rest.js

const user = { id: 7, name: "Asha", password: "secret", token: "abc" };
const { password, token, ...safeUser } = user;   // remove sensitive fields
console.log(safeUser);

⌨️ Terminal

node object-rest.js

🖥️ Output

{ id: 7, name: 'Asha' }

💡 Tip: The rest pattern is a clean way to remove fields before logging or sending an object, such as stripping passwords and tokens from test logs.


🪆 Nested Destructuring

Patterns can mirror the shape of nested data:

📄 nested.js

const order = {
  id: 501,
  customer: { name: "Asha", address: { city: "Pune", pin: "411001" } },
  items: [
    { sku: "PEN-1", qty: 3 },
    { sku: "BOOK-9", qty: 1 },
  ],
};

const {
  id,
  customer: { name, address: { city } },
  items: [firstItem, ...otherItems],
} = order;

console.log(id, name, city);
console.log(firstItem.sku, otherItems.length);

⌨️ Terminal

node nested.js

🖥️ Output

501 Asha Pune
PEN-1 1

Note that customer and address are not created as variables here; they only describe the path. Only the names at the end of each path (name, city) become variables.

⚠️ Watch out: Destructuring a missing nested object throws. If customer could be missing, give it a default object: const { customer: { name } = {} } = order;.

📄 nested-missing.js

const order = { id: 502 };   // no customer
try {
  const { customer: { name } } = order;
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}
const { customer: { name = "Guest" } = {} } = order;
console.log(name);

⌨️ Terminal

node nested-missing.js

🖥️ Output

TypeError: Cannot read properties of undefined (reading 'name')
Guest

🔧 Destructuring in Parameters and Loops

Destructuring in a function’s parameter list is very common. It is the “options object” pattern from the Parameters lesson, and it is how Playwright passes fixtures into tests:

📄 params.js

function formatUser({ name, role = "viewer", address: { city } = {} }) {
  return `${name} (${role})${city ? " from " + city : ""}`;
}
console.log(formatUser({ name: "Asha", role: "tester", address: { city: "Pune" } }));
console.log(formatUser({ name: "Ravi" }));

// Playwright style: async ({ page, request }) => { ... }
const runTest = async ({ page, baseURL = "https://qa.example.com" }) => `${page} opened ${baseURL}`;
runTest({ page: "page#1" }).then(console.log);

⌨️ Terminal

node params.js

🖥️ Output

Asha (tester) from Pune
Ravi (viewer)
page#1 opened https://qa.example.com

In loops, destructure each element directly:

📄 loops.js

const results = [
  { test: "login", status: "passed", ms: 820 },
  { test: "cart", status: "failed", ms: 1430 },
];
for (const { test, status } of results) {
  console.log(test, status);
}

const config = { env: "qa", workers: 4 };
for (const [key, value] of Object.entries(config)) {
  console.log(`${key}=${value}`);
}

console.log(results.map(({ test, ms }) => `${test}:${ms}`));

⌨️ Terminal

node loops.js

🖥️ Output

login passed
cart failed
env=qa
workers=4
[ 'login:820', 'cart:1430' ]

🌊 Spread with Arrays

Definition: spread syntax ...value expands an iterable (such as an array, string or Set) into individual elements. It looks like rest, but appears where values are used, not where variables are declared.

📄 array-spread.js

const smoke = ["login", "search"];
const regression = ["refund", "export"];

const all = [...smoke, ...regression];          // merge
const copy = [...smoke];                         // shallow copy
const withExtra = ["setup", ...smoke, "teardown"];  // insert around
console.log(all, copy === smoke, withExtra);

console.log([..."QA"]);                          // string -> characters
console.log([...new Set([3, 1, 3, 2, 1])]);      // unique values
console.log(Math.max(...[12, 99, 45]));          // into function arguments

⌨️ Terminal

node array-spread.js

🖥️ Output

[ 'login', 'search', 'refund', 'export' ] false [ 'setup', 'login', 'search', 'teardown' ]
[ 'Q', 'A' ]
[ 3, 1, 2 ]
99

🧬 Spread with Objects

Object spread copies an object’s own properties into a new object. When the same key appears more than once, the last one wins, which makes spread perfect for “defaults plus overrides”:

📄 object-spread.js

const defaults = { browser: "chromium", headless: true, retries: 0, timeout: 30000 };
const ciOverrides = { retries: 2, workers: 4 };
const localOverrides = { headless: false };

const ciConfig = { ...defaults, ...ciOverrides };
const localConfig = { ...defaults, ...localOverrides };
console.log(ciConfig);
console.log(localConfig);

const user = { name: "Asha", role: "tester" };
const promoted = { ...user, role: "lead", since: 2026 };   // copy + change + add
console.log(user, promoted);

const wrongOrder = { role: "lead", ...user };             // user's role overwrites "lead"
console.log(wrongOrder.role);

⌨️ Terminal

node object-spread.js

🖥️ Output

{
  browser: 'chromium',
  headless: true,
  retries: 2,
  timeout: 30000,
  workers: 4
}
{ browser: 'chromium', headless: false, retries: 0, timeout: 30000 }
{ name: 'Asha', role: 'tester' } { name: 'Asha', role: 'lead', since: 2026 }
tester

⚠️ Watch out: Spread makes a shallow copy. Nested objects and arrays are still shared between the original and the copy. Changing copy.address.city also changes the original. Use structuredClone for a deep copy, or spread each nested level you change.

📄 shallow.js

const base = { name: "Asha", address: { city: "Pune" } };
const shallow = { ...base };
shallow.address.city = "Delhi";
console.log(base.address.city);              // changed!

const safe = { ...base, address: { ...base.address, city: "Mumbai" } };
console.log(base.address.city, safe.address.city);

⌨️ Terminal

node shallow.js

🖥️ Output

Delhi
Delhi Mumbai

🧪 Tester Scenario: Build Test Data Variations

A base valid user plus small overrides gives you every variation a form test needs, with each test showing only what is different:

📄 variations.js

const validUser = Object.freeze({
  firstName: "Asha",
  lastName: "Rao",
  email: "asha@sqatools.in",
  password: "Secret@123",
  address: Object.freeze({ city: "Pune", pin: "411001" }),
});

const build = (overrides = {}) => ({
  ...validUser,
  ...overrides,
  address: { ...validUser.address, ...overrides.address },
});

const cases = [
  ["valid user", build(), true],
  ["missing email", build({ email: "" }), false],
  ["short password", build({ password: "abc" }), false],
  ["invalid PIN", build({ address: { pin: "12" } }), false],
];

const isValid = ({ email, password, address: { pin } }) =>
  email.includes("@") && password.length >= 8 && /^\d{6}$/.test(pin);

for (const [name, data, expected] of cases) {
  const actual = isValid(data);
  console.log(`${actual === expected ? "PASS" : "FAIL"} ${name.padEnd(15)} city=${data.address.city} pin=${data.address.pin}`);
}
console.log("base untouched:", validUser.address.pin);

⌨️ Terminal

node variations.js

🖥️ Output

PASS valid user      city=Pune pin=411001
PASS missing email   city=Pune pin=411001
PASS short password  city=Pune pin=411001
PASS invalid PIN     city=Pune pin=12
base untouched: 411001
  • Object.freeze makes accidental changes to the base data impossible.
  • build merges overrides over the base and also merges the nested address, so overriding only pin keeps the city.
  • The validator destructures exactly the fields it needs, directly in its parameter list.

📝 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. Destructure ["2026", "11", "23"] into year, month and day, and print 23/11/2026.

Show answer

📄 practice1.js

const [year, month, day] = "2026-11-23".split("-");
console.log(`${day}/${month}/${year}`);

🖥️ Output

23/11/2026

Q2. From { status: 404, statusText: "Not Found", body: null }, take status as code and statusText as message, and print them.

Show answer

📄 practice2.js

const res = { status: 404, statusText: "Not Found", body: null };
const { status: code, statusText: message } = res;
console.log(code, message);

🖥️ Output

404 Not Found

Q3. Write describe({ name, tags = [] }) that returns "name [tag1, tag2]" or "name [no tags]".

Show answer

📄 practice3.js

function describe({ name, tags = [] }) {
  return `${name} [${tags.length ? tags.join(", ") : "no tags"}]`;
}
console.log(describe({ name: "login", tags: ["smoke", "auth"] }));
console.log(describe({ name: "export" }));

🖥️ Output

login [smoke, auth]
export [no tags]

Q4. Remove the password field from { user: "asha", password: "x", role: "tester" } without changing the original object.

Show answer

📄 practice4.js

const account = { user: "asha", password: "x", role: "tester" };
const { password, ...publicAccount } = account;
console.log(publicAccount, account);

🖥️ Output

{ user: 'asha', role: 'tester' } { user: 'asha', password: 'x', role: 'tester' }

Q5. Merge { retries: 0, workers: 1 } with { workers: 4, reporter: "html" } so the second object wins on conflicts.

Show answer

📄 practice5.js

const base = { retries: 0, workers: 1 };
const ci = { workers: 4, reporter: "html" };
console.log({ ...base, ...ci });

🖥️ Output

{ retries: 0, workers: 4, reporter: 'html' }

Q6. Get the city from const data = { user: { profile: { address: { city: "Pune" } } } } with one nested destructuring statement.

Show answer

📄 practice6.js

const data = { user: { profile: { address: { city: "Pune" } } } };
const { user: { profile: { address: { city } } } } = data;
console.log(city);

🖥️ Output

Pune

🧠 MCQ Quiz: Destructuring and Spread

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 b after const [a, b] = [10, 20, 30];?
  2. What is rest after const [x, ...rest] = [1, 2, 3];?
  3. How do you rename while destructuring { status } into a variable called code?
  4. What is t after const { t = 5 } = { t: null };?
  5. How do you swap a and b?
  6. What is { ...{ a: 1, b: 2 }, b: 3 }?
  7. Is { ...obj } a deep copy?
  8. What happens with const { a: { b } } = {};?
  9. What does [...new Set([1, 1, 2])] produce?
  10. In test("x", async ({ page }) => ...), what is { page }?

💼 Interview Questions and Answers

Q1. What is the difference between the rest and spread syntax?

Both use .... Rest collects multiple values into one: in function parameters (function f(...args)) and in destructuring patterns (const [first, ...others] = arr). Spread expands one iterable or object into many: in function calls (f(...arr)), array literals ([...a, ...b]) and object literals ({ ...obj }).

Q2. How does object spread handle duplicate keys and nested objects?

Properties are copied left to right, so for duplicate keys the last one wins; this is why { ...defaults, ...overrides } works. The copy is shallow: nested objects are copied by reference, so changing them through the copy also changes the original. Spread nested levels explicitly or use structuredClone for deep copies.

Q3. Predict the output.

📄 predict.js

const { a = 1, b = 2, c = 3 } = { a: undefined, b: null };
const [x = 10, y = x * 2] = [];
console.log(a, b, c, x, y);

⌨️ Terminal

node predict.js

🖥️ Output

1 null 3 10 20

Defaults apply to undefined (a and the missing c), not to null, so b stays null. Defaults can refer to earlier variables, so y is x * 2 = 20.

Q4. How would you use destructuring and spread to manage test configuration?

Keep a frozen object of defaults, merge environment-specific overrides with spread ({ ...defaults, ...envConfig, ...cliOverrides }), and destructure only the needed settings in helpers (function launch({ browser, headless = true })). Strip secrets before logging with a rest pattern (const { password, ...safe } = config). This keeps every test explicit about what it changes.


❓ Frequently Asked Questions

🤔 Can I destructure a function’s return value?

Yes, and it is a common way to return several values: const { min, max } = stats(list); or const [data, error] = await safeCall();.

🤔 Does destructuring copy objects?

No. Destructured variables hold the same values; if a value is an object, the variable refers to the same object.

🤔 Can I spread an object into an array?

Not directly; plain objects are not iterable. Use Object.values(obj), Object.keys(obj) or Object.entries(obj) and spread that.

🤔 What happens if I destructure null or undefined?

It throws a TypeError (“Cannot destructure property … of undefined”). Give the source a default, for example function f({ a } = {}) or const { a } = obj ?? {}.


🏁 Summary

  • Array destructuring unpacks by position; object destructuring unpacks by name.
  • Use name: newName to rename, = value for defaults (undefined only), and ...rest to collect the remainder.
  • Nested patterns mirror nested data; give optional nested objects a default = {}.
  • Spread copies and merges arrays and objects; for duplicate keys the last one wins.
  • Spread copies are shallow: use structuredClone or spread nested levels to avoid shared changes.

Next, continue with Lesson 32: Sorting and Searching Arrays.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Arrays: Create, Access, Update and Loop Through Arrays

An array is an ordered list of values: test names, prices from a table, rows of test data, API results. Almost every program and every test works with arrays. In this lesson you will learn how to create arrays, read and change items by index, add and remove items, loop through them, work with nested arrays, and avoid the bugs that come from arrays being objects that are shared by reference.

📖 What You’ll Learn: what an array is, creating arrays with literals, Array.of and Array.from, indexes and at(), length and how it changes, adding and removing items with push, pop, shift and unshift, updating items, checking for arrays, looping, nested arrays and tables, arrays as references, copying arrays, holes and array-like objects.


📋 What Is an Array?

Definition: an array is an ordered collection of values, called elements. Each element has a numbered position, its index, starting at 0. An array can hold any mix of types, including other arrays and objects.

📄 arrays.js

const browsers = ["chromium", "firefox", "webkit"];
const prices = [499, 1299.5, 89];
const mixed = ["login", 200, true, null, { retries: 2 }, [1, 2]];
const empty = [];

console.log(browsers);
console.log(prices.length, empty.length);
console.log(mixed[4].retries, mixed[5][1]);
console.log(typeof browsers, Array.isArray(browsers));

⌨️ Terminal

node arrays.js

🖥️ Output

[ 'chromium', 'firefox', 'webkit' ]
3 0
2 2
object true
  • Write arrays with square brackets; separate elements with commas. A trailing comma after the last element is allowed.
  • typeof reports "object" for arrays; use Array.isArray() to check for an array.
  • In practice, keep one type of item per array (all strings, or all user objects). Mixed arrays are harder to work with.

🏗️ Other Ways to Create Arrays

📄 create.js

console.log(Array.of(7));                         // [7]
console.log(new Array(3));                        // 3 empty slots (avoid)
console.log(new Array(3).fill(0));                // [0, 0, 0]
console.log(Array.from("QA"));                     // from a string
console.log(Array.from({ length: 5 }, (_, i) => i + 1));   // [1..5]
console.log(Array.from(new Set(["a", "b", "a"])));  // from a Set: unique values
console.log("pen,book,lamp".split(","));          // from text

⌨️ Terminal

node create.js

🖥️ Output

[ 7 ]
[ <3 empty items> ]
[ 0, 0, 0 ]
[ 'Q', 'A' ]
[ 1, 2, 3, 4, 5 ]
[ 'a', 'b' ]
[ 'pen', 'book', 'lamp' ]

⚠️ Watch out: new Array(3) creates an array with 3 empty slots, not [3]. Methods such as map skip empty slots, which leads to surprising results. Prefer literals, Array.of or Array.from({ length: n }, fn).

Array.from({ length: n }, (_, i) => ...) is the standard way to generate test data: the callback receives the index i (the underscore is a placeholder name for the unused first argument).


🔢 Reading Elements: Indexes and at()

📄 read.js

const steps = ["open", "login", "search", "checkout", "logout"];

console.log(steps[0]);                 // first
console.log(steps[2]);
console.log(steps[steps.length - 1]);  // last, classic way
console.log(steps.at(-1), steps.at(-2)); // last and second-last with at()
console.log(steps[10]);                // out of range: undefined (no error)
console.log(steps.indexOf("search"), steps.includes("refund"));

⌨️ Terminal

node read.js

🖥️ Output

open
search
logout
logout checkout
undefined
2 false

⚠️ Watch out: Reading an index that does not exist returns undefined silently. If you then read a property, such as rows[10].price, you get TypeError: Cannot read properties of undefined. Check the length, or use rows[10]?.price.


📏 The length Property

length is always one more than the highest index. It updates automatically, and you can also set it to shorten an array:

📄 length.js

const queue = ["a", "b", "c"];
console.log(queue.length);

queue[5] = "f";              // assigning beyond the end creates empty slots
console.log(queue, queue.length);

queue.length = 2;            // truncate
console.log(queue);

queue.length = 0;            // empty the array in place
console.log(queue, queue.length === 0);

⌨️ Terminal

node length.js

🖥️ Output

3
[ 'a', 'b', 'c', <2 empty items>, 'f' ] 6
[ 'a', 'b' ]
[] true

💡 Tip: To check whether an array is empty, use arr.length === 0. Never write if (arr): an empty array is truthy.


➕ Adding and Removing Items

Four methods add or remove items at the ends. All four change the original array (they mutate it):

MethodDoesReturns
push(x, ...)Adds to the endNew length
pop()Removes the last itemThe removed item
unshift(x, ...)Adds to the startNew length
shift()Removes the first itemThe removed item

📄 add-remove.js

const cart = ["pen"];

console.log(cart.push("book", "lamp"));   // returns the new length
console.log(cart);
console.log(cart.pop());                   // returns "lamp"
console.log(cart.unshift("bag"));
console.log(cart);
console.log(cart.shift());                 // returns "bag"
console.log(cart);
console.log([].pop());                     // empty array: undefined

⌨️ Terminal

node add-remove.js

🖥️ Output

3
[ 'pen', 'book', 'lamp' ]
lamp
3
[ 'bag', 'pen', 'book' ]
bag
[ 'pen', 'book' ]
undefined

A stack (last in, first out) uses push and pop; a queue (first in, first out) uses push and shift. To insert or remove in the middle, use splice (next lesson).


✏️ Updating Elements

Assign to an index to replace an element. This works even with const, because const fixes the variable, not the array contents (see the Variables lesson).

📄 update.js

const statuses = ["passed", "failed", "passed"];
statuses[1] = "retried";
console.log(statuses);

const users = [{ name: "Asha", active: true }, { name: "Ravi", active: true }];
users[1].active = false;            // change a property of an object inside the array
console.log(users);

// ES2023: with() returns a NEW array with one item replaced, leaving the original untouched
const updated = statuses.with(0, "skipped");
console.log(updated, statuses);

⌨️ Terminal

node update.js

🖥️ Output

[ 'passed', 'retried', 'passed' ]
[ { name: 'Asha', active: true }, { name: 'Ravi', active: false } ]
[ 'skipped', 'retried', 'passed' ] [ 'passed', 'retried', 'passed' ]

🔁 Looping Through Arrays

The Loops lesson covered every loop. For arrays, the three you will use most are:

📄 loop.js

const tests = ["login", "search", "cart"];

for (const test of tests) {                       // values
  console.log("run", test);
}

for (const [i, test] of tests.entries()) {        // index + value
  console.log(`${i + 1}/${tests.length} ${test}`);
}

tests.forEach((test, i) => console.log(i, test.toUpperCase()));   // callback style

⌨️ Terminal

node loop.js

🖥️ Output

run login
run search
run cart
1/3 login
2/3 search
3/3 cart
0 LOGIN
1 SEARCH
2 CART

To build a new array from an existing one, the methods map, filter and reduce (lesson 30) are usually clearer than a loop with push.


🧮 Nested Arrays: Tables and Grids

An array of arrays represents a table: each inner array is a row. Use two indexes, table[row][column], to reach a cell.

📄 table.js

const table = [
  ["Name", "Role", "City"],
  ["Asha", "Tester", "Pune"],
  ["Ravi", "Developer", "Delhi"],
];

console.log(table[1][0], table[2][2]);    // row 1 col 0, row 2 col 2
console.log(table.length, "rows,", table[0].length, "columns");

const [header, ...rows] = table;          // destructuring: first row and the rest
for (const row of rows) {
  console.log(header.map((h, i) => `${h}=${row[i]}`).join(", "));
}

const cities = rows.map((row) => row[2]);
console.log(cities);

⌨️ Terminal

node table.js

🖥️ Output

Asha Delhi
3 rows, 3 columns
Name=Asha, Role=Tester, City=Pune
Name=Ravi, Role=Developer, City=Delhi
[ 'Pune', 'Delhi' ]

This is exactly the shape you get when you read an HTML table cell by cell in a test, or parse a CSV file.


🔗 Arrays Are References: Copying Safely

Arrays are objects, so assigning an array to another variable copies the reference, not the items. Both names point to the same array:

📄 reference.js

const original = ["smoke", "login"];
const alias = original;
alias.push("regression");
console.log(original);              // changed too!
console.log(alias === original);

const copy1 = [...original];        // spread copy
const copy2 = original.slice();     // slice copy
const copy3 = Array.from(original);
copy1.push("api");
console.log(original.length, copy1.length, copy2 === original, copy3 === original);

⌨️ Terminal

node reference.js

🖥️ Output

[ 'smoke', 'login', 'regression' ]
true
3 4 false false

These copies are shallow: objects inside the array are still shared. For a full independent copy, use structuredClone:

📄 deep-copy.js

const users = [{ name: "Asha", tags: ["ui"] }];
const shallow = [...users];
const deep = structuredClone(users);

shallow[0].tags.push("api");     // changes the shared object
deep[0].tags.push("mobile");     // changes only the deep copy

console.log(JSON.stringify(users));
console.log(JSON.stringify(deep));

⌨️ Terminal

node deep-copy.js

🖥️ Output

[{"name":"Asha","tags":["ui","api"]}]
[{"name":"Asha","tags":["ui","mobile"]}]

Comparing arrays with === checks whether they are the same array, not whether they have the same items: [1, 2] === [1, 2] is false. Use deep equality (toEqual in tests), as shown in the Equality lesson.


🧪 Tester Scenario: Collect and Check Table Data

This simulates reading a product table from a page (in Playwright you would get the cell texts with locator.allTextContents()) and checking it:

📄 table-check.js

const cellTexts = [
  "Pen", "₹10.00", "In stock",
  "Notebook", "₹45.50", "In stock",
  "Lamp", "₹899.00", "Out of stock",
];

const COLUMNS = 3;
const rows = [];
for (let i = 0; i < cellTexts.length; i += COLUMNS) {
  const [name, price, stock] = cellTexts.slice(i, i + COLUMNS);
  rows.push({ name, price: Number(price.replace(/[^\d.]/g, "")), inStock: stock === "In stock" });
}

console.table(rows);
console.log("row count ok:", rows.length === 3);
console.log("names:", rows.map((r) => r.name).join(", "));
console.log("out of stock:", rows.filter((r) => !r.inStock).map((r) => r.name));
console.log("most expensive:", rows.reduce((a, b) => (b.price > a.price ? b : a)).name);

⌨️ Terminal

node table-check.js

🖥️ Output

┌─────────┬────────────┬───────┬─────────┐
│ (index) │ name       │ price │ inStock │
├─────────┼────────────┼───────┼─────────┤
│ 0       │ 'Pen'      │ 10    │ true    │
│ 1       │ 'Notebook' │ 45.5  │ true    │
│ 2       │ 'Lamp'     │ 899   │ false   │
└─────────┴────────────┴───────┴─────────┘
row count ok: true
names: Pen, Notebook, Lamp
out of stock: [ 'Lamp' ]
most expensive: Lamp

Turning flat text into an array of objects first makes every later check a short, readable line.


📝 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 an array of 5 city names, print the first, the last (with at) and the total count.

Show answer

📄 practice1.js

const cities = ["Pune", "Delhi", "Mumbai", "Chennai", "Kolkata"];
console.log(cities[0], cities.at(-1), cities.length);

🖥️ Output

Pune Kolkata 5

Q2. Start with an empty array log. Push “start”, “step 1” and “step 2”, remove the last item with pop, add “init” at the beginning, and print the array.

Show answer

📄 practice2.js

const log = [];
log.push("start", "step 1", "step 2");
log.pop();
log.unshift("init");
console.log(log);

🖥️ Output

[ 'init', 'start', 'step 1' ]

Q3. Create an array of the squares of 1 to 10 using Array.from.

Show answer

📄 practice3.js

const squares = Array.from({ length: 10 }, (_, i) => (i + 1) ** 2);
console.log(squares);

🖥️ Output

[
   1,  4,  9, 16,  25,
  36, 49, 64, 81, 100
]

Q4. Given the grid [[1, 2, 3], [4, 5, 6], [7, 8, 9]], print the middle value and the sum of the diagonal (1 + 5 + 9).

Show answer

📄 practice4.js

const grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let diagonal = 0;
for (let i = 0; i < grid.length; i++) diagonal += grid[i][i];
console.log(grid[1][1], diagonal);

🖥️ Output

5 15

Q5. Explain the output, then change the code so defaults is not modified.

const defaults = ["chromium"];
const browsers = defaults;
browsers.push("firefox");
console.log(defaults);
Show answer

browsers and defaults are the same array, so pushing through either name changes it. Copy it first:

📄 practice5.js

const defaults = ["chromium"];
const browsers = [...defaults];
browsers.push("firefox");
console.log(defaults, browsers);

🖥️ Output

[ 'chromium' ] [ 'chromium', 'firefox' ]

Q6. Write lastN(arr, n) that returns the last n items without changing the array, and returns the whole array if n is larger than its length.

Show answer

📄 practice6.js

function lastN(arr, n) {
  return n >= arr.length ? [...arr] : arr.slice(-n);
}
const runs = [1, 2, 3, 4, 5];
console.log(lastN(runs, 2), lastN(runs, 10), runs);

🖥️ Output

[ 4, 5 ] [ 1, 2, 3, 4, 5 ] [ 1, 2, 3, 4, 5 ]

🧠 MCQ Quiz: Arrays Basics

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 index of the first element of an array?
  2. What is ["a", "b", "c"].length?
  3. What does ["a", "b"][5] return?
  4. What does push return?
  5. Which method removes the first element?
  6. What does typeof [] return?
  7. What does new Array(3) create?
  8. After const a = [1]; const b = a; b.push(2); what is a?
  9. Which creates an independent copy including nested objects?
  10. How do you check that an array is empty?

💼 Interview Questions and Answers

Q1. What is an array in JavaScript, and how is it different from arrays in Java?

A JavaScript array is an ordered, zero-indexed, dynamically sized list that can hold values of any type. It is an object with numeric keys and a special length property. Unlike Java arrays, it grows and shrinks automatically, can mix types, and has many built-in methods. Typed arrays (Int32Array etc.) exist for fixed-type binary data.

Q2. What is the difference between push/pop and unshift/shift?

push/pop work at the end of the array; unshift/shift work at the start. All four mutate the array. push/unshift return the new length; pop/shift return the removed item (or undefined if empty). Adding or removing at the start requires moving every other element, so it is slower for very large arrays.

Q3. How do you copy an array, and what is the difference between a shallow and a deep copy?

Shallow copies: [...arr], arr.slice(), Array.from(arr). They create a new array, but object elements are still shared. Deep copy: structuredClone(arr) copies nested objects too (older code used JSON.parse(JSON.stringify(arr)), which loses dates, undefined and functions).

Q4. Predict the output.

📄 predict.js

const a = [1, 2, 3];
a[10] = 99;
console.log(a.length, a[5], 5 in a);
console.log([1, 2] == "1,2", [1, 2] === [1, 2]);

⌨️ Terminal

node predict.js

🖥️ Output

11 undefined false
true false

Assigning index 10 sets length to 11 and leaves empty slots, so a[5] is undefined and 5 in a is false. [1, 2] == "1,2" converts the array to a string, so it is true; two separate arrays are never ===.


❓ Frequently Asked Questions

🤔 Can a JavaScript array hold different types?

Yes, but keep one type per array in real code; it makes methods like map and sort predictable. Use objects for records with mixed fields.

🤔 Is there a maximum array size?

The maximum length is 232 − 1 items, far more than memory allows in practice.

🤔 Why can I change a const array?

const prevents reassigning the variable, not changing the array it points to. Use Object.freeze(arr) to make it read-only.

🤔 What is the difference between an array and an object?

Arrays are ordered and indexed by number, with a length and list methods. Objects store named properties. Use arrays for lists and objects for records.


🏁 Summary

  • Arrays are ordered, zero-indexed lists created with [], Array.of or Array.from.
  • Read with arr[i] or arr.at(-1); out-of-range reads return undefined.
  • push/pop work at the end, unshift/shift at the start, and all mutate the array.
  • Nested arrays model tables: table[row][col].
  • Arrays are copied by reference: use spread or slice for shallow copies and structuredClone for deep copies.

Next, continue with Lesson 29: Array Methods.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript map, filter and reduce (plus find, some, every) Explained

map, filter and reduce are the three array methods you will use most once you start working with real data: transforming API responses, picking failed tests, totalling prices, grouping results by status. They replace most hand-written loops with short, readable code. In this lesson you will learn exactly what each one does, how to chain them, the related search methods find, some and every, the new Object.groupBy, and the mistakes that trip up beginners.

📖 What You’ll Learn: map to transform every item, filter to keep matching items, reduce to combine items into one value, the callback arguments, find, findLast, findIndex, some and every, chaining methods into pipelines, grouping with reduce and Object.groupBy, when to use a loop instead, and common mistakes such as forgetting to return.


🗺️ map: Transform Every Item

Definition: arr.map(callback) calls the callback for every item and returns a new array of the same length containing whatever the callback returned. The original array is not changed.

📄 map.js

const prices = [100, 250, 80];
const withTax = prices.map((p) => p * 1.18);
console.log(withTax, prices);

const users = [
  { first: "Asha", last: "Rao", role: "tester" },
  { first: "Ravi", last: "Kumar", role: "dev" },
];
console.log(users.map((u) => `${u.first} ${u.last}`));
console.log(users.map((u) => ({ name: u.first, isTester: u.role === "tester" })));
console.log(["a", "b"].map((item, index) => `${index}:${item}`));

⌨️ Terminal

node map.js

🖥️ Output

[ 118, 295, 94.39999999999999 ] [ 100, 250, 80 ]
[ 'Asha Rao', 'Ravi Kumar' ]
[ { name: 'Asha', isTester: true }, { name: 'Ravi', isTester: false } ]
[ '0:a', '1:b' ]

The callback receives three arguments: (item, index, array). Most of the time you only need the item.

⚠️ Watch out: Use map only when you need the new array. If you just want to do something for each item (log it, click it), use forEach or for...of. A map whose result is ignored confuses readers.


🔎 filter: Keep Matching Items

Definition: arr.filter(callback) returns a new array with only the items for which the callback returned a truthy value. The result can be shorter, or empty.

📄 filter.js

const results = [
  { test: "login", status: "passed", ms: 820 },
  { test: "search", status: "failed", ms: 1430 },
  { test: "cart", status: "passed", ms: 2610 },
  { test: "refund", status: "skipped", ms: 0 },
];

const failed = results.filter((r) => r.status === "failed");
const slow = results.filter((r) => r.ms > 2000);
const ran = results.filter((r) => r.status !== "skipped");

console.log(failed.map((r) => r.test));
console.log(slow.map((r) => r.test));
console.log(ran.length, "of", results.length, "ran");

console.log([0, "", "QA", null, 7, undefined].filter(Boolean));   // remove falsy values

⌨️ Terminal

node filter.js

🖥️ Output

[ 'search' ]
[ 'cart' ]
3 of 4 ran
[ 'QA', 7 ]

filter(Boolean) is a handy idiom: Boolean is a function that returns false for falsy values, so they are removed.


🧮 reduce: Combine Items into One Value

Definition: arr.reduce(callback, initialValue) walks through the array and builds up a single result, called the accumulator. The callback receives (accumulator, item, index, array) and returns the new accumulator.

📄 reduce.js

const cart = [
  { item: "Pen", price: 10, qty: 3 },
  { item: "Notebook", price: 45, qty: 2 },
  { item: "Lamp", price: 899, qty: 1 },
];

const total = cart.reduce((sum, line) => sum + line.price * line.qty, 0);
console.log("total:", total);

const itemCount = cart.reduce((count, line) => count + line.qty, 0);
console.log("items:", itemCount);

const mostExpensive = cart.reduce((best, line) => (line.price > best.price ? line : best));
console.log("most expensive:", mostExpensive.item);

⌨️ Terminal

node reduce.js

🖥️ Output

total: 1019
items: 6
most expensive: Lamp

Step by step for the total: the accumulator starts at 0, then becomes 0 + 30 = 30, then 30 + 90 = 120, then 120 + 899 = 1019.

⚠️ Watch out: Always pass an initial value (the 0 above) unless you are sure the array is never empty. [].reduce((a, b) => a + b) throws TypeError: Reduce of empty array with no initial value.

📄 reduce-empty.js

const noResults = [];
console.log(noResults.reduce((sum, n) => sum + n, 0));   // safe: 0
console.log(noResults.reduce((sum, n) => sum + n));      // throws

⌨️ Terminal

node reduce-empty.js

🖥️ Output

0
/home/you/js-course/reduce-empty.js:3
console.log(noResults.reduce((sum, n) => sum + n));      // throws
                      ^

TypeError: Reduce of empty array with no initial value
    at Array.reduce (<anonymous>)
    at Object.<anonymous> (/home/you/js-course/reduce-empty.js:3:23)

Node.js v26.13.0

reduce can build any shape of result, such as an object that counts occurrences:

📄 count.js

const statuses = ["passed", "failed", "passed", "skipped", "passed"];
const counts = statuses.reduce((acc, s) => {
  acc[s] = (acc[s] ?? 0) + 1;
  return acc;
}, {});
console.log(counts);

⌨️ Terminal

node count.js

🖥️ Output

{ passed: 3, failed: 1, skipped: 1 }

🎯 find, findLast, findIndex, some and every

These methods search with a callback and stop early once the answer is known:

MethodReturnsIf nothing matches
find(fn)First matching itemundefined
findLast(fn)Last matching item (ES2023)undefined
findIndex(fn) / findLastIndex(fn)Index of the match-1
some(fn)true if at least one item matchesfalse
every(fn)true if all items matchtrue for an empty array

📄 search.js

const runs = [
  { id: 1, status: "passed", ms: 900 },
  { id: 2, status: "failed", ms: 1500 },
  { id: 3, status: "failed", ms: 700 },
];

console.log(runs.find((r) => r.status === "failed")?.id);
console.log(runs.findLast((r) => r.status === "failed")?.id);
console.log(runs.findIndex((r) => r.ms > 1000));
console.log(runs.find((r) => r.status === "skipped"));
console.log(runs.some((r) => r.status === "failed"));
console.log(runs.every((r) => r.ms < 2000));
console.log([].every((r) => r.ok), [].some((r) => r.ok));   // empty-array results

⌨️ Terminal

node search.js

🖥️ Output

2
3
1
undefined
true
true
true false

💡 Tip: [].every(...) is true (“no item breaks the rule”). A test that asserts “every row is valid” passes on an empty table, so also assert the table is not empty.


⛓️ Chaining Methods into a Pipeline

Because map and filter return arrays, you can chain them. Read the chain from top to bottom like a recipe:

📄 chain.js

const orders = [
  { id: 101, customer: "Asha", total: 1299, status: "delivered" },
  { id: 102, customer: "Ravi", total: 349, status: "cancelled" },
  { id: 103, customer: "Meera", total: 2499, status: "delivered" },
  { id: 104, customer: "Asha", total: 899, status: "delivered" },
];

const asha = orders
  .filter((o) => o.status === "delivered")
  .filter((o) => o.customer === "Asha")
  .map((o) => o.total)
  .reduce((sum, t) => sum + t, 0);

console.log("Asha delivered total:", asha);

const report = orders
  .filter((o) => o.total > 500)
  .toSorted((a, b) => b.total - a.total)
  .map((o) => `#${o.id} ${o.customer.padEnd(6)} ₹${o.total}`)
  .join("\n");
console.log(report);

⌨️ Terminal

node chain.js

🖥️ Output

Asha delivered total: 2198
#103 Meera  ₹2499
#101 Asha   ₹1299
#104 Asha   ₹899

💡 Tip: Put filter before map where possible, so later steps process fewer items. Give long chains intermediate variables if they stop being readable.


🗂️ Grouping: reduce and Object.groupBy

Grouping items by a key, such as test results by status, is a very common task. ES2024 added Object.groupBy(array, fn), which does it in one call (Node.js 21+):

📄 group.js

const results = [
  { test: "login", status: "passed" },
  { test: "search", status: "failed" },
  { test: "cart", status: "passed" },
  { test: "refund", status: "skipped" },
];

const grouped = Object.groupBy(results, (r) => r.status);
console.log(Object.keys(grouped));
console.log(grouped.passed.map((r) => r.test));

// The same with reduce (works in older environments)
const grouped2 = results.reduce((acc, r) => {
  (acc[r.status] ??= []).push(r.test);
  return acc;
}, {});
console.log(grouped2);

⌨️ Terminal

node group.js

🖥️ Output

[ 'passed', 'failed', 'skipped' ]
[ 'login', 'cart' ]
{
  passed: [ 'login', 'cart' ],
  failed: [ 'search' ],
  skipped: [ 'refund' ]
}

Map.groupBy works the same way but returns a Map, which allows keys that are not strings.


⚠️ Common Mistakes

Forgetting to return in a block body

📄 no-return.js

const prices = [10, 20];
console.log(prices.map((p) => { p * 2; }));      // block without return
console.log(prices.map((p) => p * 2));          // expression body returns

⌨️ Terminal

node no-return.js

🖥️ Output

[ undefined, undefined ]
[ 20, 40 ]

Using map for side effects or filter to change items

filter decides which items to keep; it does not change them. Returning a modified item from a filter callback just counts as “truthy”. Use map to change items.

Mutating objects inside map

📄 mutate-in-map.js

const users = [{ name: "asha" }];
const upper = users.map((u) => { u.name = u.name.toUpperCase(); return u; });   // changes the original!
console.log(users[0].name);

const users2 = [{ name: "asha" }];
const upper2 = users2.map((u) => ({ ...u, name: u.name.toUpperCase() }));       // new objects
console.log(users2[0].name, upper2[0].name);

⌨️ Terminal

node mutate-in-map.js

🖥️ Output

ASHA
asha ASHA

async callbacks

arr.map(async (x) => ...) returns an array of promises, not results, and forEach ignores them completely. You will learn to combine them with Promise.all in Module 10.


🧪 Tester Scenario: Summarise a Test Report

This example turns raw results (the kind a JSON reporter produces) into a summary using only the methods from this lesson:

📄 summary.js

const report = [
  { suite: "auth", test: "login valid", status: "passed", ms: 820 },
  { suite: "auth", test: "login invalid", status: "passed", ms: 610 },
  { suite: "cart", test: "add item", status: "failed", ms: 1430, error: "Timeout 5000ms" },
  { suite: "cart", test: "remove item", status: "passed", ms: 540 },
  { suite: "pay", test: "card", status: "failed", ms: 2210, error: "Expected 200, got 500" },
  { suite: "pay", test: "upi", status: "skipped", ms: 0 },
];

const executed = report.filter((r) => r.status !== "skipped");
const passed = executed.filter((r) => r.status === "passed").length;
const durationMs = report.reduce((sum, r) => sum + r.ms, 0);
const passRate = ((passed / executed.length) * 100).toFixed(1);

console.log(`Executed ${executed.length}/${report.length}, passed ${passed}, pass rate ${passRate}%, total ${(durationMs / 1000).toFixed(1)}s`);
console.log("all suites have a test:", ["auth", "cart", "pay"].every((s) => report.some((r) => r.suite === s)));

const failuresBySuite = Object.groupBy(report.filter((r) => r.status === "failed"), (r) => r.suite);
for (const [suite, tests] of Object.entries(failuresBySuite)) {
  console.log(`${suite}: ${tests.map((t) => `${t.test} (${t.error})`).join("; ")}`);
}
console.log("slowest:", report.reduce((a, b) => (b.ms > a.ms ? b : a)).test);

⌨️ Terminal

node summary.js

🖥️ Output

Executed 5/6, passed 3, pass rate 60.0%, total 5.6s
all suites have a test: true
cart: add item (Timeout 5000ms)
pay: card (Expected 200, got 500)
slowest: card

📝 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. Use map to convert ["login", "search", "cart"] into ["LOGIN.spec.js", "SEARCH.spec.js", "CART.spec.js"].

Show answer

📄 practice1.js

const names = ["login", "search", "cart"];
console.log(names.map((n) => `${n.toUpperCase()}.spec.js`));

🖥️ Output

[ 'LOGIN.spec.js', 'SEARCH.spec.js', 'CART.spec.js' ]

Q2. Use filter to keep only valid emails (containing @ and a dot after it) from ["a@b.com", "bad", "x@y", "qa@sqatools.in"].

Show answer

📄 practice2.js

const emails = ["a@b.com", "bad", "x@y", "qa@sqatools.in"];
const valid = emails.filter((e) => e.includes("@") && e.slice(e.indexOf("@")).includes("."));
console.log(valid);

🖥️ Output

[ 'a@b.com', 'qa@sqatools.in' ]

Q3. Use reduce to find the average of [320, 410, 1290, 250, 730] response times.

Show answer

📄 practice3.js

const times = [320, 410, 1290, 250, 730];
const avg = times.reduce((sum, t) => sum + t, 0) / times.length;
console.log(avg);

🖥️ Output

600

Q4. Check with some whether any product is out of stock, and with every whether all prices are positive, for [{ p: 10, stock: 5 }, { p: 25, stock: 0 }].

Show answer

📄 practice4.js

const products = [{ p: 10, stock: 5 }, { p: 25, stock: 0 }];
console.log(products.some((x) => x.stock === 0), products.every((x) => x.p > 0));

🖥️ Output

true true

Q5. Use reduce to turn [["env", "qa"], ["browser", "firefox"]] into the object { env: "qa", browser: "firefox" }. Then do the same with Object.fromEntries.

Show answer

📄 practice5.js

const pairs = [["env", "qa"], ["browser", "firefox"]];
const viaReduce = pairs.reduce((obj, [k, v]) => ({ ...obj, [k]: v }), {});
console.log(viaReduce, Object.fromEntries(pairs));

🖥️ Output

{ env: 'qa', browser: 'firefox' } { env: 'qa', browser: 'firefox' }

Q6. From the list of orders below, print the IDs of delivered orders over ₹1000, sorted by total from high to low.

const orders = [
  { id: 1, total: 1500, status: "delivered" },
  { id: 2, total: 800, status: "delivered" },
  { id: 3, total: 3200, status: "delivered" },
  { id: 4, total: 5000, status: "cancelled" },
];
Show answer

📄 practice6.js

const orders = [
  { id: 1, total: 1500, status: "delivered" },
  { id: 2, total: 800, status: "delivered" },
  { id: 3, total: 3200, status: "delivered" },
  { id: 4, total: 5000, status: "cancelled" },
];
const ids = orders
  .filter((o) => o.status === "delivered" && o.total > 1000)
  .toSorted((a, b) => b.total - a.total)
  .map((o) => o.id);
console.log(ids);

🖥️ Output

[ 3, 1 ]

🧠 MCQ Quiz: map, filter and reduce

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 map return?
  2. What does [1, 2, 3, 4].filter((n) => n % 2 === 0) return?
  3. What is [1, 2, 3].reduce((a, b) => a + b, 10)?
  4. What happens with [].reduce((a, b) => a + b)?
  5. What does find return when nothing matches?
  6. What is [].every((x) => x > 0)?
  7. What does [1, 2].map((n) => { n * 2 }) return?
  8. Which method should you use to check whether at least one item matches?
  9. What does Object.groupBy(items, (i) => i.type) return?
  10. What does [0, "a", "", 5].filter(Boolean) return?

💼 Interview Questions and Answers

Q1. Explain map, filter and reduce in one sentence each.

  • map transforms every element and returns a new array of the same length.
  • filter returns a new array containing only the elements for which the callback returns truthy.
  • reduce combines all elements into a single value (number, object, array) by repeatedly applying a callback to an accumulator.

None of them mutate the original array (unless the callback mutates the objects inside it).

Q2. What is the difference between map and forEach?

map returns a new array built from the callback’s return values, so it is for transforming data and can be chained. forEach returns undefined and is only for side effects such as logging. Neither can be stopped early, and neither waits for async callbacks.

Q3. Implement map and filter using reduce.

📄 implement.js

const myMap = (arr, fn) => arr.reduce((acc, x, i) => [...acc, fn(x, i)], []);
const myFilter = (arr, fn) => arr.reduce((acc, x, i) => (fn(x, i) ? [...acc, x] : acc), []);

console.log(myMap([1, 2, 3], (n) => n * 10));
console.log(myFilter([1, 2, 3, 4], (n) => n > 2));

⌨️ Terminal

node implement.js

🖥️ Output

[ 10, 20, 30 ]
[ 3, 4 ]

It shows that reduce is the most general of the three. In real code use the built-in methods; they are clearer and faster.

Q4. A test asserts that every row of a results table has a valid price, and it passes even when the table fails to load. Why?

If no rows are found, the array is empty, and [].every(fn) is true. The assertion is vacuously satisfied. Assert the row count first (expect(rows.length).toBeGreaterThan(0), or toHaveCount in Playwright), then check every row.


❓ Frequently Asked Questions

🤔 Do map, filter and reduce change the original array?

No, they return new values. But if the callback changes properties of objects inside the array, those objects are changed, because they are shared references.

🤔 When should I use a for loop instead of map/filter/reduce?

When you need to stop early (use for...of with break, or find/some), when you need await step by step, or when a reduce becomes hard to read.

🤔 Is reduce hard to read?

It can be. For sums and counts it is fine; for complex shapes, a plain loop or Object.groupBy may be clearer.

🤔 Are these methods slow?

For typical test data (hundreds or thousands of items) the difference is negligible. Choose clarity first.


🏁 Summary

  • map transforms every item into a new array of the same length.
  • filter keeps the items that pass a test; filter(Boolean) removes falsy values.
  • reduce combines items into one value; always pass an initial value.
  • find, findLast, findIndex, some and every search and stop early; every is true for an empty array.
  • Chain methods into readable pipelines and use Object.groupBy to group results.

Next, continue with Lesson 31: Destructuring and Spread.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in