Last 30 Days
No notifications
Objects are JavaScript's universal data container — keyed collections of values. Almost everything in JS is an object (arrays, functions, dates, regex). This page covers literal syntax, the dot vs bracket access debate, modern shortcuts (shorthand props, computed keys, destructuring, spread), and the deep vs shallow copy trap that bites everyone once.
# Objects
const user = {
name: "Alice",
age: 25,
"favorite color": "blue", // quoted key — needed for spaces / special chars
isAdmin: true,
};const empty = {};
const fromCtor = new Object(); // rarely used
user.name; // dot — known, valid identifier key
user["favorite color"]; // bracket — keys with spaces / special chars
const key = "age";
user[key]; // bracket — DYNAMIC keys (variable name)user.email = "a@x.com"; // add
user.age = 26; // update
delete user.isAdmin; // remove (rarely needed)const name = "Bob";
const age = 30;
const u = { name, age }; // same as { name: name, age: age }[expr]const field = "score";
const update = { [field]: 99, [${field}_max]: 100 };
// { score: 99, score_max: 100 }const obj = {
greet(name) { return hi ${name}; }, // = greet: function(name) {…}
};const { name, age } = user; // basic
const { name: userName } = user; // rename
const { country = "IN" } = user; // default value
const { address: { city } = {} } = user; // nested + default// In function params
function greet({ name, age = 18 }) { … }
greet({ name: "Alice" });
const copy = { ...user }; // shallow copy
const merged = { ...defaults, ...overrides }; // later wins
const next = { ...user, age: 27 }; // immutable update⚠️ Spread is SHALLOW — nested objects are still shared by reference:
const a = { profile: { city: "Delhi" } };
const b = { ...a };
b.profile.city = "Mumbai";
console.log(a.profile.city); // "Mumbai" — same nested object!// deep copy options
const deep = structuredClone(a); // ✅ modern
const json = JSON.parse(JSON.stringify(a)); // works but loses Date/Map/undefined
Object.keys(user); // ["name","age","favorite color","isAdmin"]
Object.values(user); // ["Alice", 25, "blue", true]
Object.entries(user); // [["name","Alice"], ["age",25], …]// reverse: build an object from entries
Object.fromEntries([["a", 1], ["b", 2]]); // { a: 1, b: 2 }
// iterate
for (const [k, v] of Object.entries(user)) console.log(k, v);
user?.address?.city ?? "unknown";const cfg = Object.freeze({ host: "x.com" }); // shallow immutability
cfg.host = "y.com"; // silently ignored (TypeError in strict){ a: 1 } === { a: 1 } // false — different objects
const x = { a: 1 };
const y = x;
x === y // true — same reference
For deep equality use a library (lodash.isEqual) or compare via JSON.stringify for simple data.