How To Add Property To Object Javascript

In this blog post, we will discuss different ways to add properties to an object in JavaScript. Objects in JavaScript are key-value pairs, and their properties can be created, updated, or deleted easily. Here are three ways to add properties to an object:

  • Using the dot notation
  • Using the square bracket notation
  • Using the Object.defineProperty() method

1. Using the Dot Notation

The most common way to add a property to an object is by using the dot notation. To add a property to an object, you simply have to use the object name, followed by a dot and the property name. Assign a value to the property using the assignment operator (=).

const user = {};
user.name = 'John Doe';
user.age = 30;

In the example above, we have created an empty object called user. We then added two properties, name and age, using the dot notation.

2. Using the Square Bracket Notation

You can also add properties to an object using the square bracket notation. This method is useful when you need to use a variable or a string that contains special characters as a property name.

const user = {};
const propertyName = 'country';

user['name'] = 'John Doe';
user['age'] = 30;
user[propertyName] = 'USA';

In this example, we are using the square bracket notation to add properties to the user object. We have also used a variable propertyName to add a property called country.

3. Using the Object.defineProperty() method

The Object.defineProperty() method allows you to add a property to an object and define additional attributes, such as whether the property is enumerable, writable, or configurable.

const user = {};

Object.defineProperty(user, 'name', {
    value: 'John Doe',
    enumerable: true,
    writable: true,
    configurable: true
});

Object.defineProperty(user, 'age', {
    value: 30,
    enumerable: true,
    writable: true,
    configurable: true
});

In this example, we have used the Object.defineProperty() method to add properties to the user object. We have also set the enumerable, writable, and configurable attributes to true.

In conclusion, you can add properties to an object in JavaScript using the dot notation, square bracket notation, or the Object.defineProperty() method. The choice depends on your specific use case and requirements.