JavaScript Objects Basics
Objects are collections of key-value pairs that store related data.
What Are Objects?
// Without objects
let name = "John";
let age = 25;
// With objects — organized
let person = { name: "John", age: 25 };
Creating Objects
let person = { name: "John", age: 25, city: "NYC" };
let empty = {};
Accessing Properties
let person = { name: "John", age: 25 };
person.name; // dot notation — "John"
person["age"]; // bracket notation — 25
Tip: Use dot notation for static keys. Use bracket notation when the key is dynamic.
Adding and Modifying
let person = { name: "John" };
person.age = 25; // add
person.name = "Jane"; // modify
Deleting Properties
let person = { name: "John", age: 25 };
delete person.age;
console.log(person); // { name: "John" }
Checking Properties
let person = { name: "John", age: 25 };
"name" in person; // true
person.hasOwnProperty("name"); // true
Iterating Over Objects
let person = { name: "John", age: 25 };
Object.keys(person); // ["name", "age"]
Object.values(person); // ["John", 25]
Object.entries(person); // [["name", "John"], ["age", 25]]
for (let [key, val] of Object.entries(person)) {
console.log(`${key}: ${val}`);
}
Nested Objects
let person = {
name: "John",
address: { street: "123 Main St", city: "NYC" },
hobbies: ["reading", "gaming"]
};
person.address.city; // "NYC"
Remember: Keep nesting shallow — deep structures are hard to maintain.
Complete Example: User Profile
let userProfile = {
username: "john_doe",
age: 25,
address: { city: "NYC", state: "NY" },
settings: { theme: "dark", notifications: true }
};
console.log(`City: ${userProfile.address.city}`); // "NYC"
console.log(`Theme: ${userProfile.settings.theme}`); // "dark"
Best Practices
- Use descriptive keys — meaningful property names
- Use
const— if the object won’t be reassigned - Keep it flat — avoid deep nesting
- Validate data — check for required properties
Common Mistakes
- Forgetting quotes on keys — keys with spaces need quotes
- Accessing non-existent properties — returns undefined
- Modifying
constobjects — you can change properties, just not reassign - Using
for...inon arrays — usefor...ofinstead