Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript ES6 `const a = {}` is mutable. Why? [duplicate]

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.

like image 610
Justin Avatar asked Jan 25 '16 01:01

Justin


2 Answers

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.
like image 122
Blixt Avatar answered Nov 16 '22 10:11

Blixt


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.

like image 6
Amadan Avatar answered Nov 16 '22 11:11

Amadan