How to add a new property to an object?

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

Brief Answer

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.


Full Answer

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.

Ways to Add Properties

1. Dot Notation

The simplest and most commonly used way:

const user = { name: 'John' };
user.age = 25; // Add age property

2. Square Brackets

Allows using variables as keys:

const user = { name: 'John' };
user['city'] = 'Moscow'; // Add city property

3. Object.assign

Adds multiple properties at once:

const user = { name: 'John' };
Object.assign(user, { age: 25, city: 'Moscow' });

4. Spread Operator

Creates new object with added properties:

const user = { name: 'John' };
const newUser = { ...user, age: 25 };

When to Use What

Dot Notation

// When key is simple string without spaces
user.age = 25;
user.isActive = true;

Square Brackets

// When key is variable or contains spaces
const key = 'user-age';
user[key] = 25;
user['user name'] = 'John';

Object.assign

// When need to add many properties
Object.assign(user, {
  age: 25,
  city: 'Moscow',
  isActive: true
});

Spread Operator

// When don't want to change original object
const newUser = { ...user, age: 25 };

Simple Rules

Use Dot Notation When:

  • Key is simple word without spaces
  • Key is known in advance

Use Square Brackets When:

  • Key is stored in variable
  • Key contains spaces or special symbols
  • Key is formed dynamically

Common Mistakes

1. Wrong Method Choice

// ❌ Complex way for simple task
const user = { name: 'John' };
Object.assign(user, { age: 25 }); // Extra code
 
// ✅ Simple way
user.age = 25;

2. Trying to Use Dot Notation with Variables

// ❌ Doesn't work
const key = 'user-age';
user.key = 25; // Creates 'key' property, not 'user-age'
 
// ✅ Correct
user[key] = 25; // Creates 'user-age' property

Important Points

  1. Mutating methods — dot notation and square brackets change original object
  2. Non-mutating methods — spread and Object.assign can create new objects
  3. Dynamic keys — only square brackets allow using variables as keys
  4. Simplicity — dot notation is simplest and most readable way
  5. Flexibility — square brackets give more possibilities

Adding 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 💪