Modelo

  • EN
    • English
    • Español
    • Français
    • Bahasa Indonesia
    • Italiano
    • 日本語
    • 한국어
    • Português
    • ภาษาไทย
    • Pусский
    • Tiếng Việt
    • 中文 (简体)
    • 中文 (繁體)

How to Add a Property to Object in JavaScript

Oct 20, 2024

Adding a new property to an object in JavaScript is a common operation that developers often need to perform. There are several ways to achieve this, and it's important to understand the different methods available. Whether you are working with plain objects or object constructors, the process of adding a property involves assigning a new key-value pair to the object. Here are some ways to do it:

1. Dot notation:

We can use the dot notation to add a property to an object like this:

```

let obj = {};

obj.name = 'John';

```

2. Bracket notation:

Another way to add a property to an object is by using bracket notation:

```

let obj = {};

obj['age'] = 25;

```

3. Object.assign():

The Object.assign() method can be used to add properties to an object by merging multiple objects together:

```

let obj = {a: 1};

Object.assign(obj, {b: 2});

```

4. ES6 computed property names:

With ES6, we can also use computed property names to dynamically add properties to an object:

```

let key = 'newProp';

let obj = {[key]: 'someValue'};

```

5. Object.defineProperty():

For more advanced use cases, the Object.defineProperty() method can be used to add a new property with additional property descriptors:

```

let obj = {};

Object.defineProperty(obj, 'color', {

value: 'blue',

writable: true,

enumerable: true,

configurable: true

});

```

By understanding these different methods, you can choose the most suitable approach to add a property to an object in JavaScript based on your specific requirements. This will help you write cleaner and more efficient code, and enhance your overall coding skills.

Recommend