JavaScript Objects: Properties, Methods, Nested Objects and Copying
Objects are how JavaScript represents things: a user, an order, an API response, a page configuration, a test result. Almost every value you work with in testing, from response.json() to Playwright’s config file, is an object. In this lesson you will learn how to create objects, read and change their properties, add methods, work with nested data, loop through properties, and copy and compare objects without the reference bugs that catch so many beginners.
📖 What You’ll Learn: what an object is, object literals, reading properties with dot and bracket notation, adding, updating and deleting properties, shorthand properties and computed keys, methods, nested objects, checking whether a property exists, looping over keys and values, objects as references, copying and comparing objects, and objects versus arrays.
🧱 What Is an Object?
Definition: an object is a collection of properties, where each property is a key (a name) paired with a value. Values can be anything: strings, numbers, arrays, functions, even other objects. The usual way to create one is an object literal in curly braces.
📄 object.js
const user = {
id: 7,
name: "Asha Rao",
email: "asha@sqatools.in",
active: true,
roles: ["tester", "admin"],
};
console.log(user);
console.log(typeof user, Array.isArray(user));
console.log(Object.keys(user).length, "properties");
⌨️ Terminal
node object.js
🖥️ Output
{
id: 7,
name: 'Asha Rao',
email: 'asha@sqatools.in',
active: true,
roles: [ 'tester', 'admin' ]
}
object false
5 properties
- Each property is written
key: value, separated by commas. A trailing comma is allowed. - Keys are strings (or symbols). Quotes are optional when the key is a valid identifier:
nameand"name"are the same key. - Use objects for one record with named fields, and arrays for an ordered list of similar items.
🔑 Reading Properties: Dot vs Bracket Notation
📄 access.js
const order = { id: 501, "order-status": "shipped", total: 1299, 2026: "year key" };
console.log(order.id); // dot notation
console.log(order["total"]); // bracket notation with a string
console.log(order["order-status"]); // needed: the key contains a dash
console.log(order[2026]); // numeric keys are converted to strings
const field = "total";
console.log(order[field]); // needed: the key is in a variable
console.log(order.field); // looks for a key literally called "field"
console.log(order.discount); // missing property: undefined
⌨️ Terminal
node access.js
🖥️ Output
501
1299
shipped
year key
1299
undefined
undefined
| Use | When |
|---|---|
obj.key | The key is a fixed, valid identifier (most of the time) |
obj["some-key"] | The key has spaces, dashes or starts with a digit |
obj[variable] | The key is computed or stored in a variable |
⚠️ Watch out: Reading a missing property gives undefined, but reading a property of that undefined throws TypeError: Cannot read properties of undefined. Use optional chaining (order.customer?.name) for data that may be missing; see the Optional Chaining lesson.
✏️ Adding, Updating and Deleting Properties
📄 modify.js
const config = { browser: "chromium" };
config.headless = true; // add
config["retries"] = 2; // add with brackets
config.browser = "firefox"; // update
delete config.retries; // remove
console.log(config);
const settings = Object.freeze({ env: "qa" });
settings.env = "prod"; // ignored (throws in strict mode)
console.log(settings.env);
⌨️ Terminal
node modify.js
🖥️ Output
{ browser: 'firefox', headless: true }
qa
Objects declared with const can still be changed, because const only prevents assigning a new object to the variable. Object.freeze (next lesson) makes the object itself read-only.
✂️ Shorthand Properties and Computed Keys
When a variable has the same name as the key, you can write it once (shorthand property). Square brackets around a key let you compute its name from an expression:
📄 shorthand.js
const name = "Asha";
const role = "tester";
const longForm = { name: name, role: role };
const shortForm = { name, role }; // shorthand
console.log(longForm, shortForm);
const env = "qa";
const urls = {
[`${env}URL`]: "https://qa.example.com", // computed key
[`${env}_timeout`]: 15000,
};
console.log(urls);
function pick(obj, key) {
return { [key]: obj[key] };
}
console.log(pick({ a: 1, b: 2 }, "b"));
⌨️ Terminal
node shorthand.js
🖥️ Output
{ name: 'Asha', role: 'tester' } { name: 'Asha', role: 'tester' }
{ qaURL: 'https://qa.example.com', qa_timeout: 15000 }
{ b: 2 }
🛠️ Methods: Functions Inside Objects
Definition: a method is a property whose value is a function. Inside a method, this refers to the object the method was called on (see the this lesson).
📄 methods.js
const cart = {
items: [],
add(name, price, qty = 1) { // method shorthand
this.items.push({ name, price, qty });
return this; // return this to allow chaining
},
total() {
return this.items.reduce((sum, i) => sum + i.price * i.qty, 0);
},
summary() {
return `${this.items.length} lines, total ₹${this.total()}`;
},
};
cart.add("Pen", 10, 3).add("Notebook", 45);
console.log(cart.summary());
console.log(typeof cart.add);
⌨️ Terminal
node methods.js
🖥️ Output
2 lines, total ₹75
function
Returning this from a method allows chaining calls, a style you will meet in builders and in page-object methods.
🪆 Nested Objects
Real data is nested: an order has a customer, the customer has an address, the order has a list of items. Chain dots and brackets to reach inner values:
📄 nested.js
const order = {
id: 501,
customer: {
name: "Asha",
address: { city: "Pune", pin: "411001" },
},
items: [
{ sku: "PEN-1", price: 10, qty: 3 },
{ sku: "BOOK-9", price: 45, qty: 1 },
],
};
console.log(order.customer.address.city);
console.log(order.items[1].sku);
console.log(order.items.length);
console.log(order.customer.phone?.mobile ?? "no phone");
order.customer.address.city = "Mumbai"; // change a nested value
console.log(order.customer.address);
⌨️ Terminal
node nested.js
🖥️ Output
Pune
BOOK-9
2
no phone
{ city: 'Mumbai', pin: '411001' }
💡 Tip: When an API response is deeply nested, destructure the parts you need once (const { customer: { address } } = order;) instead of repeating long chains in every assertion.
🔍 Checking Whether a Property Exists
A property can exist and still hold undefined, so “is the value undefined?” and “does the key exist?” are different questions:
📄 exists.js
const user = { name: "Asha", nickname: undefined };
console.log(user.nickname === undefined, user.age === undefined); // both true
console.log("nickname" in user, "age" in user); // key exists?
console.log(Object.hasOwn(user, "nickname"), Object.hasOwn(user, "toString"));
console.log("toString" in user); // in also sees inherited keys
⌨️ Terminal
node exists.js
🖥️ Output
true true
true false
true false
true
| Check | True when |
|---|---|
obj.key !== undefined | The key exists with a value other than undefined |
"key" in obj | The key exists on the object or its prototype chain |
Object.hasOwn(obj, "key") | The key exists on the object itself (ES2022) |
🔁 Looping Through an Object
📄 loop.js
const scores = { asha: 91, ravi: 78, meera: 85 };
for (const name in scores) {
console.log(name, scores[name]);
}
console.log(Object.keys(scores));
console.log(Object.values(scores));
console.log(Object.entries(scores));
for (const [name, score] of Object.entries(scores)) {
console.log(`${name.padEnd(6)} ${score >= 80 ? "pass" : "fail"}`);
}
const average = Object.values(scores).reduce((a, b) => a + b, 0) / Object.keys(scores).length;
console.log("average", average.toFixed(1));
⌨️ Terminal
node loop.js
🖥️ Output
asha 91
ravi 78
meera 85
[ 'asha', 'ravi', 'meera' ]
[ 91, 78, 85 ]
[ [ 'asha', 91 ], [ 'ravi', 78 ], [ 'meera', 85 ] ]
asha pass
ravi fail
meera pass
average 84.7
Object.entries combined with for...of and destructuring is the most common way to walk an object. String keys come back in insertion order (integer-like keys come first, in ascending order).
🔗 Objects Are References: Copying and Comparing
Assigning an object to another variable copies the reference, so both names point to the same object. Comparing two objects with === checks whether they are the same object, not whether they have the same contents.
📄 reference.js
const base = { env: "qa", retries: 0 };
const alias = base;
alias.retries = 3;
console.log(base.retries, alias === base);
const copy = { ...base }; // shallow copy
copy.retries = 5;
console.log(base.retries, copy.retries);
console.log({ id: 1 } === { id: 1 }); // different objects
const { isDeepStrictEqual } = require("node:util");
console.log(isDeepStrictEqual({ id: 1, tags: ["a"] }, { id: 1, tags: ["a"] }));
⌨️ Terminal
node reference.js
🖥️ Output
3 true
3 5
false
true
Spread and Object.assign make shallow copies: nested objects are still shared. The Destructuring and Spread lesson and the JSON lesson cover deep copies with structuredClone.
🧪 Tester Scenario: Build and Validate an API Payload
API tests constantly build request bodies and check response objects. This example builds a payload with methods and validates a response against expected fields:
📄 payload.js
const payloadBuilder = {
data: { name: "Test User", role: "tester", active: true },
with(key, value) {
this.data = { ...this.data, [key]: value };
return this;
},
build() {
return { ...this.data, createdAt: "2026-11-23T10:00:00Z" };
},
};
const payload = payloadBuilder.with("role", "admin").with("email", "admin@sqatools.in").build();
console.log(payload);
const response = { id: 9001, ...payload, active: "true" }; // simulated server response
const expected = { role: "admin", email: "admin@sqatools.in", active: true };
for (const [key, value] of Object.entries(expected)) {
const ok = Object.is(response[key], value);
console.log(`${ok ? "PASS" : "FAIL"} ${key}: expected ${JSON.stringify(value)}, got ${JSON.stringify(response[key])}`);
}
console.log("has id:", Object.hasOwn(response, "id") && typeof response.id === "number");
⌨️ Terminal
node payload.js
🖥️ Output
{
name: 'Test User',
role: 'admin',
active: true,
email: 'admin@sqatools.in',
createdAt: '2026-11-23T10:00:00Z'
}
PASS role: expected "admin", got "admin"
PASS email: expected "admin@sqatools.in", got "admin@sqatools.in"
FAIL active: expected true, got "true"
has id: true
The check catches a classic API bug: active came back as the string "true" instead of the boolean true. Playwright’s expect(body).toMatchObject(expected) does this comparison for you.
📝 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 book object with title, author, year and tags (an array). Print the title and the number of tags.
Show answer
📄 practice1.js
const book = { title: "Clean Code", author: "Robert C. Martin", year: 2008, tags: ["craft", "quality"] };
console.log(book.title, book.tags.length);🖥️ Output
Clean Code 2Q2. Given const field = "price", read that property from { name: "Lamp", price: 899 }, then add a "discount-code" property with the value "SAVE10".
Show answer
📄 practice2.js
const product = { name: "Lamp", price: 899 };
const field = "price";
console.log(product[field]);
product["discount-code"] = "SAVE10";
console.log(product);🖥️ Output
899
{ name: 'Lamp', price: 899, 'discount-code': 'SAVE10' }Q3. Write a counter object with a count property and methods increment(), reset() and value().
Show answer
📄 practice3.js
const counter = {
count: 0,
increment() { this.count++; return this; },
reset() { this.count = 0; return this; },
value() { return this.count; },
};
counter.increment().increment().increment();
console.log(counter.value());
console.log(counter.reset().value());🖥️ Output
3
0Q4. Count how many properties of { a: 1, b: null, c: 0, d: "x", e: undefined } have a value that is not null or undefined.
Show answer
📄 practice4.js
const obj = { a: 1, b: null, c: 0, d: "x", e: undefined };
const count = Object.values(obj).filter((v) => v != null).length;
console.log(count);🖥️ Output
3Q5. Print every key: value pair of { env: "qa", browser: "firefox", workers: 4 } in the format ENV=qa.
Show answer
📄 practice5.js
const config = { env: "qa", browser: "firefox", workers: 4 };
for (const [key, value] of Object.entries(config)) {
console.log(`${key.toUpperCase()}=${value}`);
}🖥️ Output
ENV=qa
BROWSER=firefox
WORKERS=4Q6. Make a copy of { name: "Asha", settings: { theme: "dark" } }, change the copy’s theme to "light", and show that the original still says "dark".
Show answer
📄 practice6.js
const original = { name: "Asha", settings: { theme: "dark" } };
const copy = { ...original, settings: { ...original.settings } };
copy.settings.theme = "light";
console.log(original.settings.theme, copy.settings.theme);🖥️ Output
dark lightSpreading only the outer object would share settings, so the nested object must be spread too (or use structuredClone).
🧠 MCQ Quiz: Objects
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- How do you read a property whose name is stored in a variable
key?Answer: obj[key]. obj.key looks for a property literally named “key”. - What does reading a missing property return?Answer: undefined. Only reading a property of undefined throws.
- Which is required for the key
"order-id"?Answer: Bracket notation: obj[“order-id”]. obj.order-id would be parsed as obj.order minus id. - What does
{ name }mean when a variablenameexists?Answer: { name: name } (shorthand property). Shorthand properties use the variable’s name as the key. - What does
delete obj.keydo?Answer: Removes the property from the object. After delete, “key” in obj is false. - What is
{ a: 1 } === { a: 1 }?Answer: false. Objects are compared by reference. - Which check returns true only for the object’s own property, not inherited ones?Answer: Object.hasOwn(obj, “key”). in also finds inherited properties such as toString.
- What does
Object.entries({ a: 1, b: 2 })return?Answer: [[“a”, 1], [“b”, 2]]. Each entry is a [key, value] pair. - Inside a method called as
cart.total(), what isthis?Answer: cart. this is the object before the dot. - Why can you change properties of an object declared with const?Answer: const only prevents reassigning the variable. Use Object.freeze to prevent changes.
💼 Interview Questions and Answers
Q1. What is the difference between dot notation and bracket notation?
Dot notation (obj.name) is shorter and used when the key is a fixed, valid identifier. Bracket notation (obj["name"]) accepts any string or expression, so it is required for keys with spaces or dashes, keys starting with digits, and dynamic keys stored in variables. Both read the same property.
Q2. How do you check if an object has a property?
Object.hasOwn(obj, key) (or the older obj.hasOwnProperty(key)) checks own properties only. key in obj also checks the prototype chain. Comparing obj[key] !== undefined fails when the property exists but holds undefined. For API assertions, hasOwn is the precise check.
Q3. How do you loop through an object’s properties?
Use Object.keys, Object.values or Object.entries with for...of, for example for (const [key, value] of Object.entries(obj)). for...in also works but includes inherited enumerable properties. Plain objects are not iterable, so for (const x of obj) throws a TypeError.
Q4. Predict the output.
📄 predict.js
const a = { x: 1 };
const b = a;
const c = { ...a };
b.x = 2;
c.x = 3;
console.log(a.x, b.x, c.x, a === b, a === c);
⌨️ Terminal
node predict.js
🖥️ Output
2 2 3 true false
b is the same object as a, so setting b.x changes a.x to 2. c is a separate copy, so its change to 3 does not affect a.
❓ Frequently Asked Questions
🤔 How do I create an empty object?
Use {}. new Object() works too but is never needed. Object.create(null) creates an object with no prototype, useful for pure dictionaries.
🤔 Can object keys be numbers?
Keys are always strings or symbols. A numeric key such as obj[1] is converted to the string “1”. Use a Map if you need keys of any type.
🤔 How do I get the number of properties in an object?
Use Object.keys(obj).length. Objects have no length property.
🤔 What is the difference between an object and JSON?
An object is a value in your program. JSON is a text format for data. JSON.stringify converts an object to JSON text and JSON.parse converts JSON text back to an object.
🏁 Summary
- Objects store named properties: create them with
{ key: value }literals. - Use dot notation for fixed keys and bracket notation for dynamic or unusual keys.
- Add, update and delete properties freely; methods are functions stored as properties and use
this. - Check keys with
Object.hasOwnorin, and loop withObject.entriesandfor...of. - Objects are references: copy with spread (shallow) or
structuredClone(deep), and compare contents with deep equality.
Next, continue with Lesson 34: Object Methods. For extra practice, solve the JavaScript object practice programs.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in