In JavaScript:
const a = 6;
a = 2; // Error
const o = {};
o = 7; // Error
o.a = 5; // Good. Why?
const o = {a:1};
o.a = 2; // Good. Why?
I found people sometimes define a const object but later change its value. Why a const can be changed after its definition?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With