Modelo

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

How to Add a Key to a Const Object in JavaScript

Oct 05, 2024

When working with JavaScript objects, you may come across the need to add new keys to a const object. While const provides immutability to the object reference, it does not restrict the object's properties from being modified. Therefore, it is possible to add new keys to a const object using various techniques.

One way to add a key to a const object is by using the spread operator. With the spread operator, you can create a new object by copying the existing key-value pairs of the const object and adding the new key-value pair. Here's an example:

```javascript

const originalObj = { key1: 'value1' };

const newObj = { ...originalObj, key2: 'value2' };

```

In this example, `newObj` will have both `key1` and `key2` as its keys with their respective values. While the original object remains unchanged, you have effectively added a new key to the const object.

Another approach to adding a key to a const object is by using the `Object.assign` method. This method allows you to merge multiple objects into a target object. Here's how you can use `Object.assign` to add a key to a const object:

```javascript

const originalObj = { key1: 'value1' };

const newObj = Object.assign({}, originalObj, { key2: 'value2' });

```

In this example, `newObj` will have both `key1` and `key2` as its keys with their respective values. Again, the original object remains const while you have successfully added a new key.

It's important to note that both of these approaches create a new object with the additional key-value pair while leaving the original const object unchanged. This means that the original const object still cannot have its existing keys modified or be reassigned to a completely new object, maintaining its immutability.

In conclusion, while a const object in JavaScript cannot have its reference reassigned, you can add new keys to it using the spread operator or `Object.assign` method. These techniques allow you to extend the functionality of const objects without violating their immutability. By understanding these methods, you can effectively work with const objects and add new keys as needed in your JavaScript applications.

Recommend