New property in an object
1. Via a dot (.)
javascript
const user = { name: 'Tim' };
user.age = 25; // add a new property
console.log(user);
// { name: 'Tim', age: 25 }Works if the property name is a valid identifier (no spaces, no special characters, does not start with a digit).
2. Via square brackets ([])
javascript
const user = { name: 'Tim' };
user['city'] = 'Kyiv';
console.log(user);
// { name: 'Tim', city: 'Kyiv' }This way works well when:
-
the key is stored in a variable:
javascriptconst key = 'email'; user[key] = 'tim@mail.com'; -
or contains invalid characters:
javascriptuser['favorite color'] = 'blue';
3. With Object.assign()
javascript
const user = { name: 'Tim' };
Object.assign(user, { age: 25, city: 'Kyiv' });
console.log(user);
// { name: 'Tim', age: 25, city: 'Kyiv' }You can add several properties at once. The method mutates the original object.
4. With the spread operator (...) - creates a new object
javascript
const user = { name: 'Tim' };
const updatedUser = { ...user, age: 25 };
console.log(updatedUser);
// { name: 'Tim', age: 25 }The original object is not changed - a new copy is created (an immutable approach).
5. Via Object.defineProperty() (rarer, but flexible)
javascript
const user = {};
Object.defineProperty(user, 'age', {
value: 25,
writable: true,
enumerable: true,
configurable: true
});
console.log(user); // { age: 25 }Lets you fine-tune the property: for example, make it read-only or hidden when iterated over.
SUMMARY
| Way | Mutates the original object | Best for |
|---|---|---|
obj.key = value | Yes | simple cases |
obj['key'] = value | Yes | dynamic keys |
Object.assign() | Yes | bulk additions |
{ ...obj, key: value } | No | creating a new object |
Object.defineProperty() | Yes | special property configuration |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.