Objects — Basics
Objects are collections of key-value pairs that represent real-world entities. They're fundamental to JavaScript programming.
Creating Objects
javascript// Object literal (most common) const person = { name: "Alice", age: 30, city: "New York", isEmployed: true }; // Empty object const empty = {}; // Object constructor const user = new Object(); user.name = "Bob"; user.age = 25; // Nested objects const student = { name: "Charlie", grades: { math: 95, science: 87, english: 92 }, address: { street: "123 Main St", city: "Boston", zipCode: "02101" } };
Accessing Properties
javascriptconst car = { brand: "Toyota", model: "Camry", year: 2022, "fuel-type": "gasoline" // Property with hyphen }; // Dot notation console.log(car.brand); // "Toyota" console.log(car.year); // 2022 // Bracket notation console.log(car["model"]); // "Camry" console.log(car["fuel-type"]); // "gasoline" - required for hyphens // Dynamic property access const property = "brand"; console.log(car[property]); // "Toyota" // Non-existent property console.log(car.color); // undefined
Adding and Modifying Properties
javascriptconst product = { name: "Laptop", price: 999 }; // Add new properties product.brand = "Dell"; product["warranty"] = "2 years"; // Modify existing properties product.price = 899; product["name"] = "Gaming Laptop"; console.log(product); // { // name: "Gaming Laptop", // price: 899, // brand: "Dell", // warranty: "2 years" // } // Dynamic property names const key = "color"; const value = "silver"; product[key] = value;
Deleting Properties
javascriptconst user = { name: "John", age: 30, email: "john@example.com", password: "secret123" }; // Delete property delete user.password; console.log(user); // password property is gone // Check if property exists console.log("password" in user); // false console.log("name" in user); // true // Alternative check console.log(user.hasOwnProperty("email")); // true console.log(user.hasOwnProperty("password")); // false
Object Methods
javascriptconst calculator = { result: 0, // Method using function keyword add: function(num) { this.result += num; return this; }, // Method using shorthand syntax subtract(num) { this.result -= num; return this; }, // Arrow function (be careful with 'this') multiply: (num) => { // 'this' doesn't refer to calculator object! console.log("Arrow function this:", this); }, getValue() { return this.result; }, reset() { this.result = 0; return this; } }; // Method chaining calculator.add(10).subtract(3).add(5); console.log(calculator.getValue()); // 12
Object Iteration
javascriptconst person = { name: "Alice", age: 30, city: "New York", occupation: "Developer" }; // for...in loop (iterates over keys) for (let key in person) { console.log(`${key}: ${person[key]}`); } // Object.keys() - get array of keys const keys = Object.keys(person); console.log(keys); // ["name", "age", "city", "occupation"] // Object.values() - get array of values const values = Object.values(person); console.log(values); // ["Alice", 30, "New York", "Developer"] // Object.entries() - get array of [key, value] pairs const entries = Object.entries(person); console.log(entries); // [["name", "Alice"], ["age", 30], ["city", "New York"], ["occupation", "Developer"]] // Iterate with forEach Object.entries(person).forEach(([key, value]) => { console.log(`${key}: ${value}`); });
Copying Objects
javascriptconst original = { name: "John", age: 30, hobbies: ["reading", "gaming"] }; // Shallow copy methods const copy1 = { ...original }; // Spread operator const copy2 = Object.assign({}, original); // Object.assign // Both create shallow copies copy1.name = "Jane"; console.log(original.name); // "John" - unchanged // But nested objects are still referenced copy1.hobbies.push("cooking"); console.log(original.hobbies); // ["reading", "gaming", "cooking"] - changed! // Deep copy (simple objects only) const deepCopy = JSON.parse(JSON.stringify(original)); deepCopy.hobbies.push("swimming"); console.log(original.hobbies); // ["reading", "gaming", "cooking"] - unchanged
Object Comparison
javascriptconst obj1 = { name: "Alice", age: 30 }; const obj2 = { name: "Alice", age: 30 }; const obj3 = obj1; // Objects are compared by reference, not value console.log(obj1 === obj2); // false (different objects) console.log(obj1 === obj3); // true (same reference) // Compare object contents function objectsEqual(obj1, obj2) { const keys1 = Object.keys(obj1); const keys2 = Object.keys(obj2); if (keys1.length !== keys2.length) return false; for (let key of keys1) { if (obj1[key] !== obj2[key]) return false; } return true; } console.log(objectsEqual(obj1, obj2)); // true // Simple comparison using JSON (limited) function simpleEqual(obj1, obj2) { return JSON.stringify(obj1) === JSON.stringify(obj2); }
Practical Examples
javascript// User profile management const userProfile = { id: 1, username: "alice_dev", email: "alice@example.com", profile: { firstName: "Alice", lastName: "Johnson", bio: "Full-stack developer", avatar: "avatar.jpg" }, settings: { theme: "dark", notifications: true, language: "en" }, // Methods getFullName() { return `${this.profile.firstName} ${this.profile.lastName}`; }, updateSetting(key, value) { this.settings[key] = value; }, getDisplayInfo() { return { name: this.getFullName(), username: this.username, theme: this.settings.theme }; } }; // Shopping cart const shoppingCart = { items: [], addItem(product, quantity = 1) { const existingItem = this.items.find(item => item.id === product.id); if (existingItem) { existingItem.quantity += quantity; } else { this.items.push({ ...product, quantity: quantity }); } }, removeItem(productId) { this.items = this.items.filter(item => item.id !== productId); }, updateQuantity(productId, quantity) { const item = this.items.find(item => item.id === productId); if (item) { item.quantity = quantity; } }, getTotal() { return this.items.reduce((total, item) => { return total + (item.price * item.quantity); }, 0); }, getItemCount() { return this.items.reduce((count, item) => count + item.quantity, 0); }, clear() { this.items = []; } }; // Game character const character = { name: "Hero", level: 1, health: 100, maxHealth: 100, mana: 50, maxMana: 50, stats: { strength: 10, agility: 8, intelligence: 12 }, inventory: [], levelUp() { this.level++; this.maxHealth += 20; this.maxMana += 10; this.health = this.maxHealth; this.mana = this.maxMana; // Increase stats this.stats.strength += 2; this.stats.agility += 1; this.stats.intelligence += 3; }, takeDamage(amount) { this.health = Math.max(0, this.health - amount); return this.health === 0; // Return true if dead }, heal(amount) { this.health = Math.min(this.maxHealth, this.health + amount); }, addToInventory(item) { this.inventory.push(item); }, getCharacterInfo() { return { name: this.name, level: this.level, health: `${this.health}/${this.maxHealth}`, mana: `${this.mana}/${this.maxMana}`, stats: { ...this.stats } }; } };
Object Patterns
javascript// Factory function function createUser(name, email) { return { name: name, email: email, isActive: true, activate() { this.isActive = true; }, deactivate() { this.isActive = false; }, getInfo() { return `${this.name} (${this.email}) - ${this.isActive ? 'Active' : 'Inactive'}`; } }; } const user1 = createUser("Alice", "alice@example.com"); const user2 = createUser("Bob", "bob@example.com"); // Configuration object const appConfig = { api: { baseUrl: "https://api.example.com", timeout: 5000, retries: 3 }, ui: { theme: "light", language: "en", showNotifications: true }, features: { darkMode: true, betaFeatures: false, analytics: true }, get(path) { return path.split('.').reduce((obj, key) => obj?.[key], this); }, set(path, value) { const keys = path.split('.'); const lastKey = keys.pop(); const target = keys.reduce((obj, key) => obj[key], this); target[lastKey] = value; } }; // Usage console.log(appConfig.get('api.baseUrl')); // "https://api.example.com" appConfig.set('ui.theme', 'dark');
Common Mistakes
javascript// Mistake 1: Modifying objects unintentionally const settings = { theme: "light", lang: "en" }; const userSettings = settings; // Same reference! userSettings.theme = "dark"; console.log(settings.theme); // "dark" - original changed! // Fix: Create a copy const userSettings = { ...settings }; // Mistake 2: Using arrow functions for methods const obj = { name: "Test", greet: () => { console.log(`Hello, ${this.name}`); // 'this' is not obj! } }; // Fix: Use regular function or method shorthand const obj = { name: "Test", greet() { console.log(`Hello, ${this.name}`); // Works correctly } }; // Mistake 3: Assuming property order const obj = { b: 2, a: 1, c: 3 }; // Don't rely on property order in older JavaScript versions