Adding Properties to Existing Objects
What you'll learn: How to add new properties to objects after they're created, making them flexible and dynamic.
Objects Can Grow
Unlike some programming languages where structures are fixed, JavaScript objects are like notebooks where you can add new pages anytime. Once you've created an object, you're not stuck with its initial properties — you can extend it on the fly.
The Core Idea
You add new properties using the same notation you've already learned for accessing properties: dot notation or bracket notation. If you assign to a property that doesn't exist yet, JavaScript simply creates it.
Using Dot Notation
const user = { name: "Alice" };
user.age = 25;
console.log(user); // { name: "Alice", age: 25 }
Using Bracket Notation
const user = { name: "Alice" };
user["email"] = "alice@example.com";
console.log(user); // { name: "Alice", age: 25, email: "alice@example.com" }
When Each Notation Shines
Use dot notation for simple, known property names. Use bracket notation when:
- The property name comes from a variable
- The property name has special characters or spaces
- You're computing the property name dynamically
const car = { brand: "Toyota" };
const propName = "year";
car[propName] = 2020; // Adds the property "year"
console.log(car.year); // 2020
Think of It Like...
Imagine an object as a contact card. You can always add new fields — phone number, birthday, notes — even after the card was printed. JavaScript objects work the same way.
Key Takeaway: You can add properties to any object after creation using dot or bracket notation — if the property doesn't exist, JavaScript creates it automatically.