Add property to object can be done in several ways: dot notation, square brackets, Object.assign, or spread operator. The simplest and most commonly used are dot notation and square brackets.
In JavaScript there are several ways to add a new property to an existing object. All of them are simple, but have their own features.
The simplest and most commonly used way:
const user = { name: 'John' };
user.age = 25; // Add age propertyAllows using variables as keys:
const user = { name: 'John' };
user['city'] = 'Moscow'; // Add city propertyAdds multiple properties at once:
const user = { name: 'John' };
Object.assign(user, { age: 25, city: 'Moscow' });Creates new object with added properties:
const user = { name: 'John' };
const newUser = { ...user, age: 25 };// When key is simple string without spaces
user.age = 25;
user.isActive = true;// When key is variable or contains spaces
const key = 'user-age';
user[key] = 25;
user['user name'] = 'John';// When need to add many properties
Object.assign(user, {
age: 25,
city: 'Moscow',
isActive: true
});// When don't want to change original object
const newUser = { ...user, age: 25 };// ❌ Complex way for simple task
const user = { name: 'John' };
Object.assign(user, { age: 25 }); // Extra code
// ✅ Simple way
user.age = 25;// ❌ Doesn't work
const key = 'user-age';
user.key = 25; // Creates 'key' property, not 'user-age'
// ✅ Correct
user[key] = 25; // Creates 'user-age' propertyAdding properties is one of the basic operations in JavaScript. Understanding different ways helps write cleaner and more efficient code.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪