How to change the value of a property in an object?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Easy
#JavaScript #Objects #JS Basics

Brief Answer

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.


Full Answer

Changing property values is one of the most common operations with objects in JavaScript. It’s simple and intuitive.

Main Ways to Change

1. Dot Notation

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 value

2. Square Brackets

Allows using variables and complex keys:

const user = { name: 'John', age: 25 };
user['name'] = 'Peter'; // Same as dot notation

Simple Examples

Changing Simple Values

const car = { brand: 'Toyota', year: 2020 };
car.brand = 'Honda'; // Change brand
car.year = 2021; // Change year

Changing Nested Objects

const user = { 
  name: 'John', 
  address: { city: 'Moscow', street: 'Lenina' } 
};
 
user.address.city = 'Saint Petersburg'; // Change city

When to Use What

Dot Notation

// For simple keys without spaces
user.name = 'New name';
car.model = 'New model';

Square Brackets

// For variables or complex keys
const key = 'name';
user[key] = 'New name';
 
// For keys with spaces
user['user name'] = 'John';

Important Points

1. Objects Passed by Reference

const original = { name: 'John' };
const copy = original;
copy.name = 'Peter';
console.log(original.name); // 'Peter' - original object changed too!

2. Creating New Properties

const user = { name: 'John' };
user.age = 25; // If property didn't exist - it will be created

Common Mistakes

1. Trying to Change Non-existent Property Through Variable

// ❌ 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

2. Misunderstanding Reference Nature

// ❌ Unexpected changes
function changeUser(user) {
  user.name = 'New name'; // Changes original object!
}
 
const originalUser = { name: 'John' };
changeUser(originalUser);
console.log(originalUser.name); // 'New name'

Simple Rules

  1. Dot notation — for simple keys
  2. Square brackets — for variables and complex keys
  3. Careful with references — changes visible everywhere there’s a reference
  4. Non-existent properties — created automatically
  5. Nested objects — changed by the same principle

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 💪