In JavaScript, the 'const' keyword is used to declare a constant reference to a value. When you use 'const' to declare an object, the reference to the object is constant, meaning you cannot reassign the variable to a different object. However, this does not mean that the object itself is immutable. You can still modify the properties of the object, including adding new keys. Here's how you can add a new key to a const object in JavaScript without breaking the immutability of const.
```javascript
const myConstObj = { key1: 'value1' };
// Method 1: Object.assign()
const updatedObj1 = Object.assign({}, myConstObj, { key2: 'value2' });
// Method 2: Spread operator
const updatedObj2 = { ...myConstObj, key2: 'value2' };
console.log(updatedObj1); // Output: { key1: 'value1', key2: 'value2' }
console.log(updatedObj2); // Output: { key1: 'value1', key2: 'value2' }
```
In the above code, we have a const object 'myConstObj' with one key 'key1'. We then use two different methods to add a new key 'key2' with the value 'value2' to the object. Both 'Object.assign()' and the spread operator (...) create a new object with the existing properties from 'myConstObj' and the new property 'key2'. The original 'myConstObj' remains unchanged, and we now have a new object with the added key.
It's important to note that while you can add new keys to a const object using the above methods, you cannot reassign the object itself to a different value. For example, the following code will throw an error:
```javascript
myConstObj = { key3: 'value3' }; // Error: Assignment to constant variable.
```
To summarize, while 'const' provides a constant reference to an object, it does not make the object itself immutable. You can add new keys to a const object using 'Object.assign()' or the spread operator without breaking the immutability of 'const'. This allows you to modify the properties of the object while keeping the reference constant.