Objects
📖 Concept
Objects are collections of key-value pairs. They are the fundamental building block of JavaScript — almost everything is an object (arrays, functions, dates, regex, etc.).
Creating objects: Object literals {}, new Object(), Object.create()
Accessing properties: Dot notation obj.key or bracket notation obj["key"]
The this keyword: Inside a method, this refers to the object the method belongs to (in most cases).
Key methods: Object.keys(), Object.values(), Object.entries(), Object.assign(), Object.freeze(), Object.seal(), Object.hasOwn()
🏠 Real-world analogy: An object is like a filing cabinet. Each drawer has a label (key) and contains something (value). You can add drawers, remove them, or look inside them.
💻 Code Example
1// Creating objects2const person = {3 name: "Alice",4 age: 25,5 hobbies: ["reading", "coding"],6 address: {7 city: "New York",8 zip: "10001"9 },10 // Method shorthand11 greet() {12 return `Hi, I'm ${this.name}`;13 }14};1516// Accessing properties17console.log(person.name); // "Alice"18console.log(person["age"]); // 2519const key = "hobbies";20console.log(person[key]); // ["reading", "coding"]2122// Dynamic keys23const field = "email";24const userData = {25 [field]: "alice@example.com", // Computed property name26 [`get${field.charAt(0).toUpperCase() + field.slice(1)}`]() {27 return this[field];28 }29};3031// Object methods32console.log(Object.keys(person)); // ["name", "age", "hobbies", "address", "greet"]33console.log(Object.values(person)); // ["Alice", 25, [...], {...}, fn]34console.log(Object.entries(person)); // [["name","Alice"], ["age",25], ...]3536// Shallow copy37const copy = { ...person }; // spread38const copy2 = Object.assign({}, person);3940// Freeze vs Seal41const config = Object.freeze({ api: "/v1", debug: false });42// config.api = "/v2"; // ❌ Silently fails (or throws in strict mode)4344const settings = Object.seal({ theme: "dark" });45settings.theme = "light"; // ✅ Can modify existing46// settings.lang = "en"; // ❌ Can't add new properties4748// Check property existence49console.log("name" in person); // true50console.log(person.hasOwnProperty("name")); // true51console.log(Object.hasOwn(person, "name")); // true (modern)5253// Iterating54for (const [key, value] of Object.entries(person)) {55 console.log(`${key}: ${value}`);56}
🏋️ Practice Exercise
Mini Exercise:
- Create a "bank account" object with deposit and withdraw methods using
this - Write a function to deep clone an object (handle nested objects and arrays)
- Write a function that merges two objects, with the second overriding the first
- Create an object with a computed property name based on a variable
⚠️ Common Mistakes
thisin arrow functions doesn't refer to the object — arrow functions inheritthisfrom the enclosing scopeShallow copy with spread
{...obj}doesn't deep clone — nested objects are still referencesUsing
delete obj.propis slow — set toundefinedif performance matters, or use destructuring to excludeChecking property existence with
if (obj.prop)fails when the value is falsy — useinoperator orObject.hasOwn()Object.freeze()is shallow — nested objects can still be modified
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for Objects. Login to unlock this feature.