Despite referring to ES6 specifications that emphasize the immutability of constants, JavaScript allows seemingly contradicting actions on constant objects. When assigning a different value to a constant object, it remains unchanged, yet adding or removing elements within the object is seemingly possible.
According to the MDN documentation, "constant cannot change through re-assignment" and "constant cannot be re-declared." Crucially, this implies that the reference to the object is constant, not the object itself. You cannot assign a new object to the constant variable, but you can modify the contents of the object.
Consider the following code snippet:
const myArray = []; myArray.push(1); console.log(myArray); // Output: [1]
In this case, the reference to the myArray array remains unchanged as it is still pointing to the same array object. However, the push() operation adds an element to the array, altering its contents but not violating the constant semantics.
Similarly, you can add properties to a constant object without modifying the reference:
const myObject = {}; myObject.foo = 'bar'; console.log(myObject); // Output: {foo: "bar"}
It's important to distinguish between re-assignment and modification. While re-assignment creates a new reference, modification operates on the same object reference. In the case of constant objects, re-assignment is prohibited to ensure immutability, while modification of the object's contents is still allowed.
The above is the detailed content of How Can JavaScript Constants Be Modified If They\'re Immutable?. For more information, please follow other related articles on the PHP Chinese website!