Home >Web Front-end >JS Tutorial >Why Can I Modify a Constant Object in JavaScript?
Const Objects in JavaScript: Understanding Immutable Properties
Despite the constant keyword in ES6, you can seemingly modify constant objects in JavaScript. This can be puzzling, especially considering the spec's claim of immutability. So, what's going on?
Firstly, as the MDN documentation clarifies, the constant keyword prohibits reassignment and re-declaration of the constant itself. However, when modifying an object or array, you're not re-assigning or re-declaring it. Instead, you're simply manipulating the object's properties or the array's elements.
Consider the examples:
const x = {}; x.foo = 'bar'; // Adds a property to an existing object
const y = []; y.push('foo'); // Appends an element to an existing array
In both cases, the constant object (x) and array (y) remain the same references. You're not changing the object itself, but instead adding or modifying its elements. This is allowed because it doesn't violate the immutability of the constant reference.
However, reassignment or re-declaration is still prevented:
const x = {}; x = {foo: 'bar'}; // Error: Reassigning a constant
const y = ['foo']; const y = ['bar']; // Error: Re-declaring a constant
Therefore, while you can modify the properties of a constant object or the elements of a constant array, you cannot replace or redefine the reference itself.
The above is the detailed content of Why Can I Modify a Constant Object in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!