Skip to main content

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:

    javascript
    const key = 'email'; user[key] = 'tim@mail.com';
  • or contains invalid characters:

    javascript
    user['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

WayMutates the original objectBest for
obj.key = valueYessimple cases
obj['key'] = valueYesdynamic keys
Object.assign()Yesbulk additions
{ ...obj, key: value }Nocreating a new object
Object.defineProperty()Yesspecial property configuration

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.