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 19, 2024

In JavaScript, the 'const' keyword is used to declare a constant variable, which means the value of the variable cannot be changed once it is assigned. However, when it comes to objects, using 'const' does not make the object immutable. It only prevents the variable from being reassigned to a different object. This means that you can still modify the properties of a 'const' object, including adding new keys.

Here's how you can add a key to a 'const' object in JavaScript:

1. Using Object.assign()

You can use the Object.assign() method to create a new object with the additional key and value, while keeping the original object unchanged. Here's an example:

```javascript

const myConstObj = {key1: 'value1'};

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

console.log(newObj); // Output: {key1: 'value1', key2: 'value2'}

```

2. Using the spread operator (ES6)

In ES6, you can also use the spread operator to achieve the same result in a more concise way. Here's an example:

```javascript

const myConstObj = {key1: 'value1'};

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

console.log(newObj); // Output: {key1: 'value1', key2: 'value2'}

```

It's important to note that while these methods allow you to add new keys to a 'const' object, the original object remains unchanged. This means that the immutability of the original 'const' object is preserved, while still allowing you to work with the object in a flexible manner.

In conclusion, adding a key to a 'const' object in JavaScript is possible by creating a new object with the additional key and value, while keeping the original object unchanged. This allows you to work with 'const' objects in a way that maintains their immutability while still accommodating changes when necessary.

Recommend