When working with JavaScript, you may come across situations where you need to add a key to a const object. While the const keyword in JavaScript prevents reassignment of the entire object, it does not prevent modification of the object's properties. This means you can still add, update, or delete keys from a const object. Here are a few techniques to achieve this:
1. Using Object.assign():
const obj = { key1: 'value1' };
const newObj = Object.assign({}, obj, { key2: 'value2' });
In this example, Object.assign() creates a new object newObj by combining the properties of the original obj and the new key-value pair. The original obj remains unchanged.
2. Using Spread Operator (ES6):
const obj = { key1: 'value1' };
const newObj = { ...obj, key2: 'value2' };
The spread operator (...) spreads the properties of the original obj into the new object newObj and adds the new key-value pair.
3. Using Square Bracket Notation:
const obj = { key1: 'value1' };
obj['key2'] = 'value2';
You can directly add a new key to the const object using square bracket notation. This method directly modifies the original object.
It's important to note that while these techniques allow you to add new keys to a const object, they do not prevent the modification of the existing keys. If you want to ensure that the object is completely immutable, you can use Object.freeze() to freeze the object, making it read-only. However, this is a shallow freeze and does not prevent nested objects or arrays within the const object from being modified.
In conclusion, adding a key to a const object in JavaScript is possible by using Object.assign(), the spread operator, or square bracket notation. These techniques provide flexibility while still maintaining the immutability of the object, depending on your specific requirements. It's important to understand the implications of modifying const objects and choose the appropriate approach based on the desired level of immutability.