A JavaScript object is an unordered collection of key-value pairs that models real-world entities such as users, products, or configuration records. Keys are strings (or Symbols), and values can be any data type, including arrays and functions.
You can read or set object properties in two ways:
user.name): Clean and readable when the property name is a fixed valid identifier.user[key]): Required when the key comes from a variable or contains spaces or hyphens like "first-name".Use delete obj.prop to remove a key completely, and use Object.keys(), Object.values(), or Object.entries() to loop over properties cleanly.
ES6 added property shorthand, concise method syntax, computed keys, and ES2020 added optional chaining (?.) to prevent crashes on missing nested fields.
const field = "role";
const name = "Nadia";
const member = {
name, // Shorthand for name: name
[field]: "editor",
profile: { city: "Dhaka" },
describe() {
return `${this.name} (${this.role})`;
},
};
console.log(member.describe());
console.log("City:", member.profile?.city);
console.log("Missing phone:", member.contact?.phone ?? "Not provided");
undefined: Writing user.address.zip throws a TypeError if address is missing. Use user.address?.zip instead.Object.assign(target, source) by mistake: Passing an existing object as the first argument mutates it. Use { ...objA, ...objB } to create a fresh object.this: Arrow functions do not bind their own this, so this.name will be undefined.Use the modern static method Object.hasOwn(obj, "key"). It is safer than obj.hasOwnProperty("key") because it works even on null-prototype objects.
Use object spread syntax: const merged = { ...defaults, ...overrides };. Properties in overrides replace matching keys from defaults.
Keys in plain objects are converted to strings automatically, so obj[1] and obj["1"] refer to the exact same property.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.