Objects
Key-value pairs. The fundamental building block of JavaScript.
Creating Objects
Key-value pairs inside curly braces.
// Object literal (most common):
const user = {
name: "Alice",
age: 28,
isAdmin: false,
};
// Empty object:
const empty = {};
// Shorthand — variable names become keys:
const name = "Bob";
const age = 25;
const bob = { name, age };
// { name: "Bob", age: 25 }const user = {
name:"Alice"
age:28
isAdmin:false
}
Accessing Properties
Dot notation or bracket notation.
const user = { name: "Alice", age: 28 };
user.name; // "Alice"
user.age; // 28
user.email; // undefined (doesn't exist)
// Clean and readable — use when:
// • Key is a valid identifier
// • Key is known at write timeModifying Objects
Add, update, and delete properties.
const user = { name: "Alice", age: 28 };
// Update existing property:
user.age = 29;
// Add new property:
user.email = "alice@example.com";
// Delete a property:
delete user.email;
console.log(user);
// { name: "Alice", age: 29 }⚠️ constprevents reassigning the variable, but you can still modify the object's properties. Use Object.freeze() to make an object truly immutable.
Nested Objects
Objects inside objects — common for structured data.
const user = {
name: "Alice",
address: {
street: "123 Main St",
city: "Springfield",
country: "US",
},
hobbies: ["reading", "coding"],
};
// Access nested properties:
user.address.city; // "Springfield"
user.hobbies[0]; // "reading"
// Optional chaining (safe access):
user.address?.zip; // undefined (no error)
user.contact?.email; // undefined (no error)
// Without ?. → TypeError if contact is undefinedChecking Properties
Iterate and inspect object contents.
const user = { name: "Alice", age: 28, role: "dev" };
// Check if property exists:
"name" in user; // true
"email" in user; // false
user.hasOwnProperty("age"); // true
// Get all keys, values, or entries:
Object.keys(user); // ["name", "age", "role"]
Object.values(user); // ["Alice", 28, "dev"]
Object.entries(user); // [["name","Alice"], ["age",28], ...]
// Loop through properties:
for (const [key, value] of Object.entries(user)) {
console.log(`${key}: ${value}`);
}References
Objects are stored by reference, like arrays.
const a = { x: 1 };
const b = a;
b.x = 99;
console.log(a.x); // 99 ← same object!Assigning an object to another variable creates a reference — both point to the same data.
💡 b = a does NOT copy the object
1 / 3
FAQ
Common questions about objects.