Using JavaScript ES6, I am surprised that doing:
const a = {};
a.foo = 'bar';
a.foo = 'car';
Is valid. Why is this? I would have assumed const
would mean you cannot change the a
empty object and apply new properties. Even further, I would also have assumed you cannot change the value of a property of a
once it is set.
Only the variable assignment is constant. Any objects or arrays referenced stay mutable.
const a = {one: 1};
a.three = 3; // this is ok.
a = {two: 2}; // this doesn't work.
What you can do is use Object.freeze
:
const a = {one: 1};
Object.freeze(a);
a.three = 3; // silently fails.
// a is still {one: 1} here.
No, const a
means you cannot change the value of the variable a
. Its value is always the same object; changing properties of an object doesn't make it into a different object.
Using an analogy, I am the same Person
whether amadan.jacket = null
or amadan.jacket = "Heavy Winter Jacket"
. amadan
is constant.
To make the properties immutable, you would either have to make the properties explicitly readonly by writable: false
, or use Object.freeze
or Object.seal
(differences) to make the entire object immutable.
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