JavaScript ES6 `const a = {}` changed. What for?

Using JavaScript ES6, I am surprised that:

const a = {};
a.foo = 'bar';
a.foo = 'car';

Valid. Why is this? I would suggest that constmeans you cannot change an empty object aand apply new properties. Moreover, I also suggested that you cannot change the value of a property aafter setting it.

0
source share
2 answers

Only variable assignment is constant. Any objects or arrays referenced remain 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.
+7
source

, const a , a. ; .

, Person, amadan.jacket = null amadan.jacket = "Heavy Winter Jacket". amadan .

, readonly writable: false, Object.freeze Object.seal () .

+4

All Articles