Change property value in an object can be done the same ways as adding new properties: through dot notation or square brackets. If property already exists, it will simply get a new value.
Changing property values is one of the most common operations with objects in JavaScript. It’s simple and intuitive.
The simplest and most commonly used way:
const user = { name: 'John', age: 25 };
user.name = 'Peter'; // Change name property value
user.age = 30; // Change age property valueAllows using variables and complex keys:
const user = { name: 'John', age: 25 };
user['name'] = 'Peter'; // Same as dot notationconst car = { brand: 'Toyota', year: 2020 };
car.brand = 'Honda'; // Change brand
car.year = 2021; // Change yearconst user = {
name: 'John',
address: { city: 'Moscow', street: 'Lenina' }
};
user.address.city = 'Saint Petersburg'; // Change city// For simple keys without spaces
user.name = 'New name';
car.model = 'New model';// For variables or complex keys
const key = 'name';
user[key] = 'New name';
// For keys with spaces
user['user name'] = 'John';const original = { name: 'John' };
const copy = original;
copy.name = 'Peter';
console.log(original.name); // 'Peter' - original object changed too!const user = { name: 'John' };
user.age = 25; // If property didn't exist - it will be created// ❌ Error with wrong usage
const user = { name: 'John' };
const key = 'nonexistent';
user.key = 'value'; // Creates 'key' property, not value of key variable
// ✅ Correct
user[key] = 'value'; // Creates 'nonexistent' property// ❌ Unexpected changes
function changeUser(user) {
user.name = 'New name'; // Changes original object!
}
const originalUser = { name: 'John' };
changeUser(originalUser);
console.log(originalUser.name); // 'New name'Changing object properties is a basic operation in JavaScript. Understanding simple rules helps avoid mistakes and write predictable code.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪