Why Object Const Can Be Changed After Definition In Javascript?
Solution 1:
A variable declared with const
means one thing: the standalone variable name cannot be reassigned with =
later.
In contrast, o.a = 5;
is not reassigning the variable name - it's mutating the content of the object, but it's not changing what the o
variable points to in memory.
To prevent reassignment of a variable name, use const
. To prevent mutation of an object is something entirely different - for that, you'd need something like Object.freeze
or manipulate objects using immutable-js.
Solution 2:
In the first case, a
is const
and cannot be reassigned. In the second and third, the object o
is const
so that object cannot be assigned another value, but its properties are not const
. See here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
The
const
declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.
Solution 3:
const
variables aren't enforced to be immutable.
From MDN:
Constants are block-scoped, much like variables defined using the let statement. The value of a constant can't be changed through reassignment, and it can't be redeclared.
Emphasis mine.
o.a = 5
isn't reassigning o
; it's reassigning a property in o
.
Solution 4:
For adding more information from the other answers, if you want to define a constant object property. You can try these ways:
const o = {
geta() {
return1;
}
};
o.a = 2;
// 1console.log(o.a);
const o2 = {};
Object.defineProperty(o2, 'a', {
value: 1,
writable: false,
enumerable: true,
configurable: true
});
o2.a = 2;
// 1console.log(o2.a);
Post a Comment for "Why Object Const Can Be Changed After Definition In Javascript?"