Adding and changing properties
Learn to add new properties and change existing ones.
Adding properties
You can add new properties to an object later. Just assign a value using dot or bracket notation.
const user = { name: 'Alex' };
user.age = 28;
user['city'] = 'Berlin';
// user: { name: 'Alex', age: 28, city: 'Berlin' }Even if the object is declared with const, its contents can change; const only blocks reassignment. This behavior is called mutation.
Changing properties
Changing an existing property's value uses the same assignment. You give a new value to the same key.
const user = { name: 'Alex', age: 28 };
user.age = 29;
// user.age is now 29The only difference between adding and changing is whether the key already exists on the object. JavaScript picks the right behavior automatically.
Exercise Update the product
Change the price property of the product object to 49. Then add a discount property set to 10. Finally print product with console.log.
Show example solution
const product = { name: 'Pen', price: 25 };
product.price = 49;
product.discount = 10;
console.log(product);
Test yourself
-
Correct way to add a property to user?
const user = { name: 'Alex' };- user.age = 28;
- user(age) = 28;
- user->age = 28;
- age.user = 28;
Show answer
user.age = 28; — Correct! Assigning with dot notation adds the property.
-
Update the score
const player = { name: 'Alex', score: 10 }; player.score ____ 20;Show answer
const player = { name: 'Alex', score: 10 }; player.score = 20; -
Match each operation
- user.age = 28
- add age
- user.age = 29
- change age
- user.age
- read age