Introduction & Syntax
Objects · Study material
Objects are JavaScript's main data structure: a user, a product, an API response, a configuration – all are collections of key–value pairs. Nearly everything else (arrays, functions, dates) is an object too. Interviews test how objects really behave: keys are always strings (or symbols), this depends on how a method is called, spread copies only one level, Object.freeze is shallow, in also sees inherited keys, and JSON.stringify quietly drops some values. This topic covers all of it, from literals to prototypes. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.
Creating objects and reading properties
An object literal lists key: value pairs. Read a property with dot notation (obj.name) when the key is a valid identifier, and with bracket notation (obj["in-stock"], obj[variable]) when it contains special characters or is stored in a variable. Missing properties read as undefined. Properties can be added by assignment and removed with delete. A computed key [expression]: value builds the key name at creation time.
const key = "price";
const product = {
name: "Keyboard",
"in-stock": true, // keys that are not valid identifiers need quotes…
[key + "INR"]: 1499, // computed key: the expression decides the name
tags: ["usb", "wired"],
};
// …and bracket notation to read them
console.log(product.name, product["in-stock"], product.priceINR, product.color);
product.color = "black"; // add a property
delete product.tags; // remove a property
console.log(Object.keys(product));
Keyboard true 1499 undefined [ 'name', 'in-stock', 'priceINR', 'color' ]
Shorthand properties and methods
{ name } is short for { name: name }, and { grade() { … } } defines a method. Inside a method called as obj.method(), this is obj – the object before the dot. If the method is detached (const f = obj.method; f()), this is lost; see Coding Techniques.
const name = "Asha", marks = 91;
const student = {
name, marks, // shorthand for name: name, marks: marks
grade() { return this.marks >= 90 ? "A+" : "A"; }, // method: this is the object before the dot
};
console.log(student.grade());
console.log(JSON.stringify(student)); // JSON skips functions
A+
{"name":"Asha","marks":91}Keys are strings
Property keys are strings or symbols. Numbers are converted to strings (obj[1] and obj["1"] are the same property) and objects become "[object Object]" – use a Map when you need non-string keys. Integer-like keys are listed first in ascending order, then string keys in insertion order.
Looping over an object
Object.keys, Object.values and Object.entries return arrays of the object's own enumerable string keys, values and [key, value] pairs. Object.fromEntries does the reverse, which makes "entries → map/filter → fromEntries" the standard way to transform an object.
const scores = { maths: 88, physics: 79, chemistry: 91 };
console.log(Object.keys(scores).length, Object.values(scores).reduce((a, b) => a + b));
for (const [subject, m] of Object.entries(scores)) {
if (m > 80) console.log(subject);
}
// entries → transform → fromEntries: a new object with every mark raised by 5
const curved = Object.fromEntries(Object.entries(scores).map(([s, m]) => [s, m + 5]));
console.log(curved);
3 258
maths
chemistry
{ maths: 93, physics: 84, chemistry: 96 }Merging and copying
Spread ({ ...a, ...b }) and Object.assign(target, ...sources) copy own enumerable properties; when keys collide, the later source wins. Both make a shallow copy: nested objects are shared. Note that Object.assign modifies and returns its first argument. For a deep copy use structuredClone.
const defaults = { theme: "light", lang: "en", notify: { email: true } };
const user = { lang: "hi" };
const settings = { ...defaults, ...user }; // later properties win
const assigned = Object.assign({}, defaults, user); // same result, older API
settings.notify.email = false; // shallow copy: notify is shared with defaults!
console.log(settings.lang, assigned.lang, defaults.notify.email);
hi hi false
freeze, seal and preventExtensions
| Change values | Add properties | Delete properties | |
|---|---|---|---|
Object.preventExtensions | yes | no | yes |
Object.seal | yes | no | no |
Object.freeze | no | no | no |
All three are shallow. Blocked operations fail silently in normal scripts and throw a TypeError in strict mode and modules.
const frozen = Object.freeze({ a: 1 }); // no changes, no additions, no deletions
const sealed = Object.seal({ a: 1 }); // existing properties may change; none added or deleted
for (const [label, obj] of [["frozen", frozen], ["sealed", sealed]]) {
try { obj.a = 2; } catch {} // this example is a module (strict): blocked writes throw
try { obj.b = 3; } catch {}
try { delete obj.a; } catch {}
console.log(label, JSON.stringify(obj));
}
frozen {"a":1}
sealed {"a":2}Getters, setters and property descriptors
get prop() { … } runs when the property is read and set prop(v) { … } when it is assigned – useful for computed values and validation. Every property also has hidden attributes: writable, enumerable and configurable. Object.defineProperty sets them (and defaults them all to false for new properties); non-enumerable properties are skipped by Object.keys, for…in and JSON.stringify.
const account = {
_balance: 1000,
get balance() { return `₹${this._balance}`; }, // runs when the property is read
set balance(v) { // runs when it is assigned
if (v < 0) throw new RangeError("negative balance");
this._balance = v;
},
};
account.balance = 2500;
console.log(account.balance);
try { account.balance = -5; } catch (e) { console.log(e.name); }
Object.defineProperty(account, "_balance", { enumerable: false }); // hide it from keys/JSON
console.log(Object.keys(account));
₹2500 RangeError [ 'balance' ]
Prototypes
When a property is not found on an object, JavaScript looks at the object's prototype, then the prototype's prototype, and so on – the prototype chain. Object.create(proto) makes a new object with the given prototype; Object.create(null) makes one with none (a clean dictionary without toString and friends). in checks the whole chain; Object.hasOwn checks only the object itself. Classes are built on the same mechanism (see ES6 Features).
// Every object has a prototype; missing properties are looked up along the prototype chain
const animal = { speak() { return `${this.name} makes a sound`; } };
const dog = Object.create(animal); // dog's prototype is animal
dog.name = "Bruno";
console.log(dog.speak());
console.log(Object.getPrototypeOf(dog) === animal, Object.hasOwn(dog, "speak"), "speak" in dog);
Bruno makes a sound true false true
Comparing objects and JSON
=== compares references, so two objects with the same content are not equal. JSON.stringify converts objects to text: functions, symbols and undefined properties are dropped (and become null inside arrays), NaN and Infinity become null, Dates become ISO strings, and circular references throw. JSON.parse requires double-quoted keys and strings.
const order = { id: 7, items: ["pen"], placed: new Date(Date.UTC(2026, 10, 30)), note: undefined };
const json = JSON.stringify(order); // Dates become ISO strings; undefined properties are dropped
console.log(json);
const back = JSON.parse(json);
console.log(typeof back.placed, back.items[0], "note" in back);
{"id":7,"items":["pen"],"placed":"2026-11-30T00:00:00.000Z"}
string pen falseCommon mistakes
- obj.key when the key is in a variable – reads a property literally called "key"; use obj[key].
- Thinking spread or Object.assign copy deeply – nested objects stay shared.
- Detaching a method – const f = obj.method loses this; bind it or use an arrow wrapper.
- if (obj.count) to test existence – 0 and "" are falsy; use Object.hasOwn or "count" in obj.
- for…in on objects with prototypes – inherited keys appear too.
- Merging nested defaults with spread – the whole nested object is replaced.
- JSON round-trips – Dates come back as strings; Maps, functions and undefined are lost.
Key points to remember
- Keys are strings or symbols; use brackets for variables and special characters.
- this in a method is the object before the dot at call time.
- keys/values/entries list own enumerable properties; fromEntries rebuilds an object.
- Spread and Object.assign are shallow; later sources win.
- freeze > seal > preventExtensions – all shallow.
- in includes the prototype chain; Object.hasOwn does not.
- === compares references; JSON.stringify drops functions and undefined.
Frequently asked questions
Object or Map?
Use objects for records with known keys (a user, a config). Use a Map for dictionaries with dynamic or non-string keys, frequent additions and removals, or when you need the size and guaranteed insertion order.
How do I check whether a property exists?
Object.hasOwn(obj, "key") for own properties, "key" in obj to include inherited ones. Avoid relying on obj.key !== undefined, because the property may exist with the value undefined.
How do I deep-copy an object?
structuredClone(obj) handles nested objects, arrays, Dates, Maps and Sets (but not functions or class methods). JSON.parse(JSON.stringify(obj)) only works for plain JSON data.
Where can I learn more?
Read JavaScript Objects, The this Keyword and Prototypes in the JavaScript tutorial, then practise with the exercises below.