Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 1 of 11
Object Literals & Properties
Objects are collections of key-value pairs. They represent real-world entities - a user, a product, a settings config. Objects are the most fundamental data structure in JavaScript after arrays.
Object Basics
- Object literal - const user = { name: 'Alice', age: 25 };
- Access - Dot notation: user.name. Bracket notation: user['name']
- Add/modify - user.email = 'alice@email.com'; or user['phone'] = '9876543210';
- Delete - delete user.phone; removes the property
- Shorthand - const name = 'Alice'; const user = { name }; (same as { name: name })
- Computed keys - const key = 'age'; const user = { [key]: 25 }; creates { age: 25 }
- Nested - Objects inside objects: user.address.city
Objects Code
// Object literal
const user = {
name: "Alice",
age: 25,
email: "alice@email.com",
isAdmin: false,
hobbies: ["coding", "reading"],
address: {
city: "Mumbai",
country: "India"
}
};
// Access
console.log(user.name); // "Alice"
console.log(user["age"]); // 25
console.log(user.address.city); // "Mumbai"
console.log(user.hobbies[0]); // "coding"
// Dynamic key access
const key = "email";
console.log(user[key]); // "alice@email.com"
// Add & modify
user.phone = "9876543210";
user.age = 26;
// Shorthand property
const name = "Bob";
const age = 30;
const bob = { name, age }; // same as { name: name, age: age }
console.log(bob); // { name: "Bob", age: 30 }
// Check if property exists
console.log("name" in user); // true
console.log(user.hasOwnProperty("email")); // trueTip
Tip
Use optional chaining (?.) for safe nested access: user?.address?.city returns undefined instead of crashing if address is missing. This is essential when working with API data where properties may not exist.
Object Literals & Properties in JavaScript
Common Mistake
Warning
Accessing nested properties without checking if the parent exists. user.address.city crashes with TypeError if address is undefined. Always use optional chaining (user?.address?.city) or check first: if (user.address) { }.
Practice Task
Note
Create a user profile object: (1) Include name, age, email, hobbies array, and nested address object. (2) Access properties using both dot and bracket notation. (3) Add a new property dynamically. (4) Use 'in' operator and hasOwnProperty to check existence.
Quick Quiz
Key Takeaways
- Objects are collections of key-value pairs.
- Object literal - const user = { name: 'Alice', age: 25 };
- Access - Dot notation: user.name. Bracket notation: user['name']
- Add/modify - user.email = 'alice@email.com'; or user['phone'] = '9876543210';
Finished this lesson?