Ad

JavaScript ES6 `const A = {}` Is Mutable. Why?

- 1 answer

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.

Ad

Answer

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.
Ad
source: stackoverflow.com
Ad